我正在启动一项为 BT 设备连接/断开连接注册广播接收器的服务。它似乎工作得很好。虽然,我遇到了问题。我需要检测 BT 耳机是否已经连接,以便我知道当前状态。我使用下面的代码,但看起来它没有完成它的工作:
// ...
// get BluetoothAdapter
BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
// to tell if BT headset is connected
boolean isBtHeadsetOn = false;
// if device supports BT
if (ba != null) {
// get list of paired devices
Set<BluetoothDevice> devices = ba.getBondedDevices();
if (devices != null) {
// loop through devices
for (BluetoothDevice device : devices) {
// get device class
BluetoothClass bc = device.getBluetoothClass();
if (bc == null) continue;
int devClass = bc.getDeviceClass();
// check if device is handsfree, headphones or headset
if (devClass == BluetoothClass.Device.AUDIO_VIDEO_HANDSFREE || devClass == BluetoothClass.Device.AUDIO_VIDEO_HEADPHONES || devClass == BluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET) {
// yes, it is
isBtHeadsetOn = true;
break;
}
}
}
}
// now I got my result in variable isBtHeadsetOn
// ...
我正在为 android 2.1 开发,上面的代码放在 Service#onCreate() 中。谢谢你的帮助。