处理程序postDelayed - 每秒打印一次

时间:2017-01-06 18:09:56

标签: android video handler android-camera2

我想使用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的每一秒更改文本?

3 个答案:

答案 0 :(得分:4)

工作回答:

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>

答案 1 :(得分:2)

要每秒打印文字,您可以使用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");
    }
};

答案 2 :(得分:1)

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

 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()