项目中有一个需求,就是获取已连接的蓝牙地址
private void getConnectBt() {
LogUtil.i("getConnectBt");
int a2dp = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
int headset = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
int health = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH);
int flag = -1;
if (a2dp == BluetoothProfile.STATE_CONNECTED) {
flag = a2dp;
} else if (headset == BluetoothProfile.STATE_CONNECTED) {
flag = headset;
} else if (health == BluetoothProfile.STATE_CONNECTED) {
flag = health;
}
Log.d(TAG,"flag:"+flag);
if (flag != -1) {
_bluetoothAdapter.getProfileProxy(_context, new BluetoothProfile.ServiceListener() {
@Override
public void onServiceDisconnected(int profile) {
}
@Override
public void onServiceConnected(int profile, BluetoothProfile proxy) {
List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
if (mDevices != null && mDevices.size() > 0) {
for (BluetoothDevice device : mDevices) {
Log.d(TAG,device.getName() + "," + device.getAddress());
}
} else {
}
}
}, flag);
}
}
从网上看到这段代码并没有作用,由于flag一直等于-1,所以一直返回BluetoothProfile.STATE_DISCONNECTED。也就是说
int a2dp = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.A2DP);
int headset = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEADSET);
int health = _bluetoothAdapter.getProfileConnectionState(BluetoothProfile.HEALTH);这三个方法都是返回的BluetoothProfile.STATE_DISCONNECTED

本文探讨了在Android项目中如何获取已连接蓝牙设备的地址。通过分析源码,发现BluetoothAdapter的mService是关键,实际操作由AdapterServiceBinder执行。重点关注BluetoothProfile接口及其子类如BluetoothHeadset和BluetoothA2dp,它们定义了不同类型的蓝牙连接。当使用默认方法无效时,可以尝试使用BluetoothAdapter的隐藏方法直接调用AdapterProperties的getConnectionState方法。
最低0.47元/天 解锁文章
1933





