手动Handler与Thread处理UI数据同步问题
2015-08-25 16:25
465 查看
(1)在Android 2.3以前,为防止ANR(Application Not Responding),Google是不赞成将网络连接等一系列耗时操作直接放到应用主线程进行的,推荐将这类操作放在子线程内;而Android 4.0版本开始,Google强制要求这类操作必须在子线程内进行,否则将抛出 NetworkOnMainThreadException 异常。
(2)操作UI必须只能在主线程内进行,否则报“Can’t create handler inside thread that has not called Looper.prepare()”错误。注意Toast 也属于UI操作
Thread与Handler的简单使用:
(2)操作UI必须只能在主线程内进行,否则报“Can’t create handler inside thread that has not called Looper.prepare()”错误。注意Toast 也属于UI操作
Thread与Handler的简单使用:
public class TestActivity extends Activity { //自定义数据处理handler private Handler myHandler = new Handler() { @Override public void handleMessage(Message msg) { //更新UI数据 if (msg.what == 1) { String message = (String) msg.obj; Toast.makeText(TestActivity.this, message, Toast.LENGTH_SHORT).show(); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.test); Button btnLoad = (Button) this.findViewById(R.id.btnLoad); btnLoad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Thread thread = new Thread() { @Override public void run() { try { Thread.sleep(1000*10); Message message = new Message(); message.what = 1; message.obj = "测试调用完成"; //向主线程发送数据 myHandler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); Log.e(TestActivity.class.toString(), e.getMessage()); } } }; thread.start(); } }); } }
相关文章推荐
- POJ-1503 Integer Inquiry-多个大数相加
- POJ-2299 Ultra-QuickSort-分治法排序求交换速度
- UIScrollView使用
- 无需编码实现UI动效:XCode+Canvas
- easyui-combobox如何使用选择器
- 代码里手动编写UI
- building live555 library for iphoneos
- POJ 2524 Ubiquitous Religions 并查集
- [leetcode] 95.Unique Binary Search Trees II
- UILabel设置圆角和背景
- 外来人员如何发起流程与参与内部流程?CCFlow中Guest流程说明
- 回顾交互设计史:回归人性,重拾质朴
- POJ - 2524 Ubiquitous Religions(简单并查集)
- Repository 返回 IQueryable?还是 IEnumerable?
- HDU 1159 Common Subsequence
- uestc 250 windy数(数位dp)
- 外来人员如何发起流程与参与内部流程?CCFlow中Guest流程说明
- BUILD
- UE4引擎学习
- fuel自动安装openstack文档