BBish937 BBish937 - 1 year ago 92
Android Question

Android Back Button Pressed Check

So I'm currently developing a turn based game app. And it displays toasts from a view on who's turn it is after each turn is taken. What's weird though, is if I hit the back button it will go back to the main menu(previous activity) but the toasts will still linger till they time out. Also if I hit back twice and it goes to the home screen, the toasts will still show until they finish. I want to implement a check or some way to cancel those toasts when the back button is pressed. I have to do this in my view too, my view contains all the toasts and all the code to the game, the gameActivity only has onCreate to create the view for the game. Any ideas?

Answer Source

In your Activity you have override method:

public boolean onKeyDown(int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_BACK) {
// do something
return false;

return super.onKeyDown(keyCode, event);

And in your View have to implement method, for example notifyBackPressed();