美文网首页
Android耳机线控

Android耳机线控

作者: Aaglnny | 来源:发表于2018-06-23 12:32 被阅读0次

    注册耳机事件监听器

    private BroadcastReceiver headSetReceiver;
    private AudioManager mAudioManager;
    private ComponentName mComponentName;
    
    public void initHeadSetReceiver() {
            Log.i(TAG, "initHeadSetReceiver: ");
            headSetReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();
                    if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
                        // phone headset plugged
                        if (intent.getIntExtra("state", 0) == 1) {
                            // do something
                            Log.d(TAG, "耳机检测:插入");
                            ChatHelper.getTnstance().isHeadset = true;
    //                  Toast.makeText(context, "耳机检测:插入", Toast.LENGTH_SHORT) .show();
                            mAudioManager.registerMediaButtonEventReceiver(mComponentName);
                            // phone head unplugged
                        } else {
                            // do something
                            Log.d(TAG, "耳机检测:没有插入");
                            ChatHelper.getTnstance().isHeadset = false;
    //                  Toast.makeText(context, "耳机检测:没有插入", Toast.LENGTH_SHORT).show();
                            mAudioManager.unregisterMediaButtonEventReceiver(mComponentName);
                        }
                    }
                }
            };
        }
    
    public void initMediaButtonReceiver() {
            initHeadSetReceiver();
    
            if (mAudioManager == null) {
                mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
            }
            // AudioManager注册一个MediaButton对象
           mComponentName = new ComponentName(getPackageName(), MediaButtonReceiver.class.getName());
    
           mAudioManager.registerMediaButtonEventReceiver(mComponentName);
           getContext().registerReceiver(headSetReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
        }
    

    其中关键语句是

    mAudioManager.registerMediaButtonEventReceiver(mComponentName);
    

    当其他软件注册耳机监听事件后,系统就不会向该监听发送事件;
    解决方法:
    经测试,在小米5和华为mete9上使用MediaPlayer播放音频可以重新使系统向该监听发送事件,
    但是在OPPO和Vivo手机上无法起作用;

    查看registerMediaButtonEventReceiver源码

    image.png
    继续查看registerMediaButtonIntent方法
    image.png
    继续搜索MediaSessionLegacyHelper.addMediaButtonListener(pi, eventReceiver, getContext())方法
    //查看安卓源码网站http://androidxref.com
    image.png
    关键语句
    holder.mSession.setMediaButtonReceiver(pi);
    holder.update();
    
    image.png image.png

    由此可知只有一个MediaButtonReceiver能收到事件回调

    解决方法:

    mAudioManager.unregisterMediaButtonEventReceiver(mComponentName);
    mAudioManager.registerMediaButtonEventReceiver(mComponentName);
    

    至于为何需要调用unregisterMediaButtonEventReceiver方法,猜测某些ROM厂商修改了源码,对于已经注册过的不能重复注册

    更新:在小米MAX2 和华为mete9手机上,当APP处于后台时,无法抢占耳机控制权
    解决方法:使用MediaSession

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)//注意申明 API 21
    private void setMediaButtonEvent() {
            MediaSessionCompat mSession = new MediaSessionCompat(getContext(), "MediaSession");
            mSession.setCallback(
                    new MediaSessionCompat.Callback() {
                        @Override
                        public boolean onMediaButtonEvent(Intent intent) {
                            Log.i(TAG, "onMediaButtonEvent: ");
                            // 获得Action
                            String intentAction = intent.getAction();
                            // 获得KeyEvent对象
                            KeyEvent keyEvent = intent
                                    .getParcelableExtra(Intent.EXTRA_KEY_EVENT);
    
                            if (keyEvent == null) {
                                return false;
                            }
    
                            Log.i(TAG, "Action ---->" + intentAction + "  KeyEvent----->"
                                    + keyEvent.toString());
                            // 按下 / 松开 按钮
                            int keyAction = keyEvent.getAction();
                            Log.i(TAG, "onMediaButtonEvent: " + keyAction);
    
                            disposeKeyEvent(keyEvent, intentAction);
    
                            return true;
                        }
                    }
    
            );
            mSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
                    MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    //FLAG_HANDLES_MEDIA_BUTTONS 控制媒体按钮
    //FLAG_HANDLES_TRANSPORT_CONTROLS 控制传输命令
            mSession.setActive(true); //激活
    //      mSession.release(); //退出时需要销毁
            //更新播放状态和歌曲信息  //最重要
    
            PlaybackState.Builder stateBuilder = new PlaybackState.Builder().setActions(
                    PlaybackState.ACTION_PLAY
                            | PlaybackState.ACTION_PLAY_PAUSE
                            | PlaybackState.ACTION_PLAY_FROM_MEDIA_ID
                            | PlaybackState.ACTION_PAUSE
                            | PlaybackState.ACTION_SKIP_TO_NEXT
                            | PlaybackState.ACTION_SKIP_TO_PREVIOUS);
    
            stateBuilder.setState(PlaybackState.STATE_PLAYING,
                    PlaybackState.PLAYBACK_POSITION_UNKNOWN,
                    SystemClock.elapsedRealtime());
    
            if (mSession.getMediaSession() instanceof MediaSession) {
                Log.i(TAG, "setMediaButtonEvent: session.setPlaybackState");
                MediaSession session = (MediaSession) mSession.getMediaSession();
                session.setPlaybackState(stateBuilder.build());
            }
    }
    
    private void disposeKeyEvent(KeyEvent keyEvent, String intentAction) {
            int keyAction = keyEvent.getAction();
    
            if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
                //按下的是耳机中间按键
                // 获得按键字节码
                int keyCode = keyEvent.getKeyCode();
    
                if (KeyEvent.ACTION_UP == keyAction) {
                    Log.d(TAG, "action=ACTION_UP");
                    if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_HEADSETHOOK) {
                        Log.d(TAG, "action=ACTION_UP, keyCode=KEYCODE_HEADSETHOOK");
    
                       //松开了耳机按键
                    }
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:Android耳机线控

          本文链接:https://www.haomeiwen.com/subject/kdmryftx.html