How to close app with back button in android

May 2, 2013   //   by kdecom   //   android  //  No Comments

Here is a code snippet for how to close your application when someone click on back button of their phone.

First thing that you need to do is listen for the key event when someone click on the back button.

public boolean onKeyDown(int keyCode, KeyEvent event)  {

    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {

    AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
    	alertDialog .setMessage("Are you sure you want to exit?").
    	setPositiveButton("Yes",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				// if this button is clicked, close
				// current activity
				MainActivity.this.finish();
			}
		  }).
		  setNegativeButton("No",new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				// if this button is clicked, just close
				// the dialog box and do nothing
				dialog.cancel();
			}
		}).show();   

    return super.onKeyDown(keyCode, event);
}

 

So now as soon as you add the above code it start complaining about the some of the class missing so in your import list you need to add this if you dont have:

import android.view.KeyEvent;
import android.app.AlertDialog;
import android.view.KeyEvent;
import android.content.DialogInterface;

I hope above code helps. Anyone of you have a problem contact us or leave a comment and we all try to fix it.

Leave a comment

css.php