Android中获得Message对象三种方式的去呗

获得Message对象的三种方式

1.new Message()
2.Message.obtain()
3.handler.obtainMessage()

1.new Message();
这个方法没什么好多说的就是new一个对象
2.Message.obtain();
点进去看源码:

/**
     * 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;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }
看注释可知道,从消息池中返回一个新的实例,避免我们创建更多的实例对象,那么这个消息池是什么呢?我们找一下:
private static Message sPool;
private static final int MAX_POOL_SIZE = 50;

消息池最多能够保存50个消息,这里类似于线程池,同时根据源码我们也可以知道obtain()方法是线程安全的。所以通过这种方法创建Message对象可以避免创建新的Message对象,达到节省内存的作用。(ps:handler处理完消息,消息队列会自动recycle()释放消息,有时候我们在使用的时候会报该消息还在使用,这是因为这个消息还未处理,我们又发送了这个消息,这时我们只需要重新创建一个消息。)

3.handler.obtainMessage();

/**
     * 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);
    }


/**
     * Same as {@link #obtain()}, but sets the values for both <em>target</em> and
     * <em>what</em> members on the Message.
     * @param h  Value to assign to the <em>target</em> member.
     * @param what  Value to assign to the <em>what</em> member.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Handler h, int what) {
        Message m = obtain();//调用了obtain方法
        m.target = h;
        m.what = what;

        return m;
    }

从注释可以知道,这个函数会将handler对象赋值给message.taget,如果不想要这种便利,可以调用Message.obtain()函数,个人比较倾向于使用handler.obtainMessage();

总结:

1.new Message()没有任何技术含量
2.Message.obtain(),从消息池中复用Message对象,节省内存,而且现成安全
3.handler.obtainMessage()会将handler赋值给message.target,提供便利
在使用的过程中,使用Message.obtain(),或者handler.obtainmessage()
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值