How to change the back button behaviour

Sometimes, when developing Android applications, there is a need to override the default behaviour of the back button which means assigning another behavior for the ‘Back’ button. Although changing the behaviour of back button is not recommended, but there are some situations where changing the ‘back’ button behavior is mandatory, such as to avoid accidentally finishing or closing the current Activity.

For example, a text editor, should confirm if the user really wants to quit without saving the current changes, or a game, that check if it is the player’s intention to close the current game session.

[pgsubscribe]

Let us write few lines of code to change the default behavior of ‘back’ button. To start with, I assume you are going to test our code in Android devices having OS version 2.0 or above.

Quick Links

Code Listings

There is a ‘back’ key press event available in Android with which we can assign different behaviour for ‘back’ button press event:

@Override
public void onBackPressed() {
	//Include the code here
	return;
}

For lower versions below Android 2.0, we need to handle the ‘back’ button press event in different way as there is no onBackPressed() method available.

All we need to do is, override the onKeyDown() method and check if ‘back’ button has been pressed:

 
@Override  
public boolean onKeyDown(int keyCode, KeyEvent event){  
        //Changes 'back' button action  
        if(keyCode==KeyEvent.KEYCODE_BACK)  
        {  
         //Include the code here
        }  
        return true;  
    }

I just created a simple application which will ask the user to confirm leaving the application when the user presses the ‘back’ button:

package com.prgguru.example;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Toast;

public class AndroidBackButtonActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Toast.makeText(getApplicationContext(),"http://programmerguru.com/android-tutorial", Toast.LENGTH_LONG).show();
	}

	@Override
	public void onBackPressed() {
		//Display alert message when back button has been pressed
		backButtonHandler();
		return;
	}

	public void backButtonHandler() {
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(
				AndroidBackButtonActivity.this);
		// Setting Dialog Title
		alertDialog.setTitle("Leave application?");
		// Setting Dialog Message
		alertDialog.setMessage("Are you sure you want to leave the application?");
		// Setting Icon to Dialog
		alertDialog.setIcon(R.drawable.dialog_icon);
		// Setting Positive "Yes" Button
		alertDialog.setPositiveButton("YES",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						finish();
					}
				});
		// Setting Negative "NO" Button
		alertDialog.setNegativeButton("NO",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						// Write your code here to invoke NO event
						dialog.cancel();
					}
				});
		// Showing Alert Message
		alertDialog.show();
	}
}

[pglinkadssmall1]

Demo

Let us test the application:
Run click on the project >> Run as >> Android application
You could see following screens:



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

[pglinkadssmall]

I hope you enjoyed the post!! 🙂
[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • am waiting for this thanq

  • Though overriding the back button is not very adviced, in some cases it can be very usefull. Thanks.

  • reeha

    hello friends….its a nice tutorial…but…the way i need is to go back to the previous screen….can anyone help me pls

  • Doc

    Thank you for show us this answer. One question: What is the command to close all activities?

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares