应用程序进入后台时调用的通用方法

时间:2017-01-12 20:33:58

标签: android

当应用程序进入后台时,是否有任何通用方法?我不想在活动发生变化时执行操作只是想在应用程序进入后台时执行它,即出现home_screen。

1 个答案:

答案 0 :(得分:2)

您可以使用ActivityLifeCycleCallbacks

来实现此目的
public class LifeCycleCallbacks implements Application.ActivityLifecycleCallbacks {

    /**
     * Keeps a count of the activities started.
     */
    private int mActivitiesStarted;
    /**
     * Keeps a count of the activities stopped.
     */
    private int mActivitiesStopped;

    @Override
    public void onActivityCreated(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityStarted(Activity activity) {
        if (mActivitiesStarted == mActivitiesStopped) {
            // This is the session start
        }
        ++mActivitiesStarted;
    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        ++mActivitiesStopped;
        if ((mActivitiesStarted > 0) && (mActivitiesStarted == mActivitiesStopped)) {
            /* This is session end. We can do things that we need to do when the app
            * session ends, i.e. send tracking info, etc. */
        }
    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}

最后,在LifeCycleCallbacks的{​​{1}}课程中注册Application课程:

onCreate