简体   繁体   中英

Android: Using onPause() Selectively

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?

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

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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM