我正在编写一个应用程序来检测蓝牙设备是否已连接。在做了一些研究后,我发现最好的方法是使用带有蓝牙相关意图过滤器的广播接收器。
<receiver android:name=".BTReceiver" >
<intent-filter>
<action android:name="android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED" />
<action android:name="android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECTED" />
<action android:name="android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED" />
<action android:name="android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED" />
</intent-filter>
</receiver>
这是我的蓝牙接收器类。
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("android.bluetooth.BluetoothDevice.ACTION_ACL_CONNECTED") || action.equals("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED") ){
Log.d("Z","Received: Bluetooth Connected");
}
if(action.equals("android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECTED") ||action.equals("android.bluetooth.BluetoothDevice.ACTION_ACL_DISCONNECTED_REQUESTED")){
Log.d("Z","Received: Bluetooth Disconnected");
}
Log.d("Z",action);
}
当我打开蓝牙耳机并连接到手机时,我收到两次“android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED”。当我断开蓝牙耳机时,广播接收器不会运行或接收任何东西。所以我从未收到蓝牙断开连接日志消息。我正在使用我认为必须使用的两个蓝牙权限才能使其正常工作。
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
我真的可以在这里使用任何有关错误的信息。谢谢。
答案 0 :(得分:5)
你的行动有误。
<receiver android:name=".BTReceiver" >
<intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" />
<action android:name="android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED" />
</intent-filter>
</receiver>
删除
|| action.equals("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED")
因为CONNECTION_STATE_CHANGED可以连接,断开等等。所以你的第一个 if 总是如此。除非您对a2dp执行任何特定操作,否则无需注册android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED。
因此,它应该是
if(action.equals("android.bluetooth.device.action.ACL_CONNECTED") {
Log.d("Z","Received: Bluetooth Connected");
}
if(action.equals("android.bluetooth.device.action.ACL_DISCONNECTED") ||action.equals("android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED")){
Log.d("Z","Received: Bluetooth Disconnected");
}