Activity管理类

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;

import java.util.Stack;

/**
* 
*/

public final class ActivityMgr {

public final class Friend {
private ActivityMgr mgr;
public Friend(ActivityMgr mgr) {
this.mgr = mgr;
}
public void addActivity(Activity activity) {
this.mgr.addActivity(activity);
}
public void removeActivity(Activity activity) {
this.mgr.removeActivity(activity);
}
}

private Stack < Activity > activityStack;

public ActivityMgr() {
activityStack = new Stack < Activity > ();
}


public Stack getActivityStack() {
return activityStack;
}

/**
* 获取当前Activity(堆栈中最后一个压入的)
*/
public Activity currentActivity() {
if (activityStack.empty()) {
return null;
}
Activity activity = activityStack.lastElement();
return activity;
}

/**
* 把界面弹回到第一页
*/
public void popToRootActivity() {
while (activityStack.size() > 1) {
this.finishActivity();
}
}

/**
* 判断某个类型的activy是否存在于栈中
* @param cls
* @return
*/
public boolean hasActivity(Class < ? > cls) {
for (Activity activity : activityStack) {
if (activity.getClass().equals(cls)) {
return true;
}
}
return false;
}

/**
* 添加Activity到堆栈
*/
private void addActivity(Activity activity) {
this.activityStack.add(activity);
}

/**
* 移除一个Activity
* @param activity
*/
private void removeActivity(Activity activity) {
this.activityStack.remove(activity);
}

/**
* 结束当前Activity(堆栈中最后一个压入的)
*/
public void finishActivity() {
if (activityStack.empty()) {
return;
}
Activity activity = activityStack.lastElement();
finishActivity(activity);
}

/**
* 结束指定的Activity
*/
public void finishActivity(Activity activity) {
if (activity != null) {
activityStack.remove(activity);
activity.finish();
}
}

/**
* 结束指定类名的Activity
*/
public void finishActivity(Class < ? > cls) {
for (Activity activity: activityStack) {
if (activity.getClass().equals(cls)) {
finishActivity(activity);
}
}
}

/**
* 结束所有Activity
*/
public void finishAllActivity() {
for (int i = 0, size = activityStack.size(); i < size; i++) {
if (null != activityStack.get(i)) {
activityStack.get(i).finish();
}
}
activityStack.clear();
}

/**
* 退出应用程序
*/
@SuppressWarnings("deprecation")
public void AppExit(Context context) {
try {
finishAllActivity();
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
activityManager.restartPackage(context.getPackageName());
System.exit(0);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
     * 活动管理器
     */
    public static ActivityMgr ActivityMgr() {
        if (activityMgr == null) {
            activityMgr = new ActivityMgr();
        }
        return activityMgr;
    }   

你可能感兴趣的:(Activity管理类)