I have a single activity timer application in which I have overridden the onPause() method to pause the timer when the user presses the home or back button. However, I would like the timer to keep moving in the case that the user manually turns off his screen, but I know this will also call the onPause() method. Is there any way to get around this?
Asked
Active
Viewed 232 times
2 Answers
0
You can override onBackPressed
to allow you to put some extra logic when the back button is pressed. However, a better approach might be to put your code in onStop()
, which is only called when another Activity is moved to the foreground.
See the Android Docs for more detail

Moshe
- 9,283
- 4
- 29
- 38
-
I don't see how this answers my question - my problem isn't with the back button but with turning the screen off. – John Roberts Jan 02 '13 at 03:06
-
I apologize, I should have been clearer. Instead of overriding `onPause` and pausing your timer there, move the timer-pausing logic to `onStop`. – Moshe Jan 02 '13 at 03:07
-
1Both onStop and onPause are called when the screen is turned off. – John Roberts Jan 02 '13 at 03:18
-
Darn. My mistake then. Sorry :( – Moshe Jan 02 '13 at 03:21
0
I ended up doing this by detecting and ignoring a screen turn off event inside the onPause() method. Instructions on how to do this can be found here: http://thinkandroid.wordpress.com/2010/01/24/handling-screen-off-and-screen-on-intents/
Specifically, I used this code from the comments (courtesy of 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();
}

John Roberts
- 5,885
- 21
- 70
- 124