@@ -147,12 +147,19 @@ class BluetoothChatService @JvmOverloads constructor(handler: Handler? = null, a
147147 }
148148
149149 private fun connectionLost () {
150- callHandler(" Device connection was lost" )
151150 stopForeground(true )
152151
153152 val preferences = PreferenceManager .getDefaultSharedPreferences(applicationContext)
153+
154154 if (mDevice != null && ! bNoReconnect && preferences.getBoolean(" reconnectBluetooth" , true )) {
155- connect(mDevice, true )
155+ try {
156+ connect(mDevice, true )
157+ } catch (e: Exception ) {
158+ e.printStackTrace()
159+ state = Constants .STATE_NONE
160+ updateUserInterfaceTitle()
161+ start()
162+ }
156163 } else {
157164 state = Constants .STATE_NONE
158165 updateUserInterfaceTitle()
@@ -208,17 +215,30 @@ class BluetoothChatService @JvmOverloads constructor(handler: Handler? = null, a
208215 override fun run () {
209216 val buffer = ByteArray (10000 )
210217 var bytes: Int
211- var out : String
212- while (true ) {
213- try {
214- bytes = mmInStream?.read(buffer) ? : 0
215- out = String (buffer, 0 , bytes)
216- mHandler?.obtainMessage(Constants .MESSAGE_READ , bytes, - 1 , out )?.sendToTarget()
217- } catch (e: IOException ) {
218- e.printStackTrace()
219- connectionLost()
220- break
218+
219+ try {
220+ while (true ) {
221+ try {
222+ if ((mmInStream?.available() ? : 0 ) > 0 ) {
223+ bytes = mmInStream?.read(buffer) ? : - 1
224+ if (bytes == - 1 ) {
225+ break
226+ }
227+
228+ val out = String (buffer, 0 , bytes)
229+ mHandler?.obtainMessage(Constants .MESSAGE_READ , bytes, - 1 , out )?.sendToTarget()
230+ } else {
231+ sleep(50 )
232+ }
233+ } catch (e: IOException ) {
234+ e.printStackTrace()
235+ break
236+ }
221237 }
238+ } catch (e: Exception ) {
239+ e.printStackTrace()
240+ } finally {
241+ connectionLost()
222242 }
223243 }
224244
@@ -228,6 +248,7 @@ class BluetoothChatService @JvmOverloads constructor(handler: Handler? = null, a
228248 mHandler?.obtainMessage(Constants .MESSAGE_WRITE , - 1 , - 1 , buffer)?.sendToTarget()
229249 } catch (e: IOException ) {
230250 e.printStackTrace()
251+ connectionLost()
231252 }
232253 }
233254
0 commit comments