如何为广播接收器分配动作

时间:2018-02-12 19:59:27

标签: android broadcastreceiver

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

 //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从不显示任何祝酒词。

我猜这是因为我没有在onCreate中正确分配过滤器/操作:

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

如何在ACTION_ACL_DISCONNECTED中添加oncreate

1 个答案:

答案 0 :(得分:0)

<强> EDITED BluetoothFilter.addAction(ACTION_ACL_DISCONNECTED)之前添加registerReceiver