问题描述
我试图让一个应用程序,显示敬酒时,该设备的蓝牙打开。我想执行,即使我的应用程序没有运行该操作。所以,我应该使用的广播接收机。我知道我应该添加权限和意向过滤器的Android清单,让一个Java类。
I am trying to make an app that shows a toast when the device's Bluetooth turned on. I wanna perform that action even when my app is not running. So I should use a broadcast receiver.I know I should add permissions and an intent-filter to android manifest and make a java class.
我应该怎么办?我应该使用什么权限?
What should I do? What 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" />
这是例子接收器应该是这样的,你加这个code到要处理的广播,例如活动:
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。这种方式可以使接收机一类特殊和处理它。无需注册的接收器,才使这个类并添加下面的code到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>
这篇关于如何使用广播接收器检测到蓝牙状态变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!