我正在尝试创建一个在设备的蓝牙开启时显示祝酒的应用。即使我的应用程序没有运行,我也想这样做。所以我应该使用广播接收器,添加一些权限,一个intent-filter到android清单并创建一个java类,但我不知道细节。
我该怎么办?我应该使用哪些权限?
答案 0 :(得分:69)
就权限而言,要检测蓝牙的状态变化,您需要将其添加到AndroidManifest.xml。
<uses-permission android:name="android.permission.BLUETOOTH" />
示例接收器看起来像这样,您将此代码添加到您要处理广播的位置,例如活动:
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
}
}
};
要使用接收器,您需要注册它。你可以做如下。我在主要活动中注册接收器。
registerReceiver(this, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
您还可以决定将所有内容添加到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>
答案 1 :(得分:21)
您必须获得以下许可。
<uses-permission android:name="android.permission.BLUETOOTH" />
你必须把它写成接收器标签中的意图过滤器。
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
答案 2 :(得分:3)
不幸的是,对于以api 26或更高版本为目标的应用程序,清单声明的广播接收器不再起作用(此处参考:this article),但有一些例外。 android.bluetooth.adapter.action.STATE_CHANGED不在该列表中。
对于蓝牙,您只能在以下位置收听更改:
ACTION_CONNECTION_STATE_CHANGED,ACTION_ACL_CONNECTED,ACTION_ACL_DISCONNECTED