Android:如何检测蓝牙连接状态

时间:2011-04-01 23:50:20

标签: android bluetooth

我想检测配对蓝牙耳机的连接状态 到手机 在Android 3.0(API级别11)中“BluetoothHeadset”类有 “isAudioConnected()”方法。

  • 我不知道如何创建(初始化)“BluetoothHeadset”对象。 似乎我需要使用 “getProfileProxy()”但我需要一个示例代码来了解我的需求 创建并传递参数。

谢谢, 何

1 个答案:

答案 0 :(得分: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) {
            // }
        }
    }
}

`

相关问题