3

I am using handler.postDelayed method to create some delay for some animation stuff. Like this:

Handler h = new Handler();
h.postDelayed(new Runnable() {
  @Override
  public void run() {
    // Start Animation.
  }
}, 6000);

Later, How can I get the remaining time until the animation starts?

Hemanth
  • 2,717
  • 2
  • 21
  • 29

1 Answers1

3

You can simply save the time in a var when you call post delayed

 long startTime = System.nanoTime();
 h.postDelayed(...

and then when you need to check the remaining time you can calculate the elapsed time like

 long elapsedTime = System.nanoTime()-startTime;

So in your case

 long remainingTime = 6000 - elapsedTime;
axl coder
  • 739
  • 3
  • 19
  • Thanks. I know I can use this to get remaining time. But, does Handler provide a convenient way to calculate remaining time? – Hemanth Aug 13 '14 at 12:18
  • remaining time of what? – pskink Aug 13 '14 at 12:23
  • @hemanth2081 Handler doesn't provide a method to do this in a better way. – axl coder Aug 13 '14 at 12:34
  • Sometimes, _elapsedTime_ will be more than 6000(As the task is not guarantied to execute exactly after 6000 ms). In such case, _remainingTime_ will be -ve. – Hemanth Aug 13 '14 at 13:07
  • Yes, unfortunately with handler you don't have that kind of precision, if you need that I suggest you to take a look at Timer or AlarmManager – axl coder Aug 13 '14 at 13:12