1.重點在于資源釋放,BluetoothGatt的close方法一定要寫在BluetoothGattCallback的onConnectionStateChange回調(diào)方法的newState為BluetoothProfile.STATE_DISCONNECTED的狀態(tài)下,即調(diào)用BluetoothGatt的disconnect()方法觸發(fā)的BluetoothProfile.STATE_DISCONNECTED狀態(tài)下,否則資源無法釋放.調(diào)用BluetoothGatt的disconnect()方法時一定要在主線程中,否則可能出現(xiàn)關(guān)不掉的可能.
2.下面的為網(wǎng)上都可以找到的
2.1清除藍(lán)牙緩存方法,通過反射機(jī)制調(diào)用,注意的是此方法需要在BluetoothGatt的close方法之前調(diào)用,即調(diào)用了清除緩存的方法,就可以調(diào)用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資源釋放關(guān)鍵地方
@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(); // 防止出現(xiàn)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(); // 防止出現(xiàn)status 133
????????????broadcastUpdate(intentAction);
????????????connect(reConnectAddress);
????????}
????}