android-30
????ActivityLifecycleCallbacks 是 Application 的一个接口;
????Activity 的生命周期,对应 ActivityLifecycleCallbacks 中的方法;
????当实现ActivityLifecycleCallbacks 接口后,系统会在在调用 Activity 的方法后,再调用实现的ActivityLifecycleCallbacks 的实现方法。
public interface ActivityLifecycleCallbacks {
void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState);
void onActivityStarted(@NonNull Activity activity);
void onActivityResumed(@NonNull Activity activity);
void onActivityPaused(@NonNull Activity activity);
void onActivityStopped(@NonNull Activity activity);
void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState);
void onActivityDestroyed(@NonNull Activity activity);
}
创建MyApplication
public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks {
public static final String TAG = "MyApplication";
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
Log.d(TAG, "onActivityCreated: " + activity);
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
Log.d(TAG, "onActivityStarted: " + activity);
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
Log.d(TAG, "onActivityResumed: " + activity);
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
Log.d(TAG, "onActivityPaused: " + activity);
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
Log.d(TAG, "onActivityStopped: " + activity);
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
Log.d(TAG, "onActivitySaveInstanceState: " + activity);
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
Log.d(TAG, "onActivityDestroyed: " + activity);
}
}
修改 AndroidManifest.xml
增加:
android:name=".MyApplication"
效果
D/MyApplication: onActivityCreated: com.example.testlifecycle.MainActivity@e9f5a06
D/MyApplication: onActivityStarted: com.example.testlifecycle.MainActivity@e9f5a06
D/MyApplication: onActivityResumed: com.example.testlifecycle.MainActivity@e9f5a06
D/MyApplication: onActivityPaused: com.example.testlifecycle.MainActivity@e9f5a06
D/MyApplication: onActivityStopped: com.example.testlifecycle.MainActivity@e9f5a06
D/MyApplication: onActivityDestroyed: com.example.testlifecycle.MainActivity@e9f5a06
好记性不如烂笔头!
|