Question

How can I make it so that pressing the back button does not close my application? I want to display a confirmation message.

Thank you.

Était-ce utile?

La solution

Source: Override back button to act like home button

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        //Display confirmation here, finish() activity.
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

That was a very quick search, try to look a little next time.

Autres conseils

Application close confirmation is here

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Do you want to close?")
               .setCancelable(false)
               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        //do finish
                    ImageViewActivity.this.finish();
                   }
               })
               .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       //do nothing
                       return;
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();


    }
    return super.onKeyDown(keyCode, event);
}

try this on back button pressed it shows confirmation message

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Thank You!!!!!")
           .setCancelable(false)
           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   //do things
               }
           });
    AlertDialog alert = builder.create();
    alert.show();
}   

It is not recommended to exit your Android Application.Android's design does not favor exiting an application by choice, but rather manages it by the OS. You can bring up the Home application by its corresponding Intent:

You can fire this Intent on onKeyDown() in Android 1.x and higher or onBackPressed() in Android 2.x and higher

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

A simpler approach is to capture the Back button press and call moveTaskToBack(true) as follows:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        moveTaskToBack(true);
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top