耳机按键控制Android 5.0

时间:2016-11-13 14:04:10

标签: android android-mediasession

我正在编写一个程序,按下按下耳机按钮,然后根据按下它的次数和次数做不同的事情。寻求api级别21. Android 5.0。 所以我可以抓住按钮按下,但是当启动一个MP3播放器然后它开始按下按钮按下。我怎么能防止这种情况? 第二个问题你如何恢复暂停的mp3,它和其他程序不是我的程序播放mp3。

 audioSession = new MediaSession(getApplicationContext(), "TAG11");
    MsCallback=     new MediaSession.Callback() {

        @Override
        public boolean onMediaButtonEvent(final Intent mediaButtonIntent) {
            String intentAction = mediaButtonIntent.getAction();
            Log.i("onMediaButtonEvent", intentAction );
            if (Intent.ACTION_MEDIA_BUTTON.equals(intentAction)) {
                KeyEvent event = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);

                if (event != null) {
                    if(toast!=null){
                        toast.cancel();
                    }
                    toast = Toast.makeText(getApplicationContext(), "headsetbutton press", Toast.LENGTH_SHORT);
                    toast.show();
                }
            }
            return super.onMediaButtonEvent(mediaButtonIntent);
        }


    };
    audioSession.setCallback(MsCallback);

    PlaybackState state = new PlaybackState.Builder()
            .setActions(PlaybackState.ACTION_PLAY_PAUSE)
            .setState(PlaybackState.STATE_PLAYING, 0, 0, 0)
            .build();
    audioSession.setPlaybackState(state);
    audioSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);

    audioSession.setActive(true);

1 个答案:

答案 0 :(得分:0)

为了收听媒体密钥事件,请在清单文件中声明广播接收器,如此

<receiver android:name=".RemoteControlReceiver">
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </receiver>

RemoteControlReceiver类扩展BroadcastReceiver并提取关键事件和关键代码,如此

 @Override
public void onReceive(Context context, Intent intent) {
    Log.d(TAG, "onReceive: ");
    if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
        KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
        int keyCode = event.getKeyCode();

    }
}

每个耳机上的基本按钮通常是Pause/Play按钮