异常1
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
原因:
在子线程中更新ui,抛出异常
代码:
/**
* 错误
* android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
* 在子线程中更新ui,抛出
*/
private void myError1(){
new Thread() {
@Override
public void run() {
try {
Thread.sleep(5000);
textView.setText("zhh");
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
异常2
java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare()
原因
在子线程中直接new handler对象 因为子线程中缺少Looper对象
主线程中默认有Looper对象,所以主线程可以
如果非要在子线程中new handler对象,可在HandlerThread中实例化,或者自己写Looper.prepare()
代码:
/**
* java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
* 在子线程中直接new handler对象 因为子线程中缺少Looper对象
* 主线程中默认有Looper对象,所以主线程可以
* 如果非要在子线程中new handler对象,可在HandlerThread中实例化,或者自己写Looper.prepare()
*/
private void myError2(){
new Thread(){
@Override
public void run(){
Handler handler = new Handler();
}
}.start();
}
参考视频:
https://www.imooc.com/learn/267
源码下载:
https://download.csdn.net/download/zhaihaohao1/10650382