diff --git a/app/src/main/kotlin/io/treehouses/remote/network/BluetoothChatService.kt b/app/src/main/kotlin/io/treehouses/remote/network/BluetoothChatService.kt index 7588291c4..b3da4ed1d 100644 --- a/app/src/main/kotlin/io/treehouses/remote/network/BluetoothChatService.kt +++ b/app/src/main/kotlin/io/treehouses/remote/network/BluetoothChatService.kt @@ -151,15 +151,25 @@ class BluetoothChatService @JvmOverloads constructor(handler: Handler? = null, a stopForeground(true) val preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext) + if (mDevice != null && !bNoReconnect && preferences.getBoolean("reconnectBluetooth", true)) { - connect(mDevice, true) + try { + connect(mDevice, true) + } catch (e: Exception) { + e.printStackTrace() + resetConnectionState() + } } else { - state = Constants.STATE_NONE - updateUserInterfaceTitle() - start() + resetConnectionState() } } + private fun resetConnectionState() { + state = Constants.STATE_NONE + updateUserInterfaceTitle() + start() + } + private inner class ConnectThread(private val mmDevice: BluetoothDevice?, secure: Boolean) : Thread() { private val mmSocket: BluetoothSocket? private val mSocketType: String @@ -208,17 +218,30 @@ class BluetoothChatService @JvmOverloads constructor(handler: Handler? = null, a override fun run() { val buffer = ByteArray(10000) var bytes: Int - var out: String - while (true) { - try { - bytes = mmInStream?.read(buffer) ?: 0 - out = String(buffer, 0, bytes) - mHandler?.obtainMessage(Constants.MESSAGE_READ, bytes, -1, out)?.sendToTarget() - } catch (e: IOException) { - e.printStackTrace() - connectionLost() - break + + try { + while (true) { + try { + if ((mmInStream?.available() ?: 0) > 0) { + bytes = mmInStream?.read(buffer) ?: -1 + if (bytes == -1) { + break + } + + val out = String(buffer, 0, bytes) + mHandler?.obtainMessage(Constants.MESSAGE_READ, bytes, -1, out)?.sendToTarget() + } else { + sleep(50) + } + } catch (e: IOException) { + e.printStackTrace() + break + } } + } catch (e: Exception) { + e.printStackTrace() + } finally { + connectionLost() } } @@ -228,6 +251,7 @@ class BluetoothChatService @JvmOverloads constructor(handler: Handler? = null, a mHandler?.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)?.sendToTarget() } catch (e: IOException) { e.printStackTrace() + connectionLost() } } @@ -254,4 +278,4 @@ class BluetoothChatService @JvmOverloads constructor(handler: Handler? = null, a this@BluetoothChatService.updateUserInterfaceTitle() } } -} \ No newline at end of file +}