How to set timer in android?

后端 未结 21 911
渐次进展
渐次进展 2020-11-22 00:51

Can someone give a simple example of updating a textfield every second or so?

I want to make a flying ball and need to calculate/update the ball coordinates every se

21条回答
  •  抹茶落季
    2020-11-22 01:47

    Because this question is still attracting a lot of users from google search(about Android timer) I would like to insert my two coins.

    First of all, the Timer class will be deprecated in Java 9 (read the accepted answer).

    The official suggested way is to use ScheduledThreadPoolExecutor which is more effective and features-rich that can additionally schedule commands to run after a given delay, or to execute periodically. Plus,it gives additional flexibility and capabilities of ThreadPoolExecutor.

    Here is an example of using plain functionalities.

    1. Create executor service:

      final ScheduledExecutorService SCHEDULER = Executors.newScheduledThreadPool(1);
      
    2. Just schedule you runnable:

      final Future future = SCHEDULER.schedule(Runnable task, long delay,TimeUnit unit);
      
    3. You can now use future to cancel the task or check if it is done for example:

      future.isDone();
      

    Hope you will find this useful for creating a tasks in Android.

    Complete example:

    ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    Future sampleFutureTimer = scheduler.schedule(new Runnable(), 120, TimeUnit.SECONDS);
    if (sampleFutureTimer.isDone()){
        // Do something which will save world.
    }
    

提交回复
热议问题