Clicking twice the back button to exit activity in android

Android press back button twice to exit app.

This feature is mostly used in all over android apps at present time because this feature gives us the ability to re program the android back button so you can define certain task upon it. So here is the complete step by step tutorial for  Clicking twice the back button to exit activity in android.

What is the press back button double feature in android: After implementing this code activity dose not close by single pressing back button. After pressing back button at single time it will show us a user written toast message that ” Press Back button again to exit activity application.”.

android-project-download-code-button

 Clicking twice the back button to exit activity in android.

Code for MainActivity.java file.

package com.android_examples.com.backbutton;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends Activity {

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

 public void onBackPressed() 
 {
 Log.e("My Tags", "onBackPressed");
 k++;
 if(k == 1)
 {
 Toast.makeText(MainActivity.this, "Please press again to exit activity.", Toast.LENGTH_SHORT).show();
 }
 else
 {
 finish();
 }
 }

}

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.android_examples.com.backbutton.MainActivity" >

 

</RelativeLayout>

Screenshot:

 Clicking twice the back button to exit activity in android

Click Here To Download  Clicking twice the back button to exit activity in android project.

Leave a Reply

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