android2.2程序退出

做程序退出的时候,始终退出不了,网上找了很多方法。

ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
						am.restartPackage(getPackageName());
//不行啊

android.os.Process.killProcess(android.os.Process.myPid());//也不行


最后用了这个办法:
package com.android.cist.util;

import java.util.LinkedList;
import java.util.List;

import android.app.Activity;
import android.app.Application;

public class ApplicationUtil extends Application {
	private List<Activity> activityList = new LinkedList<Activity>();
	private static ApplicationUtil instance;

	private ApplicationUtil() {
	}

	// 单例模式中获取唯一的ApplicationUtil实例
	public static ApplicationUtil getInstance() {
		if (null == instance) {
			instance = new ApplicationUtil();
		}
		return instance;

	}

	// 添加Activity到容器中
	public void addActivity(Activity activity) {
		activityList.add(activity);
	}

	// 遍历所有Activity并finish

	public void exit() {

		for (Activity activity : activityList) {
			activity.finish();
		}
		System.exit(0);
	}
}

@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			final AlertDialog isExit = new AlertDialog.Builder(this).create();
			isExit.setTitle("系统提示");
			isExit.setMessage("确定要退出吗");
			DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case AlertDialog.BUTTON1:
						ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
						am.restartPackage(getPackageName());
						/*ApplicationUtil.getInstance().exit();*/
						//android.os.Process.killProcess(android.os.Process.myPid());
						break;
					case AlertDialog.BUTTON2:
						isExit.cancel();
						break;
					default:
						break;
					}
				}
			};
			isExit.setButton("确定", listener);
			isExit.setButton2("取消", listener);
			isExit.show();
			return false;
		}
		return false;
	}

在每个界面的onCreate()方法中添加ApplicationUtil.getInstance().addActivity(this);



你可能感兴趣的:(android2.2 退出程序)