I'm new to Android development and I want it so when the user presses the back button on the main activity, a toast message appears with a "confirm exit by pressing the back button again" message. How would I do this? This is what I have so far:
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Toast s = Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_LONG);
s.show();
wait();
public boolean onBackPressed() {
finish();
}
}
I would just save the time of the backpress and then compare the time of the latest press to the new press.
long lastPress;
@Override
public void onBackPressed() {
long currentTime = System.currentTimeMillis();
if(currentTime - lastPress > 5000){
Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_LONG).show();
lastPress = currentTime;
}else{
super.onBackPressed();
}
}
You can also dismiss the toast when the app the back press is confirmed (cred @ToolmakerSteve):
long lastPress;
Toast backpressToast;
@Override
public void onBackPressed() {
long currentTime = System.currentTimeMillis();
if(currentTime - lastPress > 5000){
backpressToast = Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_LONG);
backpressToast.show();
lastPress = currentTime;
} else {
if (backpressToast != null) backpressToast.cancel();
super.onBackPressed();
}
}