How to check if the Android application is running in foreground, in background, or is killed? (API level 27+)

3.2k Views Asked by At

I have this code snippet in my Android application, that checks if the app is killed or not.

    static boolean isAppKilled(Context appContext) {
        boolean appProcessRunning = false;

        ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses != null) {
            String packageName = appContext.getPackageName();
            for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
                System.out.println("LM:appProcess: " + appProcess.processName);
                System.out.println("LM:appProcess: " + appProcess.importance);
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE &&
                        appProcess.processName.equals(packageName)) {
                    appProcessRunning = true;
                    break;
                }
            }
        }

        return appProcessRunning;
    }

But, this snippet returns "true" for the application in the background also, which is not intended.

enter image description here

Can any of you please provide me a code snippet to fulfill all the above cases?

1

There are 1 best solutions below

0
On

You can implement LifecycleObserver interface in you Application class and implement lifecycle method:

 class YourApp : Application, LifecycleObserver {
    
        override fun onCreate() { ....}
    
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onAppInForeground {
            //do some logic to handle onForeground event.
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onAppInBackground {
                //do some logic to handle onBackground event.
            }
        }

But you need to add dependency to your gradle file:

// ProcessLifecycleOwner provides a lifecycle for the whole application process
  implementation("androidx.lifecycle:lifecycle-process:$lifecycle_version")

For more information check the link: https://developer.android.com/topic/libraries/architecture/lifecycle