How is CountDownTimer accessing UI inside OnTick method?

十年热恋 提交于 2019-12-01 04:24:25

问题


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.



来源:https://stackoverflow.com/questions/6354740/how-is-countdowntimer-accessing-ui-inside-ontick-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!