John John - 3 months ago 16
Java Question

Close the app when back button clicked twice

My Activity flow looked like this

LogIn Activity-> Activity A(Main Page)->Activity B-> Activity C


When button in C is clicked, it will intent to A.

When back button in A is pressed twice,it should close the app.

boolean doubleBackToExitPressedOnce = false;
public void onBackPressed(){
if(doubleBackToExitPressedOnce)
{
super.onBackPressed();
return;
}

this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
Intent a = new Intent(Intent.ACTION_MAIN); // close app code
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}
},2000);


Problem :


when I press the button one times, it will display
Please click BACK
again to exit
, and then it will close the app automatically even I
didn't clicked the button twice.

If I click the button twice, it will back to LogIn Activity. What is
the correct way to write ? Thanks


Edit

If I remove the
intent


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

this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;

}
},2000);


}


When double click the back button, it will back to Activity C again.

Answer

maybe just use long lastTimePressed=0L; and store in it System.currentTimeMillis(); and if(System.currentTimeMillis()-lastTimePressed>2000) finish();

2000 for Toast.Length_SHORT, 3500 for Toast.LENGTH_LONG

long lastTimePressed=0L;

@Override
public void onBackPressed (){
    if(System.currentTimeMillis()-lastTimePressed>2000) //short Toast duration, now should be faded out
        finish();
    else
        Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    lastTimePressed=System.currentTimeMillis();
}

don't start new Activity (or maybe? if you have implemented singleTask or singleTop or noHistory, but I doubt). finish(); and super.onBackPressed(); do the same practially. possibility for override onBackPressed is added later in API5, because its simply usefull :)

ohh, now I see your edit and everything is clear. Don't start your Activities with startActivity, but with startActivityForResult. Implement also onActivityResult (check out here). When you use

private static final int MY_RESULT_IS_KILL_MY_APP=4573; //random

setResult(MY_RESULT_IS_KILL_MY_APP);
finish();

and Activity below receives that in own onActivityResult it should also set this result and call finish();. This way stack of Activities clean away and entire Application will exit. Without setting this static result finish(); will finish only current Activity

Comments