我正在试图找出像Spotify这样的应用程序如何在屏幕关闭或锁定时捕获耳机按钮。我目前能够使用我的类HeadSetActionButtonReciever捕获按钮按下,只有当应用程序在前台时。但是,当应用程序处于后台时,我无法捕获这些点击。有人可以向我解释为什么会这样,以及如何在后台捕获它?
public class HeadsetActionButtonReceiver extends BroadcastReceiver {
public static Delegate delegate;
private static AudioManager mAudioManager;
private static ComponentName mRemoteControlResponder;
private static int doublePressSpeed = 300; // double keypressed in ms
private static Timer doublePressTimer;
private static int counter;
public interface Delegate {
void onMediaButtonSingleClick();
void onMediaButtonDoubleClick();
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent == null || delegate == null || !Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction()))
return;
KeyEvent keyEvent = (KeyEvent) intent.getExtras().get(Intent.EXTRA_KEY_EVENT);
if (keyEvent == null || keyEvent.getAction() != KeyEvent.ACTION_DOWN) return;
counter++;
if (doublePressTimer != null) {
doublePressTimer.cancel();
}
doublePressTimer = new Timer();
doublePressTimer.schedule(new TimerTask() {
@Override
public void run() {
if (counter == 1) {
delegate.onMediaButtonSingleClick();
} else {
delegate.onMediaButtonDoubleClick();
}
counter = 0;
}
}, doublePressSpeed);
}
public static void register(final Context context) {
mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
mRemoteControlResponder = new ComponentName(context, HeadsetActionButtonReceiver.class);
mAudioManager.registerMediaButtonEventReceiver(mRemoteControlResponder);
}
public static void unregister(final Context context) {
mAudioManager.unregisterMediaButtonEventReceiver(mRemoteControlResponder);
if (doublePressTimer != null) {
doublePressTimer.cancel();
doublePressTimer = null;
}
}
}
答案 0 :(得分:0)
问题是我没有MediaSession
。 Spotify等应用使用MediaSession
来捕获后台点击次数。应用程序在后台查找最后一个活动的mediaSession,如果它不活动,那么它将尝试重新启动它(如果在后台)。
编辑:如果您有MediaSession,则根本不需要我所包含的类来捕获媒体按钮。