android 完美退出应用程序。

http://www.2cto.com/kf/201402/276808.html

 

Android 程序在点击回退键时,如果只有一个activity,调用finish()方法就能退出界面,如果有多个界面,在调用该方法时,只会销毁当前的activity,显示栈顶的其它activity,换言之,就是无法退出整个应用程序。下面是一种快速的退出整个应用的方法代码:

private void showTips() {
 
        AlertDialog alertDialog = new AlertDialog.Builder(this).setTitle("提醒")
                .setMessage("是否退出程序")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
 
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Intent.ACTION_MAIN);  
                        intent.addCategory(Intent.CATEGORY_HOME);  
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);  
                        startActivity(intent);  
                    android.os.Process.killProcess(android.os.Process.myPid());
                    }
 
                }).setNegativeButton("取消",
 
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        return;
                    }
                }).create(); // 创建对话框
        alertDialog.show(); // 显示对话框

  

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            showTips();
            return false;
        }
 
        return super.onKeyDown(keyCode, event);
    }

  

posted @ 2015-06-30 19:24  裸奔到月球  阅读(218)  评论(0编辑  收藏  举报