2011-04-01 70 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