java - BroadcastReceiver 在连接蓝牙时通知

标签 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" />

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

最佳答案

试试这个方法:

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

希望对你有帮助。

关于java - BroadcastReceiver 在连接蓝牙时通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18892971/

相关文章:

android - 隐式广播接收器未调用

android - 是否可以取消注册 BroadCast Lister

android - 广播接收器未收到 USB 权限

Java 和 MySQL - 列数与第 1 行的值数不匹配

java - Elasticsearch 前缀过滤器

java - 检查Java中字符串中特定符号的特殊排列

android - 如何配置实时视频流 android 移动到 wowza 媒体服务器?

java - Spring MVC 和 Freemarker/Velocity

android - Flutter webview 拦截所有请求并添加 headers

android - 无法在OS X中添加多个环境路径