Android开发常用的工具类(二) ActivityManager 管理Activity

其他文章:
Android开发常用工具类(一) SPUtils
AAndroid开发常用的工具类(三) ImageUtils添加文字或图片水印

ActivityManager
调用pushOneActivity,把一个activity压入栈中,可以创建一个BaseActivity,调用这个方法,其他Activity继承当前Activity

public class BaseActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.getInstance().pushOneActivity(this);
    }
}

import android.app.Activity;
import java.util.Stack;

/**
 * ActivityManager
 *
 */
public class ActivityManager {
    private static ActivityManager instance;
    private Stack activityStack;// activity栈

    // 单例模式
    public static ActivityManager getInstance() {
        if (instance == null) {
            instance = new ActivityManager();
        }
        return instance;
    }

    // 把一个activity压入栈中
    public void pushOneActivity(Activity actvity) {
        if (activityStack == null) {
            activityStack = new Stack();
        }
        activityStack.add(actvity);
    }

    // 获取栈顶的activity,先进后出原则
    public Activity getLastActivity() {
        return activityStack.lastElement();
    }

    // 移除一个activity
    public void popOneActivity(Activity activity) {
        if (activityStack != null && activityStack.size() > 0) {
            if (activity != null) {
                activity.finish();
                activityStack.remove(activity);
                activity = null;
            }

        }
    }

    // 退出所有activity
    public void finishAllActivity() {
        if (activityStack != null) {
            while (activityStack.size() > 0) {
                Activity activity = getLastActivity();
                if (activity == null)
                    break;
                popOneActivity(activity);
            }
        }

    }
}

你可能感兴趣的:(Android开发常用的工具类(二) ActivityManager 管理Activity)