public class AppManager { private static Stack<Activity> activityStack; private static AppManager instance; private AppManager() { } /** * 单一实例 */ public static AppManager getAppManager() { if ( instance == null) { instance = new AppManager(); } return instance; } /** * 添加Activity到堆栈 */ public void addActivity(Activity activity) { if ( activityStack == null) { activityStack = new Stack<Activity>(); } activityStack.add(activity); } /** * 获取当前Activity(堆栈中最后一个压入的) */ public Activity currentActivity() { Activity activity = activityStack.lastElement(); return activity; } /** * 结束当前Activity(堆栈中最后一个压入的) */ public void finishActivity() { Activity activity = activityStack.lastElement(); if (activity != null) { finishActivity(activity); } } /** * 结束指定的Activity */ public void finishActivity(Activity activity) { if (activity != null) { activityStack.remove(activity); activity.finish(); activity = null; } } /** * 结束指定类名的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(); } /** * 退出应用程序 */ public void AppExit(Context context) { try { BaseApplication. myLoginState= false; BaseApplication. isEnterMain= false; BaseApplication. currentPhotoPath= ""; finishAllActivity(); ActivityManager activityMgr = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE ); activityMgr.killBackgroundProcesses(context.getPackageName()); System. exit(0); } catch (Exception e) { } } /** * 得到当前类名 */ public String getClassName(Context context){ ActivityManager manager = (ActivityManager)context.getSystemService(Context. ACTIVITY_SERVICE); List<RunningTaskInfo> runningTasks = manager .getRunningTasks(1); RunningTaskInfo cinfo = runningTasks.get(0); ComponentName component = cinfo. topActivity; return component.getClassName(); }
@Override public boolean onKeyDown( int keyCode, KeyEvent event) { //在这里就要先得到Activity栈里面的倒数第二个元素(比如在这之前是从A跳转到B。那么stack集合里面的元素为{X,X,X,A,B}),然后判断A是否被finish(); Activity activityA=AppManager.getAppManager().getActivityStack().get(AppManager. getAppManager().getActivityStack().size()-2); //因为数组下标是从0开始,所以要减去2才能得到A if(activityA.isFinishing()){ //判断A activity是否被销毁,如果被销毁,则进行跳转操作,如果没有被销毁,则不操作 Activity activityB=AppManager.getAppManager().getActivityStack().get(AppManager. getAppManager().getActivityStack().size()-1); AppManager.getAppManager().getActivityStack().remove(AppManager. getAppManager().getActivityStack().size()-2); //将A移除stack集合中 AppManager.getAppManager().getActivityStack().remove(AppManager. getAppManager().getActivityStack().size()-1); //将B移除stack集合中 startActivity( new Intent(activityB,activityA.getClass()));//从B跳转到A return true; } return super.onKeyDown(keyCode, event); }