处理程序 postDelayed - 每秒打印一些东西

Handler postDelayed - print every second something

我想使用 handler 打印当前秒数。我录制了一段正好 10 seconds 的视频,并希望每秒设置一个 TextView 的文本。

录制 10 秒是这样的:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
           stopRecordingVideo();
    }
}, 11000);  // don't know why 11000 but it only works this way

10 秒后,方法 stopRecordingVideo() 被执行。那么如何才能每秒更改 TextView 的文本?

要每秒打印文本,您可以使用CountDownTimer。但是如果你想用下面的代码来实现这个:

void startTime(){
    //Post handler after 1 second.
    handler.postDelayed(runnable, 1000);
}

int totalDelay=0;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
    @Override
    public void run() {
        totalDelay++;   
        if(totalDelay<=10){
            //If total time is less then 10 second execute handler again after 1 second
            handler.postDelayed(runnable, 1000);
        }
        textView.setText(totalDelay+" Second");
    }
};

试试这个,基本上是在工作线程中执行增量,但更新文本视图是由主线程处理程序完成的。

 Thread worker= new Thread(new Runnable() {
         @Override
         public void run() {
            for (int i = 0; i < 10; i++) {
               try {
                  TimeUnit.SECONDS.sleep(1);
               } catch (InterruptedException e) {
                  e.printStackTrace();
               }
             // stop recording after 10 seconds
               if (i == 9) {

                  handler.post(new Runnable() {
                     @Override
                     public void run() {
                        stopRecordingVideo();
                     }
                  });
               }

              else{
                   // set text for each second
                  handler.post(new Runnable() {
                     @Override
                     public void run() {
                        textView.setText(String.valueOf(i+1));
                     }
                  });

               }
            }//ends for()

     worker.start()

有效答案:

int t = 0;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        t++;
        textView.setText(getString(R.string.formatted_time, t));
        if(t<10) {
            handler.postDelayed(this, 1000);
        }
    }
}, 1000);

其中 formatted_time 是这样的:

<string android:name="formatted_time">%d seconds</string>