Android

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

How to add press back button again to quit feature to an android application
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

}