How to add ‘press back button again to quit’ feature to an android application

” data-image-meta=”{“aperture”:”0″,”credit”:””,”camera”:””,”caption”:””,”created_timestamp”:”0″,”copyright”:””,”focal_length”:”0″,”iso”:”0″,”shutter_speed”:”0″,”title”:””,”orientation”:”0″}” data-image-title=”pressbackbutton” data-large-file=”″ data-medium-file=”″ data-orig-file=”″ data-orig-size=”1184,740″ data-permalink=”” data-recalc-dims=”1″ height=”508″ sizes=”(max-width: 812px) 100vw, 812px” src=”×640.jpg?resize=812%2C508″ srcset=” 1024w, 300w, 768w, 1184w” width=”812″>

How to add press back button again to quit feature to an android application

In this tutorial we are going to implement “Press again to exit” application quit feature.

What we actually do here – when user clicks on back button a toast message is generated saying “Press again to exit”, if user press back button again then we call finish method to quit the app

We are using ‘onBackPressed’ method to implement this feature

Code snippet

public class MainHomeActivity extends AppCompatActivity
protected void onCreate(Bundle savedInstanceState)
// TODO Auto-generated method stub

boolean doubleBackToExitPressedOnce = false;

public void onBackPressed()
if (doubleBackToExitPressedOnce) {

this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, “Press again to exit”, Toast.LENGTH_SHORT).show();

new Handler().postDelayed(new Runnable() {

public void run() {
doubleBackToExitPressedOnce = false;
}, 2000); // Change time interval here if you want




Please enter your comment!
Please enter your name here

Comment moderation is enabled. Your comment may take some time to appear.