Reputation: 596
The following code is from Head First Android. It is for a stopwatch app.
I have a few questions in the following code:
Why does it skip hander.post()
in the first place?
Why doesn't the first one work? I am expecting the text to jump back and forth from "hello" to "hh:mm:ss".
Does the code starts running normally and when its 1 second the postDelay() is called?
why is this used in postDealy(this, 100). shouldn't it be this.run()
?
public class MainActivity extends AppCompatActivity {
private boolean running = false;
private int counter = 0;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runTimer();
}
public void onClickStart(View view){
running = true;
}
public void runTimer(){
final TextView textView = findViewById(R.id.timer);
handler.post(new Runnable() {
@Override
public void run() {
int hours = counter/3600;
int minutes = (counter%3600)/60;
int secs = counter%60;
String time = String.format("%d:%02d:%02d", hours, minutes, secs);
textView.setText(time); // Doesn't set it to this - see last line
if(running){
counter++;
}
handler.postDelayed(this,1000); // what does happens between next one second
textView.setText("hell0"); // Always set it to this
}
});
}
Upvotes: 1
Views: 820
Reputation: 2853
handler.postDelayed(this,1000);
This used to run your function after 1 second. It is a delay for 1 second.
The code written in your handler
will execute after a second. That's all.
Upvotes: 1
Reputation: 19949
Why does it skip
hander.post()
in the first place?
It is not skipped, it will be executed after onResume()
returns. All the Runnable
s, queued though a Handler associated with the main thread, start their execution only after onResume()
returns.
Why doesn't the first one work?
It does work. You just can't visually see it because the two method calls, textView.setText()
, are invoked "almost" at the same time.
The following sequence of calls happen at each run()
:
textView.setText(time)
,Runnable
is posted to the queue with handler.postDelayed(this,1000)
. Immediately after thattextView.setText("hell0")
is calledWhy doesn't the first one work? I am expecting the text to jump back and forth from "hello" to "hh:mm:ss".
You should implement an extra logic to switch between time and "hell0" at each run()
execution.
E.g. create a boolean flag in the Activity and set either time or "hell0" depending on the flag value (don't forget to change the flag value at each run()
execution).
why is this used in postDelay(this, 100). shouldn't it be
this.run()
?
No, this.run()
is executed synchronously (and immediately) and is of type void. The code won't compile as postDelay() expects the Runnable type, not void.
Upvotes: 1