注意: 写该文章主要帮助自己记忆,贴出来希望可以给有同样问题的人解惑,不喜勿喷,可以提意见哦。
一、待了解内容
1、MediaButtonReceiver使用的情景
2、系统发送广播到MediaButtonReceiver接收广播流程的讲解。
二、
1、MediaButtonReceiver使用的情景
Android源码中并没有MediaButtonReceiver这个类,MediaButtonReceiver继承了BroadCastReceiver,即MediaButtonReceiver也就是一个简单的广播接收者。但为什么单独要讲MediaButtonReceiver者呢,顾名思义,该广播接受者主要处理媒体按钮的一些事件,例如耳机中暂停,播放,上一曲,下一曲,音量调大,音量减小等。
例如:当有如下几个应用图片,本地音乐,蓝牙音乐,收音机等,其中这些应用中都有如下功能,暂停,播放,上一个,下一个,并且都注册了语音操作广播,当操作这些功能的时候,应用都会做相应的处理,为了避免语音操作播放,所有的应用都接收到了该广播,并执行播放动作,这个时候就需要利用MediaButtonReceiver的一个特别之处,只有当前获取焦点的应用才会接收到该广播。
2、系统发送广播到MediaButtonReceiver接收广播流程的讲解。
注册、接收广播简单实现。
(1)实现MediaButtonReceiver代码
public class MediaButtonReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String intentAction = intent.getAction();
if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
KeyEvent event =
(KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (event == null) {
return;
}
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
break;
case KeyEvent.KEYCODE_MEDIA_PAUSE:
break;
case KeyEvent.KEYCODE_MEDIA_PLAY:
break;
}
}
}}
(2)实现广播接收者之后,需要注册。在AndroidManifest.xml中静态注册广播。因为需求问题,这里只监听了一个action,表示媒体按键按下的时候会触发该广播,如果有其他需要,用户还可以监听这些广播,如,android.intent.action.HEADSET_PLUG表示耳机插入与移除,android.media.AUDIO_BECOMING_NOISY, 但是这个广播只是针对有线耳机,或者无线耳机的手机断开连接的事件,监听不到有线耳机和蓝牙耳机的接入。
<receiver android:name="com.hwatong.music.MediaButtonReceiver" >
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON" />
</intent-filter>
</receiver>
(3)广播接收者实现和注册后,接下来,就需要对广播接收者进行封装。U盘音乐,蓝牙音乐,一般是需要启动一个服务在后台播放。
public class MusicService extends Service{
private AudioManager mAudioManager;
private ComponentName mComponentName;
@Override
public void onCreate() {
super.onCreate();
mComponentName = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
//音频管理器主要是对AudioService相关方法的封装,具体实现在AudioService中。
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
//这里只是讲解MediaButtonReceiver,具体的播放代码就不贴出来了
private void play(){
//当应用开始播放的时候首先需要请求焦点,调用该方法后,原先获取焦点的应用会释放焦点
mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
//对媒体播放按钮进行封装
if(mComponentName==null){
mComponentName = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
}
//注册封装的ComponentName
mAudioManager.registerMediaButtonEventReceiver(mComponentNa
me);
//省略具体播放内容。。。
}
}
(4),经过(1)、(2)、(3)步骤后,MediaButtonReceiver就已经注册成功。
发送并分发广播的实现
(1)发送媒体按键或者模拟系统按键。
//发送上一个媒体按键
sendMediaKeyEvent(KeyEvent.KEYCODE_MEDIA_PREVIOUS);
//发送下一个媒体按键
sendMediaKeyEvent(KeyEvent.KEYCODE_MEDIA_NEXT);
//发送暂停媒体按键
sendMediaKeyEvent(KeyEvent.KEYCODE_MEDIA_PAUSE);
//发送播放媒体按键
sendMediaKeyEvent(KeyEvent.KEYCODE_MEDIA_PLAY);
private void sendMediaKeyEvent(final int keyCode) {
//wait to handle onAbandonAudioFocus
mMediaKeyRunnable = new MediaKeyRunnbale(keyCode);
}
private MediaKeyRunnbale mMediaKeyRunnable;
private static class MediaKeyRunnbale implements Runnable {
int keyCode = -1;
public MediaKeyRunnbale(int keyCode) {
this.keyCode = keyCode;
}
@Override
public void run() {
//模拟按下抬起事件
sendEvent(KeyEvent.ACTION_DOWN, 0);
sendEvent(KeyEvent.ACTION_UP, 0);
}
private void sendEvent(int action, int flags) {
final int repeatCount = (flags & KeyEvent.FLAG_LONG_PRESS) != 0 ? 1 : 0;
//判断是否是长按事件
final KeyEvent ev = new KeyEvent(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), action, keyCode, repeatCount,
0, KeyCharacterMap.VIRTUAL_KEYBOARD, 0,
flags | KeyEvent.FLAG_FROM_SYSTEM | KeyEvent.FLAG_VIRTUAL_HARD_KEY,
InputDevice.SOURCE_KEYBOARD);
//调用InputManager中的injectInputEvent(...)方法。
InputManager.getInstance().injectInputEvent(ev,
InputManager.INJECT_INPUT_EVENT_MODE_ASYNC);
}
}
(2)InputManager类位于frameworks\base\core\java\android\hardware\input中。上一步调用的方法如下。下面的对象mIm是 IInputManager,具体实现在ImputManagService。
public boolean injectInputEvent(InputEvent event, int mode) {
if (event == null) {
throw new IllegalArgumentException("event must not be null");
}
if (mode != INJECT_INPUT_EVENT_MODE_ASYNC
&& mode != INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
&& mode != INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
throw new IllegalArgumentException("mode is invalid");
}
try {
return mIm.injectInputEvent(event, mode);
} catch (RemoteException ex) {
return false;
}
}
(3)InputManagerService位于frameworks\base\services\java\com\android\server\input目录下。上一步调用方法如下。该方法中最主要的一步 result = nativeInjectInputEvent(...);该方法是一个本地方法。这里涉及到Java和C语言之间的调用,c中的具体代码就不贴出来了。
@Override // Binder call
public boolean injectInputEvent(InputEvent event, int mode) {
if (event == null) {
throw new IllegalArgumentException("event must not be null");
}
if (mode != InputManager.INJECT_INPUT_EVENT_MODE_ASYNC
&& mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
&& mode != InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
throw new IllegalArgumentException("mode is invalid");
}
final int pid = Binder.getCallingPid();
final int uid = Binder.getCallingUid();
final long ident = Binder.clearCallingIdentity();
final int result;
try {
result = nativeInjectInputEvent(mPtr, event, pid, uid, mode,
INJECTION_TIMEOUT_MILLIS, WindowManagerPolicy.FLAG_DISABLE_KEY_REPEAT);
} finally {
Binder.restoreCallingIdentity(ident);
}
switch (result) {
case INPUT_EVENT_INJECTION_PERMISSION_DENIED:
Slog.w(TAG, "Input event injection from pid " + pid + " permission denied.");
throw new SecurityException(
"Injecting to another application requires INJECT_EVENTS permission");
case INPUT_EVENT_INJECTION_SUCCEEDED:
return true;
case INPUT_EVENT_INJECTION_TIMED_OUT:
Slog.w(TAG, "Input event injection from pid " + pid + " timed out.");
return false;
case INPUT_EVENT_INJECTION_FAILED:
default:
Slog.w(TAG, "Input event injection from pid " + pid + " failed.");
return false;
}
}
(4)、第3步调用到本地方法,本地方法经过一番处理之后就会回调AudioService.java中的代码,AudioService位于frameworks\base\media\java\android\media目录中
//==========================================================================================
// RemoteControl C代码处理完毕后,就会回调该方法。关于Java代码与本地代码的相互调用,可以看另一篇文章《Java代码与本地代码相互调用主要事项》
//==========================================================================================
public void dispatchMediaKeyEvent(KeyEvent keyEvent) {
//参数1,表示KeyEvent,参数2表示是否唤醒屏幕。
filterMediaKeyEvent(keyEvent, false );
}
//filterMediaKeyEvent()方法具体实现如下,主要对于不同的KeyEvent进行分发。
private void filterMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
// sanity check on the incoming key event
//如果KeyEvent为空则直接返回
if (!isValidMediaKeyEvent(keyEvent)) {
Log.e(TAG, "not dispatching invalid media key event " + keyEvent);
return;
}
// event filtering for telephony
//来电或者通话的时候,需要调用dispatchMediaKeyEventForCalls方法
synchronized(mRingingLock) {
synchronized(mRCStack) {
if ((mMediaReceiverForCalls != null) &&
(mIsRinging || (getMode() == AudioSystem.MODE_IN_CALL))) {
dispatchMediaKeyEventForCalls(keyEvent, needWakeLock);
return;
}
}
}
// event filtering based on voice-based interactions
if (isValidVoiceInputKeyCode(keyEvent.getKeyCode())) {
filterVoiceInputKeyEvent(keyEvent, needWakeLock);
} else {
dispatchMediaKeyEvent(keyEvent, needWakeLock);
}
}
//对声音按键进行处理,主要对声音按键按下抬起,长按短按的处理。
private void filterVoiceInputKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
if (DEBUG_RC) {
Log.v(TAG, "voice input key event: " + keyEvent + ", needWakeLock=" + needWakeLock);
}
int voiceButtonAction = VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS;
int keyAction = keyEvent.getAction();
synchronized (mVoiceEventLock) {
if (keyAction == KeyEvent.ACTION_DOWN) {
//表示短按
if (keyEvent.getRepeatCount() == 0) {
// initial down
mVoiceButtonDown = true;
mVoiceButtonHandled = false;
} else if (mVoiceButtonDown && !mVoiceButtonHandled
&& (keyEvent.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0) {
// long-press, start voice-based interactions
mVoiceButtonHandled = true;
voiceButtonAction = VOICEBUTTON_ACTION_START_VOICE_INPUT;
}
} else if (keyAction == KeyEvent.ACTION_UP) {
if (mVoiceButtonDown) {
// voice button up
mVoiceButtonDown = false;
if (!mVoiceButtonHandled && !keyEvent.isCanceled()) {
voiceButtonAction = VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS;
}
}
}
}//synchronized (mVoiceEventLock)
// take action after media button event filtering for voice-based interactions
switch (voiceButtonAction) {
case VOICEBUTTON_ACTION_DISCARD_CURRENT_KEY_PRESS:
if (DEBUG_RC) Log.v(TAG, " ignore key event");
break;
case VOICEBUTTON_ACTION_START_VOICE_INPUT:
if (DEBUG_RC) Log.v(TAG, " start voice-based interactions");
// then start the voice-based interactions
startVoiceBasedInteractions(needWakeLock);
break;
case VOICEBUTTON_ACTION_SIMULATE_KEY_PRESS:
if (DEBUG_RC) Log.v(TAG, " send simulated key event, wakelock=" + needWakeLock);
sendSimulatedMediaButtonEvent(keyEvent, needWakeLock);
break;
}
}
private void dispatchMediaKeyEventForCalls(KeyEvent keyEvent, boolean needWakeLock) {
Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
keyIntent.setPackage(mMediaReceiverForCalls.getPackageName());
if (needWakeLock) {
mMediaEventWakeLock.acquire();
keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED, WAKELOCK_RELEASE_ON_FINISHED);
}
final long ident = Binder.clearCallingIdentity();
try {
mContext.sendOrderedBroadcastAsUser(keyIntent, UserHandle.ALL,
null, mKeyEventDone, mAudioHandler, Activity.RESULT_OK, null, null);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
//对普通按键进行处理,一般就是自定义的一些KeyEvent
private void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
if (needWakeLock) {
//唤醒屏幕
mMediaEventWakeLock.acquire();
}
//发送ACTION_MEDIA_BUTTON广播
Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
synchronized(mRCStack) {
//mRCStack该对象是一个栈数据结构,主要对PendingIntent进行封装
if (!mRCStack.empty()) {
// send the intent that was registered by the client
try {
//取出栈顶的PendingIntent,这里就是关键,为什么当前获取焦点的
界面才会收到广播。
mRCStack.peek().mMediaIntent.send(mContext,
needWakeLock ? WAKELOCK_RELEASE_ON_FINISHED : 0 /*code*/,
keyIntent, AudioService.this, mAudioHandler);
} catch (CanceledException e) {
Log.e(TAG, "Error sending pending intent " + mRCStack.peek());
e.printStackTrace();
}
} else {
// legacy behavior when nobody registered their media button event receiver
// through AudioManager
if (needWakeLock) {
keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED, WAKELOCK_RELEASE_ON_FINISHED);
}
final long ident = Binder.clearCallingIdentity();
try {
mContext.sendOrderedBroadcastAsUser(keyIntent, UserHandle.ALL,
null, mKeyEventDone,
mAudioHandler, Activity.RESULT_OK, null, null);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
}
}
(5)看完第(4)步大家可能不是很理解Pending是如何与RCStack产生联系的,这里就来讲解PendingIntent是如何入栈,如何出栈的。
当客户端调用
mAudioManager.registerMediaButtonEventReceiver(mComponentName);时,这时会间接调用frameworks\base\media\java\android\media目录下的AudioService.java类中的方法pushMediaButtonReceiver,具体实现如下:
private void pushMediaButtonReceiver(PendingIntent mediaIntent, ComponentName target) {
// already at top of stack?
if (!mRCStack.empty() && mRCStack.peek().mMediaIntent.equals(mediaIntent)) {
return;
}
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
RemoteControlStackEntry rcse = null;
boolean wasInsideStack = false;
while(stackIterator.hasNext()) {
rcse = (RemoteControlStackEntry)stackIterator.next();
if(rcse.mMediaIntent.equals(mediaIntent)) {
wasInsideStack = true;
stackIterator.remove();
break;
}
}
if (!wasInsideStack) {
rcse = new RemoteControlStackEntry(mediaIntent, target);
}
//主要代码,入栈。
mRCStack.push(rcse);
// post message to persist the default media button receiver
mAudioHandler.sendMessage( mAudioHandler.obtainMessage(
MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0, target/*obj*/) );
}
当客户端调用
mAudioManager.unregisterMediaButtonEventReceiver(mComponentName);时,这时会间接调用frameworks\base\media\java\android\media目录下的AudioService.java类中的方法removeMediaButtonReceiverForPackage,具体实现如下:
private void removeMediaButtonReceiverForPackage(String packageName) {
synchronized(mRCStack) {
if (mRCStack.empty()) {
return;
} else {
RemoteControlStackEntry oldTop = mRCStack.peek();
Iterator<RemoteControlStackEntry> stackIterator = mRCStack.iterator();
// iterate over the stack entries
while(stackIterator.hasNext()) {
RemoteControlStackEntry rcse = (RemoteControlStackEntry)stackIterator.next();
if (packageName.equalsIgnoreCase(rcse.mReceiverComponent.getPackageName())) {
// a stack entry is from the package being removed, remove it from the stack
stackIterator.remove();
rcse.unlinkToRcClientDeath();
}
}
if (mRCStack.empty()) {
// no saved media button receiver
mAudioHandler.sendMessage(
mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0,
null));
} else if (oldTop != mRCStack.peek()) {
// the top of the stack has changed, save it in the system settings
// by posting a message to persist it
mAudioHandler.sendMessage(
mAudioHandler.obtainMessage(MSG_PERSIST_MEDIABUTTONRECEIVER, 0, 0,
mRCStack.peek().mReceiverComponent));
}
}
}
}