Nick Nick - 3 months ago 14x
Android Question

Android: Proper Way to use onBackPressed()

I wrote a piece of code that will give the user a prompt asking them to press back again if they would like to exit. I currently have my code working to an extent but I know it is written poorly and I assume there is a better way to do it. Any suggestions would be helpful!


public void onBackPressed(){
backpress = (backpress + 1);
Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();

if (backpress>1) {


I would implement a dialog asking the user if they wanted to exit and then call super.onBackPressed() if they did.

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

            public void onClick(DialogInterface arg0, int arg1) {

In the above example, you'll need to replace WelcomeActivity with the name of your activity.