BroadcastReceiver在蓝牙连接时通知

时间:2013-09-19 11:07:32

标签: java android broadcastreceiver android-bluetooth

我想制作一个BroadcastReceiver,当蓝牙连接时,会通知我。

BroadcastReceiver bluetooth = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() == android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED) {
            Toast.makeText(MainActivity.this, "done!", Toast.LENGTH_LONG)
                    .show();
        }
    }
};

    IntentFilter ff = new IntentFilter();
    ff.addAction(android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED);
    registerReceiver(bluetooth, ff);

和AndroidManifest.xml

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

但是当设备连接时,没有任何反应,为什么?

1 个答案:

答案 0 :(得分:0)

尝试这种方式:

getApplicationContext().registerReceiver(receiver,
                new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));

getApplicationContext().registerReceiver(receiver,
                new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

private final BroadcastReceiver mReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
        {
            // LOG - Connected
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action))
        {
            // LOG - Disconnected
        }
    }
}

我希望它有所帮助。