1

我正在编写一个程序来捕捉耳机按钮的按下,然后根据你按下它的时间和次数来做不同的事情。争取 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);
4

1 回答 1

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();

    }
}

每个耳机上的基本按钮通常是暂停/播放按钮

于 2016-11-15T19:53:56.100 回答