我正在使用我的应用程序中的BLE设备进行通信。我想在设备断开连接时显示通知。我在Internet上进行了研究,但得到了一个粗略的实现,但是没有成功。谁能给我指示?这是我的代码。
public void disconnect() {
if (mBluetoothAdapter == null || mBluetoothGatt == null) {
Log.w(TAG, "Bluetooth not initialized");
return;
}
mBluetoothGatt.disconnect();
addNotification();
//mBluetoothGatt.close();
}
private void addNotification(){
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("STATE DEVICE")
.setContentText("Device Disconnected!")
.setPriority(NotificationCompat.PRIORITY_HIGH);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
答案 0 :(得分:0)
正确的方法是使用BluetoothGattCallback的 onConnectionStateChange 方法,而不是在调用connect()后显示通知
1)定义蓝牙gatt回调:
private BluetoothGattCallback callback = new BluetoothGattCallback() {
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
super.onConnectionStateChange(gatt, status, newState);
if (newState == STATE_DISCONNECTED){
// show notification
}
}
}
}
2)使用将回调传递给您的connectGatt方法:
myDevice.connectGatt(this, true, callback);