TextView setText 在 ScheduledExecutorService runOnUiThread 中不起作用

TextView setText not working inside ScheduledExecutorService runOnUiThread

代码:

private void startTimer() {
    final ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
    scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                public void run() {
                    int count = 60;
                    time.setText(count - 1 + "");
                    count--;
                }
            });
        }
    }, 0 , 1000, TimeUnit.MILLISECONDS);
}

我想每 1 秒更新一次 TextView 中的文本,但这似乎只适用于第一次,以后的文本不会更新。

有人知道这是怎么回事吗??

int count = 60;
private void startTimer() {
final ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
       runOnUiThread(new Runnable() {
          public void run() {
             if(count > 0){
               time.setText(count - 1 + "");
               count--;
             }
          }
       });
     }
   }, 0 , 1000, TimeUnit.MILLISECONDS);
}

阅读How to run a Runnable thread in Android

您可以使用Handler

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

您需要使用 handler.postDelayed(new Runnable() 方法。

Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses. The runnable will be run on the thread to which this handler is attached .

 Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
       // Add your code Here

        handler.postDelayed(this, 1000); // You can change your time
      }
    }, 900);