如何使用广播接收器检测蓝牙状态变化? [英] How to detect Bluetooth state change using a broadcast receiver?

查看:45
本文介绍了如何使用广播接收器检测蓝牙状态变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个应用程序,当设备的蓝牙打开时显示吐司.即使我的应用程序没有运行,我也想这样做.所以我应该使用广播接收器,添加一些权限,向 android manifest 添加一个意图过滤器并创建一个 java 类,但我不知道细节.

I am trying to make an app that shows a toast when the device's Bluetooth turned on. I wanna do that even when my app is not running. So I should use a broadcast receiver, add some permissions, an intent-filter to android manifest and make a java class but I don't know the details.

我该怎么办?我应该使用哪些权限?

What should I do? Which permissions should I use?

推荐答案

就权限而言,要检测蓝牙的状态变化,您需要将其添加到 AndroidManifest.xml 中.

AS far as permissions go, to detect the state change of bluetooth you need to add this to your AndroidManifest.xml.

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

一个示例接收器看起来像这样,您将此代码添加到要处理广播的位置,例如一个活动:

An example receiver would look like this, you add this code to where you want to handle the broadcast, for example an activity:

    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
            public void onReceive (Context context, Intent intent) {
                String action = intent.getAction();

                if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                    if(intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) 
    == BluetoothAdapter.STATE_OFF)
    // Bluetooth is disconnected, do handling here
}

}

        };

要使用接收器,您需要注册它.您可以执行以下操作.我在我的主要活动中注册了接收者.

To use the receiver, you need to register it. Which you can do as follows. I register the receiver in my main activity.

registerReceiver(this, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));

您也可以决定将所有这些添加到您的 AndroidManifest.xml 中.这样你就可以为接收器创建一个特殊的类并在那里处理它.无需注册接收器,只需创建类并将以下代码添加到AndroidManifest

You could also decide to add all of it to your AndroidManifest.xml. This way you can make a special class for the receiver and handle it there. No need to register the receiver, just make the class and add the below code to the AndroidManifest

<receiver
        android:name=".packagename.NameOfBroadcastReceiverClass"
        android:enabled="true">
    <intent-filter>
        <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
    </intent-filter>
</receiver>

这篇关于如何使用广播接收器检测蓝牙状态变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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