1

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

4

3 回答 3

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:

        }
}
};
于 2012-01-04T08:28:23.243 回答
0

来自 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
于 2014-07-22T02:57:46.450 回答
-1

这在应用程序启动时不会真正起作用,但由于意图过滤器是自动注册的,所以一旦你的应用程序启动,你可能会有一个有效的值:

声明以下意图过滤器

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

并在 onReceive 中的 Receiver 检查:

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

于 2012-08-06T16:53:10.323 回答