如何将动作分配给广播接收器

How to assign action to broadcast receiver

我的代码应该监听蓝牙耳机配对取消配对时发出的回调。

 //The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver bReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            Toast.makeText(getBaseContext(), "paired", Toast.LENGTH_LONG).show();
        } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            Toast.makeText(getBaseContext(), "unpaired", Toast.LENGTH_LONG).show();
        }
    }
};

连接蓝牙设备时 BluetoothDevice.ACTION_ACL_CONNECTED 会触发,但 BluetoothDevice.ACTION_ACL_DISCONNECTED 从不显示任何 toast。

我猜这是因为我没有在 onCreate 中正确分配 filters/actions :

  IntentFilter BluetoothFilter = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
    registerReceiver(bReceiver, BluetoothFilter);

如何在 oncreate 中添加 ACTION_ACL_DISCONNECTED

已编辑registerReceiver.

之前添加 BluetoothFilter.addAction(ACTION_ACL_DISCONNECTED)