在应用程序的BaseApplication类中添加如下代码:
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
Log.d("ActivityLifecycle", activity.getLocalClassName() + " created");
}
@Override
public void onActivityStarted(Activity activity) {
Log.d("ActivityLifecycle", activity.getLocalClassName() + " started");
}
@Override
public void onActivityResumed(Activity activity) {
Log.d("ActivityLifecycle", activity.getLocalClassName() + " resumed");
}
@Override
public void onActivityPaused(Activity activity) {
Log.d("ActivityLifecycle", activity.getLocalClassName() + " paused");
}
@Override
public void onActivityStopped(Activity activity) {
Log.d("ActivityLifecycle", activity.getLocalClassName() + " stopped");
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
Log.d("ActivityLifecycle", activity.getLocalClassName() + " destroyed");
}
});
}
}
这样,就可以在应用程序中监测到所有Activity的生命周期,从而进行相应的操作。