退出应用程序单击OnBackPressed

时间:2014-08-03 18:37:45

标签: android

我使用此代码信息我的Android应用程序MainActivity类,显示dailog For Quit应用程序如果我点击是应用程序运行继续它不能退出。抱歉英文不好

   public boolean onKeyDown(int keyCode, KeyEvent event) {
      if (keyCode == KeyEvent.KEYCODE_BACK) {
        // Toast.makeText(appContext, "BAck", Toast.LENGTH_LONG).show();
        AlertDialog.Builder alert = new AlertDialog.Builder(
                MainActivity.this);
        alert.setTitle(string.app_name);
        alert.setIcon(R.drawable.icon);
        alert.setMessage("Are You Sure You Want To Quit?");

        alert.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                                        int whichButton) {

                             finish();
                    }



                });

        alert.setNegativeButton("NO",
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                   }
                });
        alert.show();
        return true;
    }

    return super.onKeyDown(keyCode, event);

3 个答案:

答案 0 :(得分:1)

您可以覆盖onBackPressed回调:

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("Really Exit?")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton(android.R.string.no, null)
        .setPositiveButton(android.R.string.yes, new OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                YourActivity.super.onBackPressed();
            }
        }).create().show();
}

<强>更新

根据您的评论,我猜您在儿童活动中覆盖onBackPressed,因此在这种情况下,您必须关闭父活动以及当前活动。

为此,您必须设置一个标志以确定是要关闭活动还是否:

public static String KEY_EXIT_ME = "yourApp.exit_me";

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
        .setTitle("Really Exit?")
        .setMessage("Are you sure you want to exit?")
        .setNegativeButton(android.R.string.no, null)
        .setPositiveButton(android.R.string.yes, new OnClickListener() {

            public void onClick(DialogInterface arg0, int arg1) {
                exitApp();
            }
        }).create().show();
}

public void exitApp(){
    Intent intent = new Intent(this, ParentActivity.class); // which may be MainActivity
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra(KEY_EXIT_ME, true);
    startActivity(intent);
    finish();
}

然后使用ParentActivity onCreate方法:

if( getIntent().getBooleanExtra(KEY_EXIT_ME, false)){
    finish();
    return; // add this to prevent from doing unnecessary stuffs
}

答案 1 :(得分:0)

而不是finish();

呼叫

MainActivity.this.finish();

答案 2 :(得分:0)

而不是直接使用finish(),尝试使用MainActivity.this.finish()...

另外,你应该将AlertDialog.Builder放在DialogFragment中,它会好得多。