How is CountDownTimer accessing UI inside OnTick m

2019-02-18 01:56发布

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

3条回答
Melony?
2楼-- · 2019-02-18 02:34

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.

查看更多
来,给爷笑一个
3楼-- · 2019-02-18 02:34

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.

查看更多
萌系小妹纸
4楼-- · 2019-02-18 02:52

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.

查看更多
登录 后发表回答