How to know when bluetooth disconnected

2019-06-08 05:55发布

问题:

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!

回答1:

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);


回答2:

 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;

                }
            }
        }
    };