首先,自定义一个ActivityManager管理类,用于管理栈中的Activity
1 public class ActivityManager{ 2 private static final String TAG = "ActivityManager"; 3 private static Stack<Activity> activityStack; 4 private static ActivityManager instance; 5 private Activity currActivity; 6 private ActivityManager(){ 7 } 8 9 public static ActivityManager getActivityManager(){ 10 if(instance == null){ 11 instance = new ActivityManager(); 12 } 13 return instance; 14 } 15 16 //退出栈顶Activity 17 public void popActivity(Activity activity){ 18 if(activity == null || activityStack == null){ 19 return; 20 } 21 if(activityStack.contains(activity)){ 22 activityStack.remove(activity); 23 } 24 currActivity = activity; 25 //activity.finish; 26 27 } 28 29 public void destoryActivity(Activity activity){ 30 if(activity == null){ 31 return; 32 } 33 activity.finish(); 34 if(activityStack.contains(activity)){ 35 activityStack.remove(activity); 36 } 37 activity=null; 38 } 39 40 //获得当前栈顶Activity 41 public Activity currentActivity(){ 42 if(activityStack == null||activityStack.empty()){ 43 return null; 44 } 45 return activityStack.lastElement(); 46 } 47 48 //将当前Activity推入栈中 49 public void pushActivity(Activity activity){ 50 if(activityStack == null){ 51 activityStack = new Stack<Activity>(); 52 } 53 activityStack.add(activity); 54 } 55 56 //退出栈中除指定的Activity外所有 57 public void popAllActivityExceptOne(Class cls){ 58 while(true){ 59 Activity activity = currentActivity(); 60 if(activity == null){ 61 break; 62 if(activity.getClass().equals(cls)) 63 break; 64 destroyActivity(activity); 65 } 66 } 67 68 //退出栈中所有Activity 69 public void popAllActivity(){ 70 popAllActivityExceptOne(null); 71 } 72 73 public Activity getCurrentActivity(){ 74 return currActivity; 75 } 76 77 public int getActivityStackSize(){ 78 int size = 0; 79 if(activityStack != null){ 80 size = activityStack.size(); 81 } 82 return size; 83 } 84 }
然后,在baseActivity中的两个方法添加如下方法(如果没有baseActivity,就得一个个加了)
1 @Override 2 protected void onPause(){ 3 super.onPause(); 4 ActivityManager.getActivityManager().pushActivity(this); 5 } 6 7 @Override 8 protected void onResume(){ 9 super.onResume(); 10 ActivityManager.getActivityManager().popActivity(this); 11 }
最后,根据需求判断,在需要清除所有activity的地方,加上如下代码
1 if(isRestart){ 2 ActivityManager.getActivityManager().popAllActivity(); 3 Intent intent = new Intent(this, LoadingActivity.class); 4 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 5 startActivity(intent); 6 isRestart=false; 7 this.finish(); 8 }
PS:清除掉所有activity后,startActivity时需要给它加上Intent.FLAG_ACTIVITY_CLEAR_TOP,表示start的这个activity置顶,并二次清除掉所有这个activity之上的activity。