How to know when bluetooth disconnected

2019-06-08 06:02发布

i am trying to "catch" when the bluetooth is disconnected from a device. im am using this code:

if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){
            deleteNotification();
            setWarningState(WarningState.RedWarning);
            showNotification("You are parked");

but when im disconnection the bluetooth by turning off the remote device or by turning off the bluetooth toggle in the phone it will not enter this if statment.

when im using this:

BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)

its working allright (when aconnection is astablished). why is that and how can i make it work? Thanks!

2条回答
别忘想泡老子
2楼-- · 2019-06-08 06:40
 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBluetoothReceiver, filter);

 private final BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();

            if (action!=null && action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                        BluetoothAdapter.ERROR);
                switch (state) {
                    case BluetoothAdapter.STATE_OFF:

                        break;
                    case BluetoothAdapter.STATE_ON:

                        break;

                }
            }
        }
    };
查看更多
Bombasti
3楼-- · 2019-06-08 06:43

Have you registered the below IntenFilters

IntentFilter f1 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter f2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, f1);
this.registerReceiver(mReceiver, f2);
查看更多
登录 后发表回答