开发者社区> 问答> 正文

Android非UI线程无法更新UI问题

使用HandlerThread获取Looper对象,后创建Handler(mHandlerThread.getLooper),此时的HandleMessage()在子线程中运行,为何此处可以更新UI?

public class MainActivity extends AppCompatActivity {

    private TextView mTvText ;
    private Handler mHandler;
    // 使用这个新线程获取Looper对象
    private HandlerThread mHandlerThread = new HandlerThread("my_handler_thread");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTvText = (TextView)findViewById(R.id.id_tv_text);
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper()){
            @Override
            public void handleMessage(Message msg) {
                // 此处显示在子线程中执行 handleMessage()
                // 为何在此处(子线程中)更新UI组件不会抛出异常?
                Log.v("LOG","CurThread: "+Thread.currentThread());
                // CurThread:Thread[my_handler_thread,5,Main]
                mTvText.setText("update this textView!");
            }
        };
        mHandler.sendEmptyMessage(1);
    }
}

展开
收起
蛮大人123 2016-03-11 15:48:11 2650 0
2 条回答
写回答
取消 提交回答
  • elk

    在分线程更新,在主线程显示

    2019-07-17 18:59:26
    赞同 展开评论 打赏
  • 我说我不帅他们就打我,还说我虚伪

    题主的代码确实是在子线程中更新的,可以打印 thread id 验证:
    `// Use the provided Looper instead of the default one.
    public Handler(Looper looper) {}`
    所以在子线程中常常可以通过如下方法获取主线程的 handler,也可以使用题主的方法在主线程中获取子线程的 handler:
    `// 这是一个主线程的 handler
    new Handler(getContext().getMainLooper());`
    至于为什么没有crash,确实很奇怪,我去查了 setText,实在复杂,没有看出端倪,但是倘若这样去做,会 crash:

    mButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mHandler.sendEmptyMessage(1);
        }
    });

    crash log 如下:

    FATAL EXCEPTION: my_handler_thread
        Process: com.magellan.mapdemo, PID: 2302
        android.view.ViewRootImpl$CalledFromWrongThreadException:
         Only the original thread that created a view hierarchy can touch its views.
         ......
        at android.widget.TextView.setText(TextView.java:4862)

    所以我猜,crash 的关键词是 touch .
    结论:不应该在子线程中更新UI,非常危险!
    参考:http://stackoverflow.com/questions/14220883/accessing-ui-view-in-another-thread-does-not-cause-a-crash-why
    http://www.codes9.com/mobile-development/android/about-the-update-ui-control-does-not-ui-in-non-crash-thread-problems/

    2019-07-17 18:59:26
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
使用TensorFlow搭建智能开发系统自劢生成App UI代码 立即下载
Fusion Design - 企业级UI解决方案揭秘 立即下载
使用TensorFlow搭建智能开发系统自动生成App UI 立即下载