一直比较懒,没有仔细整理过开发记录,今天有点小收获,分享一下
1*
BluetoothGatt = mDevice .connectGatt(mContext, false, mGattCallback)
源码
/**
* Connect to GATT Server hosted by this device. Caller acts as GATT client.
* The callback is used to deliver results to Caller, such as connection status as well
* as any further GATT client operations.
* The method returns a BluetoothGatt instance. You can use BluetoothGatt to conduct
* GATT client operations.
* @param callback GATT callback handler that will receive asynchronous callbacks.
* @param autoConnect Whether to directly connect to the remote device (false)
* or to automatically connect as soon as the remote
* device becomes available (true).
* @throws IllegalArgumentException if callback is null
*/
public BluetoothGatt connectGatt(Context context, boolean autoConnect,
BluetoothGattCallback callback) {}
参数一:上下文context
参数二:是否自动连接,通常是false,(true没试过)
参数三:回调函数
private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() {
//连接状态的改变监听
public void onConnectionStateChange(BluetoothGatt gatt, int status,
int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
//连接
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
//断开连接
//2*
BuleCommonConstants.mBluetoothGatt = gatt;
BuleCommonConstants.mBluetoothGatt. close();
}
}
// 发现连接服务监听
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
}
// 获取读的特征值
public void onCharacteristicRead(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
}
// 获取从机回复特征值
public void onCharacteristicChanged(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic) {
}
// 监听到蓝牙底层发送成功事件
public void onCharacteristicWrite(BluetoothGatt gatt,
BluetoothGattCharacteristic characteristic, int status) {
};
};
在(1*)出我们已经保存了bluetoothgatt,当我们调用断开连接接口,直接通过(1*)出的bluetoothgatt,调用close()
场景一
通过apk连接上一个设备记录全局blueDevice和bluetoothgatt
然后在一设备没断开情况下,连接设备二将blueDevice和bluetoothgatt覆盖,然后调用断开接口BluetoothGatt.disconnect()
此时BluetoothGatt已经被释放掉。
就不能通过BluetoothGatt.disconnect()进行断开设备一,只能从机断开连接。但此时BluetoothGatt全局已经被释放到,但是android层还持有这个BluetoothGatt,不能及时释放就会导致异常,如主机端收到回调特征值重复等
后续会陆续分享这几年的低功耗开发,文档如有不当出,望各位路过大神,留笔指点。
未完待续。。。