Detect if an app is started/resumed from 'outside' the app

*爱你&永不变心* 提交于 2019-12-01 06:28:44

It's an older question but still relevant. There is a simple solution using ActivityLifeCycleCallbacks. This answer is derived from this blogpost by Micahel Bradshaw. He explains the concept

The key is in understanding how activities coordinate with each other. When switching between activities A and B, their methods are called in this order:

A.onPause();

B.onCreate();

B.onStart();

B.onResume(); (Activity B now has user focus)

A.onStop(); (if Activity A is no longer visible on screen)

Solution: You create a class which implements Application.ActivityLifecycleCallbacks interface and keep count of resumed and stopped activities.

public class AppLifecycleHelper implements Application.ActivityLifecycleCallbacks {

// I use two separate variables here. You can, of course, just use one and
// increment/decrement it instead of using two and incrementing both.
private static int resumed;
private static int stopped;

    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    }

    public void onActivityDestroyed(Activity activity) {
    }

    public void onActivityResumed(Activity activity) {
        ++resumed;
    }

    public void onActivityPaused(Activity activity) {
    }

    public void onActivitySaveInstanceState(Activity activity, Bundle     outState) {
    }

    public void onActivityStarted(Activity activity) {
        if (!isApplicationInForeground()){
            // resumed and stopped both are 0,
            // that means it is the first activity to come on display
            // i.e. App is launched from outside the app
        }
    }

    public void onActivityStopped(Activity activity) {
        ++stopped;
        if (!isApplicationInForeground()){
            // resumed and stopped both are 0
            // That means there is NO Activity in resumed state when this activity stopped
            // i.e. User came out of the App, perform all Application wide persistence tasks over here
        }
    }

    /**
     * Checks whether App is visible to the user or not
     * @return true if visible and false otherwise
     */
    public static boolean isApplicationInForeground() {
        return resumed > stopped;
    }

}

And then in your Application's onCreate() register this class for Activity callbacks like this

registerActivityLifecycleCallbacks(new AppLifecycleHelper());

and that's it! No need to add any code to every activity. Everything is contained in AppLifecycleHelper with just a few lines of code.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!