2012-07-18 103 views
0

我开始为BT设备连接/断开连接注册广播接收器的服务。它似乎工作得很好。虽然,我遇到了一个问题。我需要检测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及以上代码放置在服务#的onCreate()。 感谢您的帮助。

+0

对于android 2.2或更高版本有一个工作。否则,你运气不好。 – 2013-03-01 05:24:53

回答

0

此代码仅为您提供bonded设备,但不提供连接状态。这意味着,你的手机记住的蓝牙设备......但它们可以连接或不连接。

一般知道的状态,你应该捕捉设备状态变化:

<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> 

如果你知道这是一个免提,你可以得到这实际上有一些方法来知道连接状态BluetoothHeadset对象: http://developer.android.com/reference/android/bluetooth/BluetoothHeadset.html