android插拔耳麥廣播android.intent.action.HEADSET_PLUG中間出的問題

今天在做插拔耳麥廣播遇到一個奇怪的現象。

本來想把廣播做成全局的,在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註冊的效果。求大神指點!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章