我正在开发一款利用
Android 4.3新蓝牙BLE API的应用程序.
我使用了Android 4.2的三星BLE堆栈,它工作正常,即使稳定性可能更好.
现在有4.3,对于每个客户端连接,我们有一个BluetoothGatt类的实例.
也就是说,我通过呼叫连接到BLE设备
BluetoothGatt gatt = device.connectGatt(this, true, callbacks);
这些BluetoothGatt对象是用于实际与设备交互的对象.
由于我想连接到多个设备并与之交互,我将HashMap中的BluetoothGatt实例缓存定义为我的服务的私有属性:
private HashMap devicesGatts
= new HashMap();
密钥是设备地址.
然后,每当我想要连接到设备时,我都会从这个HashMap中拉出BluetoothGatt实例:
public BluetoothGatt connectGatt(final BluetoothDevice device){
if(device == null){
return null;
}
String adr = device.getAddress();
BluetoothGatt gatt = devicesGatts.get(adr);
if(gatt == null){
gatt = device.connectGatt(this, true, mGattCallbacks);
} else {
BluetoothDevice gattDevice = gatt.getDevice();
if(gattDevice != null && adr.equals(gattDevice.getAddress())){
gatt.connect(); // PROBLEM APPEARS HERE
} else {
gatt = device.connectGatt(this, true, mGattCallbacks);
}
}
devicesGatts.put(adr, gatt);
return gatt;
}
问题是,有时,如果设备尝试通过调用gatt.connect()通过其缓存的BluetoothGatt实例重新连接,我会收到一个名为DeadObjectException的错误(不是致命).
当我暂停应用程序并重新启动蓝牙芯片,然后恢复应用程序时,就会发生这种情况.
在发生这种情况之后我不能使用缓存实例,我并不感到惊讶,但我想知道如何捕获该异常或在它发生之前检测它.
这是堆栈跟踪:
02-18 10:43:51.884: E/BluetoothGatt(23312): android.os.DeadObjectException
02-18 10:43:51.884: E/BluetoothGatt(23312): at android.os.BinderProxy.transact(Native Method)
02-18 10:43:51.884: E/BluetoothGatt(23312): at android.bluetooth.IBluetoothGatt$Stub$Proxy.clientConnect(IBluetoothGatt.java:841)
02-18 10:43:51.884: E/BluetoothGatt(23312): at android.bluetooth.BluetoothGatt.connect(BluetoothGatt.java:759)
02-18 10:43:51.884: E/BluetoothGatt(23312): at MYSERVICE.connectGatt(...)
异常是由本机方法引发的,但蓝牙堆栈类不会引发异常.
我怎么能抓到它?