屏幕关闭时的Android捕获媒体按钮

时间:2017-02-18 00:26:17

标签: java android broadcastreceiver

我正在尝试捕捉屏幕关闭时按下媒体按钮的时间。首先,我使用getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);来保持我的活动超过锁定屏幕和PowerManager.PARTIAL_WAKE_LOCK(我知道这会消耗电池,但这只会在短时间内开启)。然后,要收听媒体按钮,我会覆盖public boolean onKeyDown(int keyCode, KeyEvent event)并使用if(keycode == KeyEvent.KEYCODE_HEADSETHOOK)。问题是如果屏幕关闭,这不起作用。

我见过有几个人使用BroadcastReceiver捕获媒体按钮,如果我的屏幕关闭了吗?

如果它不起作用,我可以在屏幕关闭时捕获该事件吗?

如果它能工作我将如何实现?因为我在这里尝试了一些例子,但是即使屏幕打开,我也无法让它工作。如果BroadcastReceiver能够正常工作,我可以发布到目前为止我所拥有的内容,即使屏幕打开也无法正常工作。

更新

我在use new media session class找到了类似的答案。我可以在按下媒体按钮时捕捉(即使屏幕关闭),但是当按下音量按钮时(屏幕打开或关闭)我不捕捉。这是我实施的内容:

mediaSession = new MediaSession(getApplicationContext(), this.getLocalClassName());

if (mediaSession == null) {
    Log.e("TEST", "initMediaSession: mediaSession = null");
    return;
}

mediaSessionToken = mediaSession.getSessionToken();

myVolumeProvider = new VolumeProviderCompat(VolumeProviderCompat.VOLUME_CONTROL_RELATIVE, 1000, 0) {
    @Override
    public void onAdjustVolume(int direction) {
    Log.d("TEST", "onAdjustVolume called: ");

    }
};

mediaSession.setPlaybackToRemote((VolumeProvider) myVolumeProvider.getVolumeProvider());
mediaSession.setCallback(new MediaSession.Callback()
{
    public boolean onMediaButtonEvent(Intent mediaButtonIntent) {
    Log.d("TEST", "onMediaButtonEvent called: " + mediaButtonIntent);
    return false;
    }

    public void onPause() {
    Log.d("TEST", "onPause called (media button pressed)");
    super.onPause();
    }

    public void onPlay() {
    Log.d("TEST", "onPlay called (media button pressed)");
    super.onPlay();
    }

    public void onStop() {
    Log.d("TEST", "onStop called (media button pressed)");
    super.onStop();
    }

});

mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);

PlaybackState state = new PlaybackState.Builder()
    .setActions(PlaybackState.ACTION_PLAY)
    .setState(PlaybackState.STATE_STOPPED, PlaybackState.PLAYBACK_POSITION_UNKNOWN, 0)
    .build();

mediaSession.setPlaybackState(state);

mediaSession.setActive(true);

0 个答案:

没有答案