How to use handler as a timer in android? - android

Handler handler = new Handler();
if (v.getId() == R.id.play){
handler.postDelayed(new Runnable() {
public void run() {
play.setBackgroundResource(R.drawable.ilk);
}
}, 2000);
play.setText("Play");
}
I want to set background first and then after 2 seconds later, code will continue next line which is play.setText("Play"); and goes like that. Instead of this, first text appears. 2 seconds later background changes.

Handler.postDelayed returns immediately. And next line is executed.
After indicated milliseconds, the Runnable will be executed.
So your code should be like this:
void doFirstWork() {
Handler handler = new Handler();
if (v.getId() == R.id.play){
handler.postDelayed(new Runnable() {
public void run() {
play.setText("Play");
doNextWork();
}
}, 2000);
play.setBackgroundResource(R.drawable.ilk);
}
}
void doNextWork() {
...
}

Set the background first. After that set the text within Handler. As you've put delays at the end of postDelayed so it'll fire right after that stated delays or in your case after 2 sec.
if (v.getId() == R.id.play){
play.setBackgroundResource(R.drawable.ilk);
new Handler().postDelayed(new Runnable() {
public void run() {
play.setText("Play");
}
}, 2000);
}

Related

Timer task implementing handler

UPDATE : The code is working only that I dint init the textview, but this question is answered so I cant remove it either. So I will leave this question as it is for anyone trying to implement a Timertask with handler that makes use of Looper.getMainLooper that directly attaches it to the UI THREAD.
OLD QUERY :Hello guys I am trying to implement a timer that runs a task which has a handler.
I am using it to update the UI every second.
This is what I am implementing:
private void setRepeatingAsyncTask() {
handler = new Handler(Looper.getMainLooper());
timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
i++;
tview.setText(String.valueOf(i));
} catch (Exception e) {
// error, do something
}
}
});
}
};
timer.schedule(task, 0, 1000); // interval of one minute
}
when I make setRepeatingAsyncTask() on create or somewhere else like button clicklistner, etc either the timer or the handler is not starting.
Please help new to android!
I used Handler to process the task every 1 sec, Using just Handler:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//some task
handler.postDelayed(this, 1000); //looping is every 1 secs
}
}, 0); //initial delay of 0

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?
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>
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");
}
};
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()

android Handler.postDelayed use in many places

I have an app, which shows a video. At some point I want to give information about videos places. For example, historical places names. I am using this code:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
}
}, 100);
But when I use this postDelayed comment in many times some message not show or overtake. What is the best solution to show some texts in a delay? For example 5 seconds later show A text, 15 sec later show B text, 30 sec later show C text. my codes look like this:
switch ()
case 1:
openVideo(video1)
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//my message
}
}, 4000);
break;
case 2:
openVideo(video2)
final Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
//my second message
}
}, 3000);
handler2.postDelayed(new Runnable() {
#Override
public void run() {
//my third message
}
}, 15000);
break;
Use multi-runnable.. Increase your duration for each text.
int mDuration=0,mAnimationDuration=5000;
mDuration=mDuration+mAnimationDuration;
//it called after 5 seconds
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Your first text
}
}, mDuration);
mDuration=mDuration+mAnimationDuration;
//it called after 10 seconds
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Your second text
}
}, mDuration);
mDuration=mDuration+mAnimationDuration;
//it called after 15 seconds
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Your third text
}
}, mDuration);
Use Timer for every second...
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
//put you code here
//or set switch case for time 5,10,15 seconds
}
}, 0, 1000);//put here time 1000 milliseconds=1 second

Displaying a stopwatch in an android app in a textView

I have setup a stop watch using the com.apache.commons library and the stop watch seems to work fine. What I don't know how to do is display this stopwatch in a textView in my app. In general, I have no idea how that would work, i.e. How exactly would a stopwatch be displayed in a textView, given that the time on a stopwatch keeps changing constantly? At the moment, I have the code below and it updated the text in the textView every second for about 2 seconds and then I got a weird error. I'm not even sure if this is the right way to go about doing this. Please help!
Timer timer = new Timer();
TimerTask timerTask;
timerTask = new TimerTask() {
#Override
public void run() {
timeText.setText(time.toString());
}
};
timer.schedule(timerTask, 0, 1000);
The error I got after 2 seconds (and it successfully updated the time) was :
"only the original thread that created a view hierarchy can touch its views"
You can only update a TextView on the UI thread.
runOnUiThread(new Runnable() {
#Override
public void run() {
//stuff that updates ui
}
});
Your code becomes
Timer timer = new Timer();
TimerTask timerTask;
timerTask = new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
timeText.setText(time.toString());
}
});
}
};
timer.schedule(timerTask, 0, 1000);
You may have to do myActivityObject.runOnUiThread() if you're getting an error there.
See this for more detail.
To update a view from another thread, you should use handler.
private void startTimerThread() {
Handler handler = new Handler();
Runnable runnable = new Runnable() {
private long startTime = System.currentTimeMillis();
public void run() {
//Change the condition for while loop depending on your program logic
while (true) {
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable(){
public void run() {
timeText.setText(time.toString());
}
});
}
}
};
new Thread(runnable).start();
}

Android: use handler post.delayed twice

I would like to know if it's possible to use handler().postdelayed twice?
I mean, I want to create a button, that when clicked it change the color and stay in this state 1 second, then, after 1 second another button change the color.
I've created the following code:
In the onclicklistener:
btn3.setBackgroundColor(Color.WHITE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
checkAnswer();
waitAnswer();
btnRsp3.setBackgroundResource(R.drawable.selector);
}
}, 1000);
CheckAnswer:
public void CheckAnswer(){
btn1.setBackgroundColor(Color.GREEN);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
}
}, 500);
btn1.setBackgroundResource(R.drawable.selector);
}
I think the problem is on CheckAnswer because it seems it doesn't stop in this postDelayed and step to the waitAnswer.
Thanks
Why do you expect it to stop on postDelayed? postDelayed places your Runnable to the Handler Looper queue and returns. Since both handlers are created on the same looper, the second runnable is executed after the first one terminates (plus whatever left of the 500 ms delay)
UPDATE:
You need something like that
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
btn1.setBackgroundColor(Color.GREEN);
}
}, 1000);
handler.postDelayed(new Runnable() {
#Override
public void run() {
btn1.setBackgroundResource(R.drawable.selector);
}
}, 2000);
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
//Your Work
}
}, 1000);

Categories

Resources