0

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

1 回答 1

0

问题是我没有MediaSession. 像 Spotify 这样的应用程序使用 aMediaSession来捕获后台点击。应用程序在后台查找最后一个活动的 mediaSession,如果它不活动,那么它将尝试重新启动它(如果在后台)。

编辑:如果您有 MediaSession,则根本不需要我包含的类来捕获媒体按钮。

于 2018-01-22T07:33:17.473 回答