androidonpausescreen-lock

Check whether onPause state of activity is called due to screen lock


If my app is running and I press lock screen button, it will put the app in background.What is the method to check whether onPause() is called by screen lock?.Thanks in advance.


Solution

  • All you have to do is check if the screen is on or not.

    @Override
    protected void onPause() {
        super.onPause();
    
        PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    
        boolean screenOn;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
            screenOn = pm.isInteractive();
        } else {
            screenOn = pm.isScreenOn();
        }
    
        if (screenOn) {
            // Screen is still on, so do your thing here
        }
    }