-->

How is CountDownTimer accessing UI inside OnTick m

2019-02-18 02:41发布

问题:

How CountDownTimer is accessing UI inside onTick method?

(new CountDownTimer(10000,1000){

    @Override
    public void onFinish() {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTick(long millisUntilFinished) {
        TextView tv = (TextView)findViewById(R.id.tvLCD);
        tv.setText(Long.toString(millisUntilFinished));
    }           
}).start();

回答1:

You can get access to UI from thread by Activity.runOnUiTread(), View.post(), View.postDelayed() or via Handler. CountDownTimer uses Handler for this purpose (source).

Read this article for understanding how to use all of these methods.



回答2:

From the links( GreCode - Handler ) in the answer given by @Sergey Glotov, it is clear that countdown timer does not use a seperate thread at all. That is the reason you are able to access the all the UI elements. I don't know why they have used a handler. But it does not spawn a new thread. It runs on the UI thread itself.



回答3:

CountDownTimer does NOT have any mechanism to access UI inside onTick method. More importantly, from the source code, you can see that internally it uses an handler that is taken at object creation. So it runs on the Thread where the timer was created.

The question is ill-posed, in your case i suppose you can access those views because probably you create the CountDownTimer as anonymous class on an activity. And if you were lucky enough, this was done on the UI thread.