0

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?

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

2 Answers2

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
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