Fixed possible crash in Bluetooth code

This commit is contained in:
Felix Ableitner 2016-09-24 18:59:24 +09:00
parent d1768ea8b4
commit a857002fa9

View file

@ -12,18 +12,26 @@ class BluetoothConnectThread(device: Device, onConnected: (Device, BluetoothSock
private val Tag = "ConnectThread" private val Tag = "ConnectThread"
private val socket = private val socket = try {
device.btDevice.get.createInsecureRfcommSocketToServiceRecord(BluetoothInterface.AppUuid) Option(device.btDevice.get.createInsecureRfcommSocketToServiceRecord(BluetoothInterface.AppUuid))
} catch {
case e: IOException =>
Log.w(Tag, "Failed to open Bluetooth connection", e)
None
}
override def run(): Unit = { override def run(): Unit = {
if (socket.isEmpty)
return
Log.i(Tag, "Connecting to " + device.toString) Log.i(Tag, "Connecting to " + device.toString)
try { try {
socket.connect() socket.get.connect()
} catch { } catch {
case e: IOException => case e: IOException =>
Log.v(Tag, "Failed to connect to " + device.toString, e) Log.v(Tag, "Failed to connect to " + device.toString, e)
try { try {
socket.close() socket.get.close()
} catch { } catch {
case e2: IOException => case e2: IOException =>
Log.e(Tag, "Failed to close socket", e2) Log.e(Tag, "Failed to close socket", e2)
@ -32,7 +40,7 @@ class BluetoothConnectThread(device: Device, onConnected: (Device, BluetoothSock
} }
Log.i(Tag, "Successfully connected to device " + device.name) Log.i(Tag, "Successfully connected to device " + device.name)
onConnected(new Device(device.btDevice.get, true), socket) onConnected(new Device(device.btDevice.get, true), socket.get)
} }
} }