关闭

Android应用程序退出实例

标签: androidapplicationbuttonnullclass
527人阅读 评论(0) 收藏 举报
分类:

1、Application当中代码:

public class WeiboApplication extends Application {

	// 程序退出标记
	private List<Activity> activities = new ArrayList<Activity>();

	public void addActivity(Activity activity) {
		activities.add(activity);
	}

	@Override
	public void onTerminate() {
		super.onTerminate();

		for (Activity activity : activities) {
			activity.finish();
		}

		android.os.Process.killProcess(android.os.Process.myPid());
	}

}

2、每个Activity在oncreate当中的代码:

@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main_activity);
		
		WeiboApplication app = (WeiboApplication) getApplication();
		app.addActivity(this);
	}

3、在TabActivity当中设置退出代码(类似的可以在普通Activity当中设置)

@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {

			// 创建对话框
			LayoutInflater li = LayoutInflater.from(this);
			View exitV = li.inflate(R.layout.exitdialog, null);
			AlertDialog.Builder ab = new AlertDialog.Builder(this);
			ab.setView(exitV);// 设定对话框显示的View对象
			ab.setPositiveButton(R.string.menu_logout_label, new OnClickListener() {
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					WeiboApplication app = (WeiboApplication) getApplication();
					app.onTerminate();
				}
			});
			ab.setNegativeButton(R.string.cancel_button_title, null);
			// 显示对话框
			ab.show();
			return false;
		}
		return false;
	};



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:452584次
    • 积分:6581
    • 等级:
    • 排名:第3853名
    • 原创:192篇
    • 转载:2篇
    • 译文:6篇
    • 评论:174条
    文章分类