Search code examples
androidvideohandlerandroid-camera2

Handler postDelayed - print every second something


I want to print the current second using a handler. I record a video for exactly 10 seconds and want to set the text of a TextView every second.

Recording 10 seconds works like that:

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

After the 10 seconds the method stopRecordingVideo() gets executed. So how can I change the text every second of the TextView?


Solution

  • Working answer:

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

    Where formatted_time is something like that:

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