我写了下面一段代码,如果把PPP类中的run方法里面的sleep去除,会发现程序成功的改变了TextView的文字,或者sleep后的参数放置的比较小,程序也能成功的改变TextView的文字。如果我在sleep后面放置的值大一些(换过一些数字后发现是 > 150,也许和运行环境有关),就会出现CalledFromWrongThreadException异常,这是什么原理?为什么在前面的情况下我可以在非主线程中间改变ui,而后面的情况却不可以?public class TV extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HandlerThread ht = new HandlerThread("pig");
ht.start();
Handler h = new Handler(ht.getLooper());
h.post(new PPP((TextView) findViewById(R.id.t)));
}
class PPP implements Runnable{ private TextView tv;
public PPP(TextView tv){
this.tv = tv;
}
@Override
public void run() {
try {
Thread.sleep(140);//这里
} catch (InterruptedException e) {
e.printStackTrace();
}
tv.setText("11111111111");
}
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
HandlerThread ht = new HandlerThread("pig");
ht.start();
Handler h = new Handler(ht.getLooper());
h.post(new PPP((TextView) findViewById(R.id.t)));
}
class PPP implements Runnable{ private TextView tv;
public PPP(TextView tv){
this.tv = tv;
}
@Override
public void run() {
try {
Thread.sleep(140);//这里
} catch (InterruptedException e) {
e.printStackTrace();
}
tv.setText("11111111111");
}
}
}
解决方案 »
- 新手求教个代码编译的问题
- Attach双向鉴权 以及Attach_Reject原因为Illegal MS
- 我创建的TXT文件在手机哪里?
- 请教使用camera类拍照后如何返回该照片路径?
- 如何管理同一源码的不同工程
- 主activity 跳转子到子activity 但是不执行子activity 的onCreate方法
- sqlite 查询 遍历 datetime
- 怎样使两个按钮的位置成为左右并列而不覆盖?谢谢!
- android 加载网络图片资源出现异常
- 关于利用POI在Android 上直接编辑word模板出错问题。
- Android平台自动化测试DEMO视频
- 一年android经验,android要怎么提高?????
因为如果长时间的业务放到了UI线程的话, 当这个业务在运行的时候,你在UI上做了别的操作,
如果一段时间之内的这个操作没有响应就会导致ANR的
正如3楼所说
有时候你放在子线程里去对ui线程做操作并不会报错,但是那是不安全的,还是有几率报错的