如何使用广播接收器检测蓝牙状态变化?

Moh*_*d H 32 android bluetooth broadcastreceiver android-permissions

我正在尝试创建一个在设备的蓝牙打开时显示祝酒的应用程序.即使我的应用程序没有运行,我也想这样做.所以我应该使用广播接收器,添加一些权限,一个intent-filter到android清单并制作一个java类,但我不知道细节.

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

小智 73

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

<uses-permission android:name="android.permission.BLUETOOTH" />
Run Code Online (Sandbox Code Playgroud)

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

    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
}

}

        };
Run Code Online (Sandbox Code Playgroud)

要使用接收器,您需要注册它.你可以做如下.我在主要活动中注册接收器.

registerReceiver(this, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
Run Code Online (Sandbox Code Playgroud)

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

<receiver
        android:name=".packagename.NameOfBroadcastReceiverClass"
        android:enabled="true">
    <intent-filter>
        <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/>
    </intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)


Man*_*olu 21

您必须获得以下许可.

<uses-permission android:name="android.permission.BLUETOOTH" />
Run Code Online (Sandbox Code Playgroud)

你必须把它写成接收器标签中的意图过滤器.

<action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
Run Code Online (Sandbox Code Playgroud)


Nic*_*zzi 8

不幸的是,对于面向api 26或更高版本的应用程序,清单声明的广播接收器不再工作(参考此处:https : //developer.android.com/guide/components/broadcast-exceptions),但有一些例外。 android.bluetooth.adapter.action.STATE_CHANGED不在那个列表中。

对于蓝牙,您只能监听以下更改:

ACTION_CONNECTION_STATE_CHANGED, ACTION_ACL_CONNECTED,ACTION_ACL_DISCONNECTED