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=”https://i0.wp.com/techaxioms.com/wp-content/uploads/2016/11/pressbackbutton.jpg?fit=1024%2C640&ssl=1″ data-medium-file=”https://i0.wp.com/techaxioms.com/wp-content/uploads/2016/11/pressbackbutton.jpg?fit=300%2C188&ssl=1″ data-orig-file=”https://i0.wp.com/techaxioms.com/wp-content/uploads/2016/11/pressbackbutton.jpg?fit=1184%2C740&ssl=1″ data-orig-size=”1184,740″ data-permalink=”https://techaxioms.com/add-press-back-button-exit-double-tap-exit-method-quit-android-application/pressbackbutton/” data-recalc-dims=”1″ height=”508″ sizes=”(max-width: 812px) 100vw, 812px” src=”https://i2.wp.com/techaxioms.com/wp-content/uploads/2016/11/pressbackbutton-1024×640.jpg?resize=812%2C508″ srcset=”https://i0.wp.com/techaxioms.com/wp-content/uploads/2016/11/pressbackbutton.jpg?resize=1024%2C640&ssl=1 1024w, https://i0.wp.com/techaxioms.com/wp-content/uploads/2016/11/pressbackbutton.jpg?resize=300%2C188&ssl=1 300w, https://i0.wp.com/techaxioms.com/wp-content/uploads/2016/11/pressbackbutton.jpg?resize=768%2C480&ssl=1 768w, https://i0.wp.com/techaxioms.com/wp-content/uploads/2016/11/pressbackbutton.jpg?w=1184&ssl=1 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
super.onCreate(savedInstanceState);
setContentView(R.layout.mainpage);
}

boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed()
{
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}

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

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

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

}

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

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