Android中的Message

一,Message
我的理解是消息就是数据的载体,它就是用来存放数据的,它的实例化有以下几种方式:
1.通过构造函数

Message msg = new Message();

2通过obtain方法

Message msg = Message.obtain();

3.通过handler

Handler handler;
Message msg = handler.obtainMessage();

推荐使用第二种方式创建消息,第二种方式创建消息可以节省内存,它的源码如下

 /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

Message中存在一个消息池用来存放已经创建的消息,obtain方法中先判断消息池中是否有消息,如果有消息就从消息池中取出消息,如果没有就通过Message的构造方法创建新的消息,这样做节省了内存,也就是为什么提倡使用第二种方式创建消息的原因
第三中方式在本质上也是通过第二种方式创建的,源码如下

/**
     * Returns a new {@link android.os.Message Message} from the global message pool. More efficient than
     * creating and allocating new instances. The retrieved message has its handler set to this instance (Message.target == this).
     *  If you don't want that facility, just call Message.obtain() instead.
     */
    public final Message obtainMessage()
    {
        return Message.obtain(this);
    }

Message有以下几个常用的属性:arg1, arg2, obj, what,其中arg1,arg2是用来存储int型的值,obj用来存储对象,what是为了让消息的接受者识别出接收的消息是哪个消息。

二,消息的发送
第一种方法:

        Message msg = Message.obtain();
        msg.what = 1;
        msg.arg1 = 5;
        msg.arg2 = 10;
        msg.obj = "hello";
        handler.sendMessage(msg);

第二种:obtain(Handler h)

        Message msg = Message.obtain(handler);
        msg.what = 1;
        msg.arg1 = 5;
        msg.arg2 = 10;
        msg.obj = "hello";
        msg.sendToTarget();

该obtain方法的源码

 /**
     * Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message returned.
     * @param h  Handler to assign to the returned Message object's <em>target</em> member.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Handler h) {
        Message m = obtain();
        m.target = h;

        return m;
    }

    public void sendToTarget() {
        target.sendMessage(this);
    }

Message.obtain(handler);该方法通过obtain()方法创建Message,并将Message的target设置为handler,在sendToTarget()方法中调用handler.sendMessage(msg)方法。
所以说第二种方法发送消息的方式本质上和第一种是一样的,只是说它对第一种方式进行了封装。

obtain还有以下几种静态重载方法:
1.Message obtain(Handler h, int what, int arg1, int arg2, Object obj);

2 Message obtain(Handler h, int what, Object obj);

3 Message obtain(Handler h, int what);
和第二种是一个道理在本质上都是第一种方式的变形

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值