How to get Bluetooth Headset connection state (connected/disconnected) using android api level 8 on application start-up? Is there any sticky broadcast intent available in android2.2? Is there any API to fetch initial Bluetooth Headset state? Is there any workaround available?
I figured out the solution:
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:
}
}
};
This won't really work on application startup, but as intent-filters are registered automatically, you might have a valid value, once your app gets started up:
Declare the following intent-filter
<intent-filter >
<action android:name="android.bluetooth.headset.action.AUDIO_STATE_CHANGED" />
</intent-filter>
and in your Receiver in onReceive check for:
if ("android.bluetooth.headset.action.AUDIO_STATE_CHANGED".equals(intent.getAction())) {
headsetAudioState = intent.getIntExtra("android.bluetooth.headset.extra.AUDIO_STATE", -2);
}
and save the int as a static variable. Access it anytime you want to know if BT audio is connected(1) / disconnected(0). Not pretty, but gets the job done.
Also check out: https://github.com/android/platform_frameworks_base/blob/gingerbread/core/java/android/bluetooth/BluetoothHeadset.java
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.