Need some help. I used double click on back button for exit app with Toast with next code:
@Override
public void onBackPressed() {
if (back_pressed + 2000 > System.currentTimeMillis()) {
super.onBackPressed();
} else {
Toast.makeText(getBaseContext(), "Нажмите еще раз для выхода", Toast.LENGTH_SHORT).show();
}
back_pressed = System.currentTimeMillis();
}
Found that fragment code here at stackoverflow. I guess this is the best solution for issue. But there is one ecxeption - toast is still on screen after exiting app. How to kill the toast when user click back button twice and application closed?
We can't kill toast when application closes. We can use toast like below code. Toast.LENGTH_SHORT).show();
less duration of toast when your app closes.
Toast.makeText(this, "Press again to exit.. ", Toast.LENGTH_SHORT).show();
Or, you can set Duration
of Toast
by code below:
Toast toast = Toast.makeText(getApplicationContext(), "Press again to exit..", Toast.LENGTH_SHORT);
toast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
toast.cancel();
}
}, 500);
Or, you can use this :
private Toast toast = null;
toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
//Toast.makeText(this, "Press again to exit..", Toast.LENGTH_SHORT).show();
toast.setText("Press again to exit..");
toast.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
@Override
protected void onStop () {
super.onStop();
toast.cancel();
}