2012-07-18 102 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