活动的最佳实践------随时随地退出程序
1. 新建一个类ActivityCollector.java,活动收集器。
2. 设置一个用于存放所有活动的容器,所有活动追溯到头,都是派生于Activity。
package com.androidstudy.activityrecycletest; import android.app.Activity; import java.util.ArrayList; import java.util.List; public class ActivityCollector { public static List<Activity> activities = new ArrayList<>(); //向集合中添加Activity 每次打开一个新活动时 public static void addActivity(Activity activity){ if (activity != null){ activities.add(activity); } } //从集合中移除Activity public static void removeActivity(Activity activity){ activities.remove(activity); } //移除并关闭所有的Activity public static void finishAll(){ for (Activity activity:activities){//遍历所有活动 if (!activity.isFinishing()){//如果沒有正在被销毁 activity.finish(); } } activities.clear(); } }
3. 新建一个类 BaseActivity.java
package com.androidstudy.activityrecycletest; import android.os.Bundle; import android.os.PersistableBundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; public class BaseActivity extends AppCompatActivity { @Override public void onCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) { super.onCreate(savedInstanceState, persistentState); ActivityCollector.addActivity(this); } @Override protected void onDestroy() { super.onDestroy(); ActivityCollector.removeActivity(this); } }
4. 所有的活动,extend BaseActivity即可