我正在启动一项服务,为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()中。谢谢你的帮助。
此代码只提供绑定的设备,而不提供连接状态。这意味着,你的手机记忆中的蓝牙设备。。。但它们可以连接也可以不连接。
一般来说,要知道状态,你应该捕捉设备状态的变化:
<receiver android:name=".receiver.BTReceiver">
<intent-filter>
<action android:name="android.bluetooth.adapter.action.STATE_CHANGED" />
<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.BOND_STATE_CHANGED" />
</intent-filter>
如果你知道这是免提,你可以得到一个蓝牙耳机对象,它实际上有一些方法来了解连接状态:http://developer.android.com/reference/android/bluetooth/BluetoothHeadset.html