开始活动时,我需要知道是否有任何蓝牙配对设备,然后根据结果做一些事情。为此,我执行以下操作:
在 onResume 中:
protected void onResume() {
super.onResume();
/**Filters para comprobar el BroadcastReceiver*/
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
然后,我使用广播接收器:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
/**Do something if connected*/
if(action.equals("android.bluetooth.device.action.ACL_CONNECTED")) {
//Action
}
/**Do something if disconnected*/
else if (action.equals("android.bluetooth.device.action.ACL_DISCONNECTED")) {
Toast.makeText(getApplicationContext(), "No device paired", Toast.LENGTH_SHORT).show();
}
}
};
在清单中:
<activity
android:name=".Configuration"
android:label="@string/config_title" >
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED"/>
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"/>
</intent-filter>
</activity>
但是仍然没有做它认为必须做的事情,所以一定是出了什么问题,或者我忘了做某事。