我正试图找到一种方法来检测蓝牙耳机连接并断开Android 2.1的事件 . 我在API Level 11中看到有一些明确的,但我如何在API级别7中执行此操作?我只是想知道用户何时连接或断开能够播放音频的耳机或汽车音响,以便我可以暂停正在播放的声音 .
您必须为 android.bluetooth.headset.action.STATE_CHANGED 操作设置 BroadcastReceiver . Intent的额外 android.bluetooth.headset.extra.STATE 包含当前状态(断开连接,连接,连接) . 更多信息Android source code
android.bluetooth.headset.action.STATE_CHANGED
BroadcastReceiver
android.bluetooth.headset.extra.STATE
没有公共API,这是answer might help,作者使用反射使用私有API .
作者还发表了关于他如何使用它的评论 .
This看起来是检测蓝牙连接/断开的好选择 .
如果这不起作用,另一个好的选择是在服务中设置一个定时器,调用 AudioManager.isBluetoothA2dpOn() 来检查蓝牙是连接还是断开 .
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
4 回答
您必须为
android.bluetooth.headset.action.STATE_CHANGED
操作设置BroadcastReceiver
. Intent的额外android.bluetooth.headset.extra.STATE
包含当前状态(断开连接,连接,连接) . 更多信息Android source code没有公共API,这是answer might help,作者使用反射使用私有API .
作者还发表了关于他如何使用它的评论 .
This看起来是检测蓝牙连接/断开的好选择 .
如果这不起作用,另一个好的选择是在服务中设置一个定时器,调用
AudioManager.isBluetoothA2dpOn()
来检查蓝牙是连接还是断开 .不确定这是否适用于2.1,但它适用于2.2和2.3 .
它将捕获蓝牙耳机连接状态的变化:
声明以下intent-filter
并在您的Receiver in onReceive中检查:
并将int保存为静态变量 . 如果您想知道BT音频是否已连接(1)/断开连接(0),请随时访问它 . 不漂亮,但完成工作 .
还可以看看:https://github.com/android/platform_frameworks_base/blob/gingerbread/core/java/android/bluetooth/BluetoothHeadset.java