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