Android 广播之ACTION_HEADSET_PLUG

脉泳 2012-12-05 05:21:57
最近开发android程序,想捕获ACTION_HEADSET_PLUG广播来判断耳麦拔插事件,于是写了一个注册方法:
private HeadsetPlugReceiver registerHeadsetPlugReceiver(Context ctx){
HeadsetPlugReceiver headsetPlugReceiver = new HeadsetPlugReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
intentFilter.addAction(Intent.ACTION_MEDIA_BUTTON);
intentFilter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
intentFilter.setPriority(Integer.MAX_VALUE);
ctx.registerReceiver(headsetPlugReceiver, intentFilter);
return headsetPlugReceiver;
}

处理方法:
public class HeadsetPlugReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction() == Intent.ACTION_HEADSET_PLUG){
if (intent.hasExtra("state")){
if (intent.getIntExtra("state", 0) == 0){
// 未接入耳麦设备
if(CSwiperController.m_cswiperControllerState != CSwiperControllerState.STATE_IDLE){
SendMessage(MSG_ONINTERRUPTED,null);
}
if (CSwiperController.m_isDetectDeviceChange) {
CSwiperController.m_listener.onDeviceUnplugged();
}

// 终止所有任务,但线程不退出
CSwiperController.StopAllWork(); // 终止所有作业
} else{
// 接入耳麦设备
if (CSwiperController.m_isDetectDeviceChange) {
CSwiperController.m_listener.onDevicePlugged();
}
}
}
// }else if(AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())){
// if(isDevicePresent()){
// Log.w("Plugin","设备存在");
// }else{
// Log.w("Plugin","设备不存在");
// }
// Log.w("Plugin","设备变更...");

}else if(intent.getAction() == Intent.ACTION_MEDIA_BUTTON){
abortBroadcast();
}else{
;
}
} //onReceive

}// class

AndroidManifest.xml :

<receiver android:name="HeadsetPlugReceiver">
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG"></action>
<action android:name="android.intent.action.MEDIA_BUTTON"></action>
<action android:name="android.intent.action.AUDIO_BECOMING_NOISY"></action>
</intent-filter>
</receiver>

最后发现在部分手机上能够获取广播,但在部分手机上又无法获取,这到底是为什么呢?
而且发现在能够获取广播的设备上即时不在xml文件中声明<action android:name="android.intent.action.HEADSET_PLUG"></action>也是可以获取到的,现在关键的问题是为虾米部分手机收不到广播呢?

...全文
564 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
帅惊联合国 2012-12-06
  • 打赏
  • 举报
回复
那楼主只能重新开贴了。。
脉泳 2012-12-06
  • 打赏
  • 举报
回复
哎,代码写错了……结贴

80,351

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧