androidandroid-lifecycleandroid-background

android, how to tell whether the app is in killed state by packagename


Having an android app which has service running to listen to the FCM notification.

By app in killed state I mean when swipe off the app from the recent activist app list, or close the app by tapping on the home button, or backpress on the app until the app closes (after all activities are popped out from backstack), or for any reason the OS killed the app.

There are functions could be used with the app's packagename to get some app's state info.

this one can help to tell the app is in background, but may not be killed.

public class ArchLifecycleApp extends Application implements LifecycleObserver {

    @Override
    public void onCreate() {
        super.onCreate();
        ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    public void onStop() {
        //App in background
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    public void onStart() {
        // App in foreground
    }
}

this one can tell app is in FG only:

   boolean isAppInFG(Context appContext, String packageName) {
        boolean appInFG = false;

        ActivityManager activityManager = (ActivityManager) appContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
        if (appProcesses != null) {
            
            for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND &&
                        appProcess.processName.equals(packageName)) {
                    appInFG = true;
                    break;
                }
            }
        }

        return appInFG;
    }

after pressed home button, or swipe out the app from the recent application list, the appProcess.importance is always 300 and is same as if the app is in background (covered by other app).

Question: in this case is there way to tell the app is killed (not just simply in background)?


Solution

  • In a comment you wrote:

    I want to determine: should the app go through a fresh re-launch (app is killed) or just bring the app to front?

    If you use a "launch Intent", this will handle all of this for you. If the app is already running, it will just bring the app to the foreground in whatever state it was in. If the app is not running, it will launch the app fresh.

    To get a "launch Intent", you can use PackageManager.getLaunchIntentForPackage()