Android中通过耳机按键控制音乐播放的实现今天在研究Android中实现Android 4.2.2源码中的Music应用的源码,
Android中通过耳机按键控制音乐播放的实现
今天在研究Android中实现Android 4.2.2源码中的Music应用的源码,关于通过耳机按键控制音乐播放的实现,有点好奇,就仔细分析了一下源码,
主要由 MediaButtonIntentReceiver 这个类来实现。
在AndroidManifest.xml中有如下Receiver的注册:
/** * Broadcast Action: Wired Headset plugged in or unplugged. * * <p>The intent will have the following extra values: * <ul> * <li><em>state</em> - 0 for unplugged, 1 for plugged. </li> * <li><em>name</em> - Headset type, human readable string </li> * <li><em>microphone</em> - 1 if headset has a microphone, 0 otherwise </li> * </ul> * </ul> */ @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) public static final String ACTION_HEADSET_PLUG = "android.intent.action.HEADSET_PLUG";自己测试了一下,在AndroidManifest.xml中静态注册,是不会生效的,为啥?
一个很简单的解释,如果你的应用还没有运行,这时插入耳机,系统如何把这个消息给这个应用?
因此,"android.intent.action.HEADSET_PLUG" 只能通过动态注册来接收此广播消息。
如果让 MediaButtonIntentReceiver 还接收"android.intent.action.HEADSET_PLUG"的广播消息,
则MediaButtonIntentReceiver会先收到 "android.media.AUDIO_BECOMING_NOISY" 这个消息,然后才会收到"android.intent.action.HEADSET_PLUG"这个消息?
为什么这样,代码层面还没有分析,后面抽空再研究下Android源码。
