码迷,mamicode.com
首页 > 其他好文 > 详细

断其一指------Handler消息传递机制

时间:2015-08-16 16:44:47      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:android   handler   消息处理机制   多线程   

出于性能优化的考虑,Android的UI操作并不是线程安全的,如果多个线程同时处理UI,可能会出现线程安全的问题。所以,谷歌的大神们想出了一个简单粗暴的解决方案:只有主线程才能操作UI。

为了能够让UI线程和其他线程进行通信,引入了Handler消息传递机制。

常用方法:
handleMessage() 处理消息的方法
sendEmptyMessage() 发送空消息
sendMessage() 发送消息
sendEmptyMessageDelayed 指定多少毫秒后发送空消息
sendMessageDelayed 指定多少毫秒后发送消息

工作原理:
和Handler一起工作的几个组件:
·Message Handler接收和处理的对象
·MessageQueue 消息队列,它是采用了先进先出的方式来管理Message,由Looper负责管理
·Looper 每一个线程只能有一个Looper,管理消息队列,并不断的从消息队列中取出消息,并将消息分给对应的Handler处理。

步骤:
1.调用Looper的prepare()方法为当前的线程创建Looper对象,构造方法会随着创建一个配套的消息队列
2.创建Handler子类的实例,并重写handleMessage()方法,负责处理来自其他线程的消息。
3.调用Looper的loop方法启动Looper。

消息传递机制的流程:

技术分享

示例:子线程计算从1+2+3+4+……+5000的数据,并传递到主线程中显示到界面上

public class HandlerActivity extends Activity
{
    private TextView mTvResult;
    private Handler handler;
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        mTvResult = (TextView) findViewById(R.id.tv_result);
        getResult();
        handler = new Handler(){
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if(msg.what == 0x1)
                {
                   mTvResult.setText(msg.getData().getString("result","0"));
                }
            }
        };
    }

    public void getResult()
    {
        new Thread(new Runnable() {
            public void run() {
                Message msg = new Message();
                msg.what = 0x1;
                int sum = 0;
                for(int i = 1 ; i <= 5000 ; i++)
                {
                    sum += i;
                }
                Bundle bundle = new Bundle();
                bundle.putString("result",Integer.toString(sum));
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        }).start();
    }
}

版权声明:刚出锅的原创内容,希望对你有帮助~

断其一指------Handler消息传递机制

标签:android   handler   消息处理机制   多线程   

原文地址:http://blog.csdn.net/liangyu2014/article/details/47702811

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!