2

当蓝牙连接到另一台设备时,我想做一个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" />

但是当设备连接时,什么也没有发生,为什么?

4

1 回答 1

-1

试试这个方法:

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
        }
    }
}

我希望它有所帮助。

于 2013-09-20T07:42:56.233 回答