2011-04-01 68 views
0

我想要檢測已配對的藍牙耳機 與手機的連接狀態。 在Android 3.0(API級別11)中,「BluetoothHeadset」類具有 「isAudioConnected()」方法。Android:如何檢測藍牙連接狀態

  • 我不知道如何創建(初始化)「BluetoothHeadset」對象。 看來我需要使用 「getProfileProxy()」,但我需要一個示例代碼來了解我如何需要 來創建和傳遞參數。

感謝, 何

回答

0

您需要實現BluetoothProfile.ServiceListener:

BluetoothProfile.ServiceListener b = new BlueToothListener(); 
      boolean profileProxy = BluetoothAdapter.getDefaultAdapter() 
        .getProfileProxy(Handler.bot, b, BluetoothProfile.HEADSET); 


public class BlueToothListener implements ServiceListener { 
     public static BluetoothHeadset headset; 
     public static BluetoothDevice bluetoothDevice; 
    @Override 
    public void onServiceDisconnected(int profile) {// dont care 
     headset = null; 
    } 

    @Override 
    public void onServiceConnected(int profile, 
      BluetoothProfile proxy) {// dont care 
     try { 
      Debugger.test("BluetoothProfile onServiceConnected "+proxy); 
      if (proxy instanceof BluetoothHeadset) 
       headset = ((BluetoothHeadset) proxy); 
      else// getProfileProxy(Handler.bot, b, BluetoothProfile.HEADSET); 
       return;// ^^ => NEVER 

      List<BluetoothDevice> connectedDevices = proxy 
        .getConnectedDevices(); 
      for (BluetoothDevice device : connectedDevices) { 
       Debugger.log("BluetoothDevice found :" + device); 
       bluetoothDevice = device; 
       int connectionState = headset.getConnectionState(bluetoothDevice); 
       Debugger.log("BluetoothHeadset connectionState "+connectionState);//2 == OK 
       boolean startVoiceRecognition = headset 
         .startVoiceRecognition(device); 
       if (startVoiceRecognition) { 
        Debugger 
          .log("BluetoothHeadset init Listener OK"); 
        return; 
       } 
       else 
        Notify.popup("Bluetooth headset can't start speech recognition"); 

      } 
     } catch (Exception e) { 
      // } 
     } 
    } 
} 

`

+0

當藍牙設備連接/斷開 'onServiceConnected' 永遠不會被調用。 – 2017-06-23 09:03:19