我已经实现了与Android notification of screen off/on类似的功能,但是它没有按预期的方式工作。我只想在屏幕关闭时停止音乐。我创建了一个像这样的屏幕操作类
public class ScreenAction extends BroadcastReceiver {
public static boolean wasScreenOn = true;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// AND DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = true;
}
}
}
然后,在我创建的主要活动中,我有这个
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenAction();
registerReceiver(mReceiver, filter);
在暂停的主要活动中,我有类似这样的内容:
public void onPause() {
super.onPause();
if (ScreenAction.wasScreenOn) {
final MediaPlayer mp = MediaPlayer.create(this, R.raw.pcmouseclick1);
mp.setVolume(.1f, .1f);
mp.start();
if (buttonState) {
mServ.reduceVolume();
}
}
}
我从一个在线资源中找到了这个,但是我遇到了问题。似乎屏幕状态始终设置为true,但我不确定如何更改此状态。
[我如何利用此ScreenAction类在用户锁定屏幕后仅在暂停状态下关闭音乐?我觉得我在onPause中缺少了一些东西,因为在onCreate中,我链接到该类。
@Override
protected void onPause() {
// when the screen is about to turn off
// or when user is switching to another application
super.onPause();
}
@Override
protected void onResume() {
// only when screen turns on
// or when user returns to application
super.onResume();
}
[您可以在android中查看Activity的整个生命周期:Activity Lifecycle
也许您也可以直接从接收器开始和停止音乐:
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Pause music player
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// Resume music player
}
}
您正在检查ScreenAction.wasScreenOn
中的onPause
,但这正在之前调用BroadcastReceiver
来通知您屏幕已关闭。因此,此时ScreenAction.wasScreenOn
仍然为true,然后将其设置为false,但是onPause
已经运行,因此您的音乐永远不会暂停。
要解决此问题,您应该直接采取措施应对BroadcastReceiver
中的屏幕关闭。如果您需要与UI进行交互,请考虑使用诸如LiveData之类的解决方案作为抽象,这样您就不必依赖于在屏幕关闭的确切时间暂停Activity(也请考虑onPause
解决方案不会如果您的“活动”当前不可见,则可以正常工作)。