3

I have an app and I want to do that when user touch back button a Toast show "press back again to exit" but i have problem with this part. on this code, when touch back button app completely finish without toast and touch back button again. Please help me.

   public void onStop(){
        super.onStop();
        if(key == 1){
            key =0;
            finish();
        }else{
            Toast.makeText(getApplicationContext(), "press back Button again to exit", Toast.LENGTH_SHORT).show();
        key++;
        }
            return;
        }

2 Answers2

4
@Override
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);
} 

you can go though this link Clicking the back button twice to exit an activity

same question

Community
  • 1
  • 1
Abhishek
  • 2,350
  • 2
  • 21
  • 35
2

You have to write code inside onBackPressed() method. Try this code:

@Override 
public void onBackPressed() { 
    if(key == 1){
            key =0;
            finish();
        }else{
            Toast.makeText(getApplicationContext(), "press back Button again to exit", Toast.LENGTH_SHORT).show();
        key++;
        }
}

I recommend you to follow this post: Clicking the back button twice to exit an activity

Community
  • 1
  • 1
Anand Singh
  • 5,672
  • 2
  • 23
  • 33