您的位置:首页 > 移动开发 > Android开发

android插拔耳麦广播android.intent.action.HEADSET_PLUG中间出的问题

2011-09-14 20:03 155 查看
今天在做插拔耳麦广播遇到一个奇怪的现象。


本来想把广播做成全局的,在Manifest文件中配置

<receiver android:name=".receiver.PlayMusicReceiver" android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.HEADSET_PLUG"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>


结果不给力,插拔耳麦时广播没起作用。

木办法,将广播接收器写到某个Activity里面再试,奇了怪了,还起作用了,为什么设成全局的就不起作用呢?

网上搜了一下,下面给出了答案:

However, you need to be aware that HEADSET_PLUG is a "sticky" event, every BroadcastReceiver subscribed to that event will receive it upon construction; I don't know if there is a possibility to determine if the
event has captured at the exact time or been "sticked" for a while.

http://groups.google.com/group/android-developers/browse_thread/thread/6d0dda99b4f42c8f

同时也给出了解决方案,将广播注册到Service中:

public class PlayMusicService extends Service
{

private final PlayMusicReceiver receiver = new PlayMusicReceiver();
private static final String TAG = "PlayMusicService";
@Override
public IBinder onBind(Intent intent)
{
return null;
}

@Override
public void onCreate()
{
registerReceiver(receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
super.onCreate();
Log.i(TAG, "Create Service");
}

@Override
public void onDestroy()
{
unregisterReceiver(receiver);
super.onDestroy();
Log.i(TAG, "Destroy Service");
}

}
在Activity中用startService启动就可以了,这样在退出时仍然可以监测到耳麦的插拔。但问题又出来,如果没启动应用,则监听不到广播,达不到在manifest注册的效果。求大神指点!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: