目标
之前使用全局广播 + BaseActivity + Activity栈中位置判断 实现全局数据接收、全局弹框。实在是有点儿low,后面请教高人,发现一个十分简单的方式对所有的Activity的生命周期进行监听追踪,既节约了性能,也提升了B格。
ActivityLifecycleCallbacks简介
每个Activity生命周期的执行都会被此接口监听,可以通过注册此接口实现Activity生命周期的监听。
Application中接口源码:
public interface ActivityLifecycleCallbacks {
void onActivityCreated(Activity activity, Bundle savedInstanceState);
void onActivityStarted(Activity activity);
void onActivityResumed(Activity activity);
void onActivityPaused(Activity activity);
void onActivityStopped(Activity activity);
void onActivitySaveInstanceState(Activity activity, Bundle outState);
void onActivityDestroyed(Activity activity);
}
实现
1.接口实现类AppActivityLifecycleTracker中进行具体的操作:
/**
* Activity生命周期追踪
*
* @author fengzhen
* @version v1.0, 2017/7/13
*/
public class AppActivityLifecycleTracker implements Application.ActivityLifecycleCallbacks{
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
// 当acitivity启动,注册广播,进行监听
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
// 当activity停止,销毁广播,后台不进行广播监听
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
2.在继承自Application的BaseApplication的onCreate()方法中进行注册该tracer
@Override
public void onCreate() {
// 注册生命周期追踪
registerActivityLifecycleCallbacks(new AppLifecycleTracker());
}
如此,便更加简单、高效、灵活的实现的对app中所有acitivity生命周期的追踪。