ANR 与FC 异常概念理解
ANR(Activity Not Respone)(无响应)
先介绍下Main线程(也称为UI线程、主线程)
功能
1. 创建UI控件
2. 更新UI控件状态
3. 事件处理
限制
Main线程不建议有超过5秒的事件
出现条件
- 当用户输入事件5s内没有得到响应,将弹出ANR对话框
- 广播接收者的onReceive()执行时间超过10s
解决方案(原则)
所有可能的耗时操作都要在子线程()中执行,常见耗时操作:I/O 网络操作 SDcard 数据运算
FC(Force close)
原因
1.Error
OOM(out of memory error)
StackOverFlowError
2.RuntimeException
解决办法:
看日志
子线程不能更新UI的解决思路:
1、 将子线程执行结果发送到Main线程:handler+massage线程间通讯。
发送消息:
Message msg = mHandler.obtainMessage(UPLOAD, json);
mHandler.sendMessage(msg);
接收消息:
public void handleMessage(Message msg) {
switch (msg.what) {
case UPLOAD:
mTextView2.setText((String) msg.obj);
break;
case DOWNLOAD:
mTextView.setText((String) msg.obj);
break;
default:
break;
}
}
2、 使更新ui代码段在Main线程执行:
1.runOnUiThread
2.view.post view.postDelay()
3.handler.post handler.postDelay()