清除所有Activity

有这样的需求:进入一个Activity并关闭app其他所有Activity。试了在Intent中添加clear_top和new_task的flag都没效果,现在的解决方案如下:

    public class ActiivtyStack {  
    private static Stack<Activity> mActivityStack = new Stack<Activity>();  
    private static ActiivtyStack instance = new ActiivtyStack();  
  
    private ActiivtyStack() {  
    }  
  
    public static ActiivtyStack getScreenManager() {  
        return instance;  
    }  
  
    // 弹出当前activity并销毁  
    public void popActivity(Activity activity) {  
        if (activity != null) {  
            activity.finish();  
            mActivityStack.remove(activity);  
            activity = null;  
        }  
    }  
  
    // 将当前Activity推入栈中  
    public void pushActivity(Activity activity) {  
        mActivityStack.add(activity);  
    }  
  
    // 退出栈中所有Activity  
    public void clearAllActivity() {  
        while (!mActivityStack.isEmpty()) {  
            Activity activity = mActivityStack.pop();  
            if (activity != null) {  
                activity.finish();  
            }  
        }  
    }  
  
}  

在Activity执行onCreate时将activity推入栈中,onDestory中弹出activity,在需要销毁所有activity时clearAllActivity即可:

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        Log.i("jone", "base onCreate");  
        // 每次加入stack  
        ActiivtyStack.getScreenManager().pushActivity(this);  
  
    }  
  
    @Override  
    protected void onDestroy() {  
        Log.i("jone", "base Destory");  
        // 退出时弹出stack  
        ActiivtyStack.getScreenManager().popActivity(this);  
        super.onDestroy();  
  
    }  
    原文作者:Qin0821
    原文地址: https://www.jianshu.com/p/3c1e63bf44ef
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞