UI阻塞及其优化

来源:互联网 发布:js字符串中的换行符 编辑:程序博客网 时间:2024/06/06 08:33

There are  simply two rules to Android's single thread model :安卓单线程模型两个基本原则

1.Don't block the UI thread 不要阻塞UI线程

2.Don't access the Android UI toolkit from outside the UI thread

不要在UI线程之外的其他线程中,对视图当中的组件进行设置

否则会报经典错误

Only the original thread that created a view hierarchy can touch its views只有创建View的那个线程才能对其进行修改


官方提供了两个解决方案

解决方法1:

建立一个线程,并调用view.post()方法调用视图中的组件

线程ID,是操作系统识别线程的唯一标志。

在view.post中打印线程和主线程id一样都是1,如图所示,view.post方法会给任务队列中加入一个任务,Runable对象

UI主线程会检测任务队列中是否有任务需要完成,所以通过调用view.post()方法,可以解决建立新线程修改view组件

但是可读性差,可维护性差



解决方法2:Asynctask

0 0