Android studio ble蓝牙配对成功后,远距离断开蓝牙后,再回近距离搜索不到蓝牙名称也无法配对成功,是什么情况?
以下是报错信息
```java
E/TestSerice2: onConnectionStateChange fail-->(连接状态更改)0
D/BluetoothGatt: close()
D/BluetoothGatt: unregisterApp() - mClientIf=14
D/BluetoothGatt: cancelOpen() - device: 94:C9:60:**:**:**
W/BluetoothGatt: Unhandled exception in callback
java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothGatt android.bluetooth.BluetoothDevice.connectGatt(android.content.Context, boolean, android.bluetooth.BluetoothGattCallback)' on a null object reference
at com.example.myapplication.TestService2$3.onConnectionStateChange(TestService2.java:209)
at android.bluetooth.BluetoothGatt$1$4.run(BluetoothGatt.java:280)
at android.bluetooth.BluetoothGatt.runOrQueueCallback(BluetoothGatt.java:794)
at android.bluetooth.BluetoothGatt.access$400(BluetoothGatt.java:42)
at android.bluetooth.BluetoothGatt$1.onClientConnectionState(BluetoothGatt.java:275)
at android.bluetooth.IBluetoothGattCallback$Stub.onTransact(IBluetoothGattCallback.java:192)
at android.os.Binder.execTransactInternal(Binder.java:1028)
at android.os.Binder.execTransact(Binder.java:1001)
D/DecorView: showOrHideHighlightView: hasFocus=true; winMode=1; isMrgNull=true
callback里使用的对象已经关闭了
执行收发之前先判断非空
扫描结果回调中获取的蓝牙设备(device)调用connectGatt()连接方法连接蓝牙。 connectGatt(Context context, boolean autoConnect,BluetoothGattCallback callback)连接方法参数解释:context上下文对象,autoConnect布尔值,是否在可用时自动连接,BluetoothGattCallback蓝牙连接回调引用。
//将BluetoothGatt设置为全局变量,方便后续调用。
private BluetoothGatt mBtGatt;
//连接蓝牙。
mBtGatt = device.connectGatt(context, false, mBtGattCallback);