Search code examples
androidbackground-processlockscreenonpausetaskmanager

Check if application went to background including by power button


How can I check if my application has gone to the background, including as a response to the power button?

I use this method when onPause is called:

private static boolean isApplicationBroughtToBackground(Context c) {
    ActivityManager am = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
         ComponentName topActivity = tasks.get(0).topActivity;
         String activeActivity = topActivity.getPackageName();
         String myActivity = c.getPackageName();
         L.e("Active : " + activeActivity + "  , MyActivity : " + myActivity);
         if (!activeActivity.equals(myActivity)) {
             return true;
         }
    }
    return false;
}

and I call this method with 500ms delay to make sure the active task is changed.

The problem is that if you use the power button or other way to lock screen this method won't detect this.

How can I catch this scenario too?


Solution

  • Try this in onPause() to detect screen lock

    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        boolean isScreenOn = powerManager.isScreenOn();
    
        if (!isScreenOn) {
    
            // The screen has been locked 
    
        }