我开发了一个游戏使用andengine
我在使用电源时遇到问题Button
。如果我Button
在玩游戏时按下电源,屏幕会关闭,并且onPause()
会按预期调用。但是当我再次按下HOME
按钮或POWER
按钮打开屏幕时,onResume()
方法被调用但lockscreen
显示出来。
在onResume()
方法中,我恢复了游戏的音乐。
所以结果lockscreen
出现了,但游戏音乐在后台播放。我不想播放中的音乐lockscreen
。请帮我解决这个问题。谢谢
解决方案在这里:屏幕解锁时的活动句柄
通过注册BroadcastReceiver
过滤Intent.ACTION_SCREEN_ON
,Intent.ACTION_SCREEN_OFF
和Intent.ACTION_SCREEN_PRESENT
操作,您将能够处理以下 3 种情况:
Intent.ACTION_SCREEN_OFF
:当POWER
按下按钮并且屏幕变黑时。Intent.ACTION_SCREEN_ON
:当POWER
再次按下按钮并显示锁屏时。Intent.ACTION_SCREEN_PRESENT
: 当你通过 locksreen 并回到你的游戏中时。但是,在我的情况下(使用带有 Froyo 2.2 的 Galaxy S GT I9000)在处理HOME
按钮时不会调用这些操作(我认为这是一种一般行为)。
HOME
处理暂停和POWER
恢复音乐的按钮的一种简单快速(但可能不是最好的)方法可能是保留onPause
andonResume
方法并使用像这样的简单布尔标志:
private boolean mPowerButton = false;
@Override
public void onPause() {
super.onPause();
// Pause your music
Log.d("Game activity", "Music paused");
}
@Override
public void onResume() {
super.onResume();
if (!this.mPowerButton) {
// Resume your music
Log.d("Game activity", "[HOME button] Music resumed inside onResume");
}
}
public class receiverScreen extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// This is the lockscreen, onResume has been already called at this
// step but the mPowerButton boolean prevented the resumption of music
}
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
LevelActivity.this.mPowerButton = true;
}
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
// Resume your music
Log.d("Game activity", "[POWER button] Music resumed inside ACTION_USER_PRESENT action");
LevelActivity.this.mPowerButton = false;
}
}
}
希望能帮助到你!