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