通常我们监听Activity的声明周期都是在每个Activity中重写声明周期函数,这里介绍一种方法统一在Application中监听Activity的声明周期:
public class MyApplication extends Application {
//声明一个监听Activity们生命周期的接口
private ActivityLifecycleCallbacks activityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
/**
* application下的每个Activity声明周期改变时,都会触发以下的函数。
*/
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
//如何区别参数中activity代表你写的哪个activity。
if (activity.getClass() == MainActivity.class)
Log.d(TAG, "MainActivityCreated.");
else if(activity.getClass()== SecondActivity.class)
Log.d(TAG, "SecondActivityCreated.");
}
@Override
public void onActivityStarted(Activity activity) {
Log.d(TAG, "onActivityStarted.");
}
@Override
public void onActivityResumed(Activity activity) {
Log.d(TAG, "onActivityResumed.");
}
@Override
public void onActivityPaused(Activity activity) {
Log.d(TAG, "onActivityPaused.");
}
@Override
public void onActivityStopped(Activity activity) {
Log.d(TAG, "onActivityStopped.");
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
Log.d(TAG, "onActivityDestroyed.");
}
};
@Override
public void onCreate() {
super.onCreate();
//注册自己的Activity的生命周期回调接口。
registerActivityLifecycleCallbacks(activityLifecycleCallbacks);
}
}
这样每个Activity的进出声明周期都能监听到