我有一个活动计时器应用程序,我在其中覆盖了onPause()方法,以便在用户按下主页或后退按钮时暂停计时器。但是,我希望计时器在用户手动关闭屏幕的情况下继续移动,但我知道这也将调用onPause()方法。有没有办法解决这个问题?
答案 0 :(得分:0)
您可以覆盖onBackPressed
以允许您在按下后退按钮时添加一些额外的逻辑。但是,更好的方法可能是将代码放在onStop()
中,只有当另一个Activity移动到前台时才会调用它。
有关详细信息,请参阅Android Docs
答案 1 :(得分:0)
我最终通过检测并忽略onPause()方法中的屏幕关闭事件来做到这一点。有关如何执行此操作的说明,请访问:http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
具体来说,我在评论中使用了这段代码(由Kyle提供):
@Override
protected void onCreate() {
// initialize receiver
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
//NEW
PowerManager pm =(PowerManager) getSystemService(Context.POWER_SERVICE);
// your code
}
@Override
protected void onPause() {
// when the screen is about to turn off
// Use the PowerManager to see if the screen is turning off
if (pm.isScreenOn() == false) {
// this is the case when onPause() is called by the system due to the screen turning off
System.out.println(“SCREEN TURNED OFF”);
} else {
// this is when onPause() is called when the screen has not turned off
}
super.onPause();
}