蓝牙连接时BroadcastReceiver的通知 [英] BroadcastReceiver to notify when Bluetooth is connected

查看:1436
本文介绍了蓝牙连接时BroadcastReceiver的通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打一个广播接收器,通知我当蓝牙的连接的到其他设备。

I want to make a BroadcastReceiver that notifies me when the Bluetooth is connected to another device.

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中

and AndroidManifest.xml

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

不过,当设备连接,没有任何反应,为什么?

but when the device is connected, nothing happens, why?

推荐答案

试试这个方法:

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

我希望它能帮助。

I hope it helps.

这篇关于蓝牙连接时BroadcastReceiver的通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆