断其一指------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();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值