关于开启线程与UI的操作

Posted on 2017-07-18 20:24  番茄番茄  阅读(347)  评论(0编辑  收藏  举报

当应用程序启动,创建了一个叫“main”的线程,用于管理UI相关,又叫UI线程。其他线程叫工作线程(Work Thread)。

Single Thread Model(单线程模型)

一个组件的创建并不会新建一个线程,他们的创建都在UI线程中进行,包括他们的回调方法,如onKeyDown()

  • 当在UI线程中进行某些耗时的操作时,将会阻塞UI线程,一般阻塞超过5秒就会报错

UI线程是非线程安全的,所以,不能在工作线程中操作UI元素。

 

两个原则

  • Do not block the UI thread (不要阻塞UI线程)
  • Do not access the Android UI toolkit from outside the UI thread (不要在工作线程中操作UI元素)

 

在工作线程更新UI方法

  • Activity.runOnUiThread(new Runnable),在子线程中直接调用
    runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mTvShow.setText(respone);
                                    }
                                });

     

  • Handler,,在Main中新建Handle实例,重写handleMessage(),方法,在里面用接受值操作UI
    Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
               Bundle bundle = msg.getData();
                String aa = bundle.getString("aa");
                mTvShow.setText(aa);
            }
        };

    在子线程中赋值,并且传值给Handle。

    Bundle bundle = new Bundle();
    Message message = Message.obtain(); bundle.putString(
    "aa",responseData); message.setData(bundle); handler.sendMessage(message);

     

  • AsyncTask
    • execute()
    • doInBackground()
    • onPostExecute()