MediaButtonReceiver相关笔记

注意: 写该文章主要帮助自己记忆,贴出来希望可以给有同样问题的人解惑,不喜勿喷,可以提意见哦。

一、待了解内容
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));
            }
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,293评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,604评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,958评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,729评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,719评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,630评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,000评论 3 397
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,665评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,909评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,646评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,726评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,400评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,986评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,959评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,996评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,481评论 2 342

推荐阅读更多精彩内容