需求
android系统车机上的播放器,连接手机蓝牙播放音乐,有时候需要判断蓝牙是否已经连接,但是不想麻烦的去注册一个广播,希望通过同步的查询方法判断蓝牙是否已经和其他的设备连接。
方法一
通过BluetoothAdapter.getProfileConnectionState(), 这个方法需要传入一个设备类型,比如我希望用来播放音乐,那传入的就是BluetoothProfile.A2DP,因为播放音视频所使用的就是蓝牙的A2DP协议。
int state = bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
if (state != BluetoothAdapter.STATE_CONNECTED){
return BLUETOOTH_NOT_CONNECT;
}
我在手机上测试这个方法是可用的,连接和断开时都能得到正确的结果。但是在车机上测试始终都是未连接状态,我猜想可能是虽然车机也是基于android11开发的,但是现在它的角色变化了,现在是一个类似于音响或者无线耳机之类的播放设备,所以得不到正确的连接状态(我猜的,如果知道正真的结果请告诉我)。
方法二
BluetoothAdapter类中有一个函数getConnectionState(),但是这个函数不提供给App使用,只能通过反射的方式调用。
try{
Method method = bluetoothAdapter.getClass().getDeclaredMethod("getConnectionState", (Class[]) null);
method.setAccessible(true);
int state = (int) method.invoke(bluetoothAdapter, (Object[]) null);
if (state == BluetoothAdapter.STATE_CONNECTED){
return BLUETOOTH_OK;
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
代码很简单,都看得懂。大家如果发现更好的方式请留言告诉我。