How to detect back button is pressed in android

How to identify android mobile phone back button clicked or not and display toast message on back button click.

Android mobile phone device back button is used to exit from any already open application or activity or settings …etc. But app developer can easily detect whether the back button is pressed or not and display any type of message on back button detection. So here is the complete step by step tutorial for How to detect back button is pressed in android.

android-project-download-code-button

How to detect back button is pressed in android.

Code for MainActivity.java file.

 package com.detectbackbutton_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 }

 @Override
 public void onBackPressed() {
 
 // Put your own code here which you want to run on back button click.
 
 Toast.makeText(MainActivity.this,"Back Button is clicked.", Toast.LENGTH_LONG).show();
 
 super.onBackPressed();
 }

}

Code for activity_main.xml layout file.

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.detectbackbutton_android_examples.com.MainActivity" >

 

</RelativeLayout>

Screenshot:

How to detect back button is pressed in android

Click here to download How to detect back button is pressed in android project.

Leave a Reply

Your email address will not be published. Required fields are marked *