我挠头试图找到一种方法来检测蓝牙耳机连接和断开事件为Android 2.1。我在API级别11中看到有一些显式的,但我如何在API级别7中做到这一点?我只是想知道用户何时连接或断开能够播放音频的耳机或汽车音响,以便我可以暂停播放的声音。
没有公共api,这个答案可能对作者使用反射的私有api有所帮助。
作者还发表了一篇关于他是如何做到这一点的评论
这看起来是一个很好的选择来检测蓝牙连接/断开。
如果这不起作用,另一个好的选择是在调用AudioManager.isBluetoothA2dpOn()
的服务中设置定时器来检查蓝牙是否连接或断开。
不确定这是否在2.1中工作,但它在2.2和2.3中工作。
它将捕获蓝牙耳机连接状态的变化:
声明以下intent-filter
<intent-filter >
<action android:name="android.bluetooth.headset.action.AUDIO_STATE_CHANGED" />
</intent-filter>
和在你的Receiver in 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
您必须为android.bluetooth.headset.action.STATE_CHANGED
操作设置BroadcastReceiver
。Intent的额外android.bluetooth.headset.extra.STATE
包含当前状态(断开,连接,连接)。更多Android源代码