簡體   English   中英

如何使用Android2.2在應用程序啟動時獲得藍牙耳機連接狀態?

[英]How to get Bluetooth Headset connection state on application start-up using Android2.2?

如何在應用程序啟動時使用android api level 8獲得藍牙耳機連接狀態(連接/斷開連接)? android2.2中是否有任何粘性廣播意圖? 是否有任何API可以獲取藍牙耳機的初始狀態? 有沒有可用的解決方法?

我想出了解決方案:

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:

        }
}
};

這實際上不會在應用程序啟動時起作用,但是由於意圖過濾器是自動注冊的,因此一旦應用程序啟動,您可能會有一個有效值:

聲明以下intent-filter

        <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

來自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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM