ActivityLifecycleCallbacks

4.0(API Level 14)新增了一个Application接口ActivityLifecycleCallbacks
Application通过此接口提供了一套回调方法,用于让开发者对Activity的生命周期事件进行集中处理。
为什么用ActivityLifecycleCallbacks?
以往若需监测Activity的生命周期事件代码,你可能是这样做的,重写每一个Acivity的onResume()

重写Application的onCreate()方法,或在Application的无参构造方法内,调用Application.registerActivityLifecycleCallbacks()方法,并实现ActivityLifecycleCallbacks接口

public void onCreate() {
super.onCreate();
this.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

@Override
public void onActivityStopped(Activity activity) {
Logger.v(activity, “onActivityStopped”);
}

@Override
public void onActivityStarted(Activity activity) {
Logger.v(activity, “onActivityStarted”);
}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
Logger.v(activity, “onActivitySaveInstanceState”);
}

@Override
public void onActivityResumed(Activity activity) {
Logger.v(activity, “onActivityResumed”);
}

@Override
public void onActivityPaused(Activity activity) {
Logger.v(activity, “onActivityPaused”);
}

@Override
public void onActivityDestroyed(Activity activity) {
Logger.v(activity, “onActivityDestroyed”);
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
Logger.v(activity, “onActivityCreated”);
}
});
};

应用:ActivityManager:
public class ActivityManager implements Application.ActivityLifecycleCallbacks {
private static ActivityManager manager = new ActivityManager();
public static ActivityManager get () {
return manager;
}
private LinkedList stack = new LinkedList<>();

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
if (!stack.contains(activity)) {
stack.add(activity);
}
}

@Override
public void onActivityStarted(Activity activity) {

}

@Override
public void onActivityResumed(Activity activity) {

}

@Override
public void onActivityPaused(Activity activity) {

}

@Override
public void onActivityStopped(Activity activity) {

}

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

}

@Override
public void onActivityDestroyed(Activity activity) {
if (stack.contains(activity)) {
stack.remove(activity);
}
}

public Activity topActivity () {
Activity activity = null;
if (!stack.isEmpty()) {
activity = stack.getLast();
}
return activity;
}

public void registerSelf(Context context) {
Application application = (Application) context.getApplicationContext();
application.registerActivityLifecycleCallbacks(ActivityManager.get());
}

你可能感兴趣的:(Android)