我试图弄清楚 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;
}
}
}