Activity 的每一个生命周期都对应 ActivityLifecycleCallbacks 接口中的一个方法,比如 onActivityCreated 回调是在 Activity 的 onCreate 方法中调用 getApplication().dispatchActivityCreated(this, savedInstanceState) 完成对 Activity 生命周期跟踪监听。
注册生命周期监听
public class MyApplication extends Application{
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new AppLifecycleCallback());
}
}
生命周期回调
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class AppLifecycleCallback implements Application.ActivityLifecycleCallbacks {
@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
ActivityManager.Instance().addActivity(activity);
}
@Override
public void onActivityDestroyed(@NonNull Activity activity) {
ActivityManager.Instance().removeActivity(activity);
}
@Override
public void onActivityStarted(@NonNull Activity activity) {
}
@Override
public void onActivityResumed(@NonNull Activity activity) {
}
@Override
public void onActivityPaused(@NonNull Activity activity) {
}
@Override
public void onActivityStopped(@NonNull Activity activity) {
}
@Override
public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle bundle) {
}
}
管理 Activity
我这里为了避免退出程序后,之前进入第三方库的Activity未被销毁清除的情况,在app退出时遍历集
合 finish 所有的 Activity
import android.app.Activity;
import java.util.Stack;
public class ActivityManager {
private Stack<Activity> activities;
private static ActivityManager _instance;
public static ActivityManager Instance() {
if (_instance == null) {
_instance = new ActivityManager();
}
return _instance;
}
public void addActivity(Activity activity) {
if (activities == null) {
activities = new Stack<>();
}
if (activities.search(activity) == -1) {
activities.push(activity);
}
}
public void removeActivity(Activity activity) {
if (activities != null && activities.size() > 0 && activities.search(activity) != -1) {
activities.remove(activity);
}
}
public void Exit() {
if (activities != null && activities.size() > 0) {
while (!activities.empty()) {
Activity mActivity = activities.pop();
if (mActivity != null) {
mActivity.finish();
}
}
}
System.exit(0);
}
}