0

I'm trying to make a simple countdown timer that shows the remaining time in a toast.
I wrote this code:

new CountDownTimer(10000, 1000) {

    public void onTick(long timeRemaining) {
        Toast.makeText(getBaseContext(), "" + timeRemaining / 1000, 
                                                      Toast.LENGTH_SHORT).show();
    }

    public void onFinish() {
        // do something
    }

}.start();

The problem is that the action that's in the onFinish method is executed when in the toast I'm showing "3".
So, the toast is slower respect the timer.
How can I solve that?

Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
Giovanni Mariotti
  • 615
  • 1
  • 7
  • 11

3 Answers3

2

Toast shouldn't be used that way. Toast.LENGTH_SHORT will remain there for 3 seconds before disappearing, however timer will tick every second so obviously Toast is slow.

If you want to show timer to user then you must use a TextView, if you want timer for your own then you can use Log.d();

Update :- After a bit searching I found out that you cannot set Toast for custom time. The Toast has only two values Toast.LENGTH_LONG and Toast.LENGTH_SHORT. See this question here Can an Android Toast be longer than Toast.LENGTH_LONG?. As a work around,if you really want to set the Toast for just 1 second, then you can do this

final Toast toast = Toast.makeText(ctx, "This message will disappear in 1 second", Toast.LENGTH_SHORT);
        toast.show();

        Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
               @Override
               public void run() {
                   toast.cancel(); 
               }
        }, 1000);
Community
  • 1
  • 1
Rohan Kandwal
  • 9,112
  • 8
  • 74
  • 107
0

The Android OS queues Toasts if they appear in rapid succession. So what happens is that there is a slow delay between the actual tick and the toast fade away. This means that for many ticks, the toasts start to lag behind. A simple fix would be to reduce the number of Toasts.

Adrian Nițu
  • 131
  • 1
  • 2
  • 11
0

onFinish -> toast.cancel()

  
  final Toast showToast = Toast.makeText(this, "test ya!!! i'm Strtoint", Toast.LENGTH_LONG); 

     // Set the countdown 
     CountDownTimer toastCountDown = new CountDownTimer(10000, 1000) //if set 1sec ->1000 ms
     {
            public void onTick(long timeRemaining) {
              showToast.show();
            }
            public void onFinish() {
              showtoast.cancel();
            }
     };

      // Show the toast and starts the countdown
      showToast.show();
      toastCountDown.start();
     }
StrTOInt
  • 16
  • 2