1.重点在于资源释放,BluetoothGatt的close方法一定要写在BluetoothGattCallback的onConnectionStateChange回调方法的newState为BluetoothProfile.STATE_DISCONNECTED的状态下,即调用BluetoothGatt的disconnect()方法触发的BluetoothProfile.STATE_DISCONNECTED状态下,否则资源无法释放.调用BluetoothGatt的disconnect()方法时一定要在主线程中,否则可能出现关不掉的可能.
2.下面的为网上都可以找到的
2.1清除蓝牙缓存方法,通过反射机制调用,注意的是此方法需要在BluetoothGatt的close方法之前调用,即调用了清除缓存的方法,就可以调用close方法.
/** * Clears the internal cache and forces a refresh of the services from the * remote device. */
public static boolean refreshDeviceCache(BluetoothGatt mBluetoothGatt) {
if (mBluetoothGatt !=null) {
try {
BluetoothGatt localBluetoothGatt = mBluetoothGatt;
Method localMethod = localBluetoothGatt.getClass().getMethod("refresh",new Class[0]);
if (localMethod !=null) {
boolean bool = ((Boolean) localMethod.invoke(localBluetoothGatt,new Object[0])).booleanValue();
return bool;
}
}catch (Exception localException) {
localException.printStackTrace();
Log.i(MyConstant.TAGBLUETOOTH,"An exception occured while refreshing device");
}
}
return false;
}
2.2资源释放关键地方
@Override
publicvoidonConnectionStateChange(BluetoothGatt gatt, intstatus, intnewState) {
String intentAction;
if(status == BluetoothGatt.GATT_SUCCESS) {
if(newState == BluetoothProfile.STATE_CONNECTED) {
intentAction = BluetoothConstants.ACTION_GATT_CONNECTED;
mBLEConnectionState = BluetoothConstants.BLE_STATE_CONNECTED;
broadcastUpdate(intentAction);
Log.i(TAG, "Connected to GATT server.");
Log.i(TAG, "Attempting to start service discovery:"+ mBluetoothGatt.discoverServices());
} elseif(newState == BluetoothProfile.STATE_DISCONNECTED) {
intentAction = BluetoothConstants.ACTION_GATT_DISCONNECTED;
mBLEConnectionState = BluetoothConstants.BLE_STATE_DISCONNECTED;
close(); // 防止出现status 133
Log.i(TAG, "Disconnected from GATT server.");
broadcastUpdate(intentAction);
}
} else{
Log.d(TAG, "onConnectionStateChange received: "+ status);
intentAction = BluetoothConstants.GATT_STATUS_133;
mBLEConnectionState = BluetoothConstants.BLE_STATE_DISCONNECTED;
close(); // 防止出现status 133
broadcastUpdate(intentAction);
connect(reConnectAddress);
}
}
网友评论