![](/img/trans.png)
[英]Android 2.2 progammically tell if my Bluetooth Headset is connected on application start
[英]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.