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.

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值