Android: Proper Way to use onBackPressed() with Toast

Viewed 275858

I wrote a piece of code that will give the user a prompt asking them to press back again if they would like to exit. I currently have my code working to an extent but I know it is written poorly and I assume there is a better way to do it. Any suggestions would be helpful!

Code:

public void onBackPressed(){
    backpress = (backpress + 1);
    Toast.makeText(getApplicationContext(), " Press Back again to Exit ", Toast.LENGTH_SHORT).show();

    if (backpress>1) {
        this.finish();
    }
}
13 Answers

I just had this issue and solved it by adding the following method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
             // click on 'up' button in the action bar, handle it here
             return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}    

Use this, it may help.

@Override
public void onBackPressed() {
    new AlertDialog.Builder(this)
            .setTitle("Message")
            .setMessage("Do you want to exit app?")
            .setNegativeButton("NO", null)
            .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    UserLogin.super.onBackPressed();
                }
            }).create().show();
}

implementing onBackPressed() by System time, if pressed twice within 2 sec, then will exit

public class MainActivity extends AppCompatActivity {
   private long backPressedTime;   // for back button timing less than 2 sec
   private Toast backToast;     // to hold message of exit
   @Override
public void onBackPressed() {


if (backPressedTime + 2000 > System.currentTimeMillis()) {

backToast.cancel();    // abruptly cancles the toast when pressed BACK Button *back2back*
super.onBackPressed();

} else {

backToast = Toast.makeText(getBaseContext(), "Press back again to exit", 
Toast.LENGTH_SHORT);
backToast.show();

}
backPressedTime = System.currentTimeMillis();

}

}

Related