如何使用Android2.2在应用程序启动时获得蓝牙耳机连接状态?

时间:2011-12-12 13:16:34

标签: android bluetooth headset

如何在应用程序启动时使用android api level 8获取蓝牙耳机连接状态(连接/断开连接)? android2.2中是否有任何粘性广播意图? 是否有任何API可以获取初始蓝牙耳机状态? 有没有可用的解决方法?

3 个答案:

答案 0 :(得分:3)

我找到了解决方案:

private static final String ACTION_BT_HEADSET_STATE_CHANGED  = "android.bluetooth.headset.action.STATE_CHANGED";
private static final int STATE_CONNECTED = 0x00000002; 
private static final int STATE_DISCONNECTED  = 0x00000000;  
private static final String EXTRA_STATE = "android.bluetooth.headset.extra.STATE";

private BroadcastReceiver mBlueToothHeadSetEventReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
    try {
        String action = intent.getAction();

        if(action == null)
            return;

        if(action.equals(ACTION_BT_HEADSET_STATE_CHANGED)){
            int extraData = intent.getIntExtra(EXTRA_STATE  , STATE_DISCONNECTED);
            if(extraData == STATE_CONNECTED ){

                //TODO :

            }else if(extraData == STATE_DISCONNECTED){

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

        //TODO:

        }
}
};

答案 1 :(得分:0)

这在应用程序启动时不会真正起作用,但是当自动注册intent-filters时,一旦你的应用程序启动,你可能会有一个有效的值:

声明以下intent-filter

        <intent-filter >
            <action android:name="android.bluetooth.headset.action.AUDIO_STATE_CHANGED" />
        </intent-filter>

并在接收者的onReceive中检查:

if ("android.bluetooth.headset.action.AUDIO_STATE_CHANGED".equals(intent.getAction())) {
  headsetAudioState = intent.getIntExtra("android.bluetooth.headset.extra.AUDIO_STATE", -2);
}

并将int保存为静态变量。如果您想知道BT音频是否已连接(1)/断开连接(0),请随时访问它。不漂亮,但完成工作。

同时退房: https://github.com/android/platform_frameworks_base/blob/gingerbread/core/java/android/bluetooth/BluetoothHeadset.java

答案 2 :(得分:0)

from packages / apps / Phone / src / com / android / phone / PhoneGlobals.java:1449

        } else if (action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
            mBluetoothHeadsetState = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE,
                                                      BluetoothHeadset.STATE_DISCONNECTED);
            if (VDBG) Log.d(LOG_TAG, "mReceiver: HEADSET_STATE_CHANGED_ACTION");
            if (VDBG) Log.d(LOG_TAG, "==> new state: " + mBluetoothHeadsetState);
            updateBluetoothIndication(true);  // Also update any visible UI if necessary