Accessing UI view in another thread does *not* cause a crash. Why?

孤街浪徒 提交于 2019-12-21 20:56:04

问题


All:

I really don't grok handlers yet. I thought that the code below -- modified so that, instead of using a handler, the UI widget (progress bar) was accessed directly -- would cause a cross-threading exception. But it doesn't. So, my question is, shouldn't this code crash? And if it doesn't, then when do I need to use a handler?

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        progress = 0;
        progressBar = (ProgressBar) findViewById(R.id.progressbar);
        progressBar.setMax(200);

        //---do some work in background thread---
        new Thread(new Runnable()
        {
            public void run()
            {
                //ó-do some work hereó-
                while (progressStatus < 200)
                {
                    progressStatus = doSomeWork();
                    progressBar.setProgress(progressStatus); // not on UI thread
                    //ó-Update the progress baró-            // so shouldn't it crash?
//                    handler.post(new Runnable()
//                    {
//                        public void run() {
//                            progressBar.setProgress(progressStatus);
//                        }
//                    });
                }

                //---hides the progress bar---
                handler.post(new Runnable()
                {
                    public void run()
                    {
                        //---0 - VISIBLE; 4 - INVISIBLE; 8 - GONE---
                        progressBar.setVisibility(View.GONE);
                    }
                });
            }

回答1:


Nowadays, ProgressBar has logic that allows setProgress() to be called on a background thread. It checks to see what thread you are on and does its own post() of a Runnable if needed. You can see this in the source code.



来源:https://stackoverflow.com/questions/14220883/accessing-ui-view-in-another-thread-does-not-cause-a-crash-why

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