首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

android Handler使用时一个易犯的异常

2012-09-09 
android Handler使用时一个易犯的错误????? 最近在使用handler的时候发现一个容易犯的错误,研究了一天才搞

android Handler使用时一个易犯的错误

????? 最近在使用handler的时候发现一个容易犯的错误,研究了一天才搞好。

handler使用方法简介:

?????? Handler mHandler;

1 定义handler,并实现handlerMessage()方法,用来处理后台线程发过来的消息。

??? ??? mHandler = new Handler() {

??? ??? ??? @Override
??? ??? ??? public void handleMessage(Message msg) {
??? ??? ??? ??? //需要在主线程里面处理的内容
??? ??? ??? ??? super.handleMessage(msg);
??? ??? ??? }
??? ??? };

2 在后台线程(或者叫非UI控制线程的主线程)中,做完某一件事情,调用mHandler.sendMessage告诉主线程:

?? 参数Message可以自己增加需要携带的内容,也可以new一个空的Message。
??? ??? new Thread(new Runnable() {
??? ??? ???
??? ??? ??? @Override
??? ??? ??? public void run() {
??? ??? ??? ??? Message msg = new Message();
??? ??? ??? ??? mHandler.sendMessage(msg);
??? ??? ??? }
??? ??? }, "subThread").start();

?? 子线程sendMessage以后,主线程的handleMessage方法就可以收到通知并修改ui。

?

3? 我因为对Handler.post方法理解不到位,犯了一个错误:

??? 在子线程启动时用了mHandler.post(new Runnable(){...},导致子线程运行时占用了主线程的执行时间,没有实现需要的功能。

??? post方法说明如下:

??? Causes the Runnable r to be added to the message queue. The runnable will be run on the thread to which this handler is attached.

?

热点排行