Message Handler Looper

本文介绍了Android中的Message创建方式,强调了Message.obtain()的效率优势。Handler用于发送和处理Message,关键方法包括sendMessage()和handleMessage()。Looper作为消息循环,通过loop()不断从MessageQueue中取出消息交给Handler处理。Looper的prepare()方法在特定线程创建消息队列,而sendMessage()则将Message加入队列等待处理。
摘要由CSDN通过智能技术生成

一、Message

Message创建方式有两种,一种是new Message(),开销较大,另外一种是Message.obtain(),使用回收但是没有被释放的message对象,减少开销,有点类似Adapter中的ConvertView与ViewHolder,一般使用Message msg = Handler.obtain(),事实上也是调用Message.Obtain().

Handler.class

/**
     * 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.class

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

通过recycle回收的Message对象

Message.class

    /**
     * Return a Message instance to the global pool.  You MUST NOT touch
     * the Message after calling this function -- it has effectively been
     * freed.
     */
    public void recycle() {
        clearForRecycle();

        synchronized (sPoolSync) {
            i
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值