在android.app; Application中ActivityLifecycleCallbacks 对activity的生命周期事件进行集中处理
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);
}
在Application中注册ActivityLifecycleCallbacks接口
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
LogUtils.i("[--------"+getFragmentNameTAG(activity)+"--------onActivityCreated--------]");
addActivity(activity); //把activity 添加Activity到堆栈
}
@Override
public void onActivityStarted(Activity activity) {
LogUtils.i("[--------"+activity.getPackageName()+"--------onActivityStarted--------]");
}
@Override
public void onActivityResumed(Activity activity) {
LogUtils.i("[--------"+getFragmentNameTAG(activity)+"--------onActivityResumed--------]");
}
@Override
public void onActivityPaused(Activity activity) {
LogUtils.i("[--------"+getFragmentNameTAG(activity)+"--------onActivityPaused--------]");
}
@Override
public void onActivityStopped(Activity activity) {
LogUtils.i("[--------"+getFragmentNameTAG(activity)+"--------onActivityStopped--------]");
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
LogUtils.i("[--------"+getFragmentNameTAG(activity)+"--------onActivitySaveInstanceState--------]");
}
@Override
public void onActivityDestroyed(Activity activity) {
LogUtils.i("[--------"+getFragmentNameTAG(activity)+"--------onActivityDestroyed--------]");
removeActivity(activity);
}
});
让activity实现自定义接口;
public interface IActivity {
@LayoutRes
int getContentViewLayoutRes();
void initData();
}
在 ActivityLifecycleCallbacks中onActivityCreated方法中给activity设置布局文件
if (activity instanceof IActivity){
activity.setContentView(((IActivity) activity).getContentViewLayoutRes());
((IActivity)activity).initData();
}else if(activity instanceof VActivity){...}
在activity中实现butterknife绑定
public class ButterKnifeSerializable implements Serializable {
private Unbinder unbinder;
public void setUnbinder(Unbinder unbinder){
this.unbinder = unbinder;
}
public Unbinder getUnbinder(){
return unbinder;
}
}
在ActivityLifecycleCallbacks中onActivityCreated方法中实现butterknife绑定
ButterKnifeSerializable bean = new ButterKnifeSerializable();
Unbinder unbinder = ButterKnife.bind(activity);
bean.setUnbinder(unbinder);
activity.getIntent().putExtra("ButterKnifeSerializable", bean);
在ActivityLifecycleCallbacks中onActivityDestroyed方法中实现butterknife解绑
ButterKnifeSerializable bean = (ButterKnifeSerializable) activity.getIntent().getSerializableExtra("ButterKnifeSerializable"); bean.getUnbinder().unbind();