Search code examples
javaandroidtimertoast

Displaying toast before app closes in java


I have created a simple dice game in Android. When the user hits an "end game" button, I want to display a toast that says "thanks for playing" and then close the application. Currently, this is what I am doing (note that I have a global timer declared as Timer timer;).

if (v.equals(endGame)) { //if "end game" button was clicked
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
        Toast t = Toast.makeText(getApplicationContext(), "Thanks for playing", Toast.LENGTH_LONG);
        t.show();
    }, 2000, 2000);

    System.exit(0); //quits the app

Currently, the application simply quits without the toast displaying. What do I need to do to properly implement this?


Solution

  • Something like this (I might have a bracket off)

    if (v.equals(endGame)) { //if "end game" button was clicked
    Toast t = Toast.makeText(getApplicationContext(), "Thanks for playing",     Toast.LENGTH_LONG);
        t.show();
    Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    // end app;
                }
            }, 2000);   //2 seconds
    }