Android ActivityLifecycle生命周期管理
全局的所有Activity生命周期监听管理类
public class RegisterActivityListener implements Application.ActivityLifecycleCallbacks {
private final ActivityManager activityManager;
public RegisterActivityListener() {
activityManager = ActivityManager.getInstance();
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
activityManager.addActivity(activity);
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
activityManager.removeActivity(activity);
}
}
Activity栈管理工具类
public class ActivityManager {
public static final String TAG = "ActivityManager";
private Stack<WeakReference<Activity>> mActivityStack;
private static volatile ActivityManager mInstance = new ActivityManager();
private ActivityManager() {
}
public static ActivityManager getInstance() {
if (mInstance == null) {
synchronized (ActivityManager.class) {
if (mInstance == null) {
mInstance = new ActivityManager();
}
}
}
return mInstance;
}
/**
* 入栈
* @param activity activity实例
*/
public void addActivity(Activity activity) {
if (mActivityStack == null) {
mActivityStack = new Stack<>();
}
mActivityStack.add(new WeakReference<>(activity));
TLog.i(TAG, "add new activity to stack");
}
/**
* 出栈
* @param activity
*/
public void removeActivity(Activity activity) {
if (mActivityStack != null) {
mActivityStack.remove(new WeakReference<>(activity));
TLog.i(TAG, "remove activity by stack");
}
}
/**
* 获取当前Activity
* @return 当前(栈顶)activity
*/
public Activity currentActivity() {
if (mActivityStack != null && !mActivityStack.isEmpty()) {
return mActivityStack.lastElement().get();
}
return null;
}
}
自定义MainApplication注册监听
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
registerActivityLifecycleCallbacks(new RegisterActivityListener());
}
注:以上代码皆来源于与网络,若有侵权请联系删除。
|