Reputation: 1632
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?
Upvotes: 5
Views: 8042
Reputation: 1632
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>
Upvotes: 7
Reputation: 3109
Try this, basically do the increment in a worker thread, but updating the text view is done by main's thread handler.
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()
Upvotes: 1
Reputation: 10299
To print text every second, you can use CountDownTimer. But if you want to achieve this with try below code:
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");
}
};
Upvotes: 2