欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Handler学习笔记

程序员文章站 2022-07-14 15:10:06
...

使用经典示例代码:

public class MainActivity extends AppCompatActivity {
    private TextView tv;
    private Handler mHandler;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        mHandler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                String msgStr = (String) msg.obj;
                tv.setText(msgStr);
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    Message message = Message.obtain();
                    message.obj = "message 1";
                    mHandler.sendMessage(message);
                    Thread.sleep(1000);
                    message.obj = "message 2";
             mHandler.sendMessageDelayed(message,1000);
                    Thread.sleep(1000);
                    message.obj = "message 3";
                    mHandler.sendMessageAtTime(message,300);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

mHandler.sendMessageXXX的核心逻辑代码

mHandler.sendMessage 最终会调用MessageQueue中的enqueueMessage(Message msg, long when)方法,其核心代码如下

boolean enqueueMessage(Message msg, long when) {
        //省略部分代码后的代码
        synchronized (this) {
            msg.when = when;
            Message p = mMessages;
            if (p == null || when == 0 || when < p.when) {
                //链表的下一个赋值
                msg.next = p;
                mMessages = msg;
            } else {
                Message prev;
                for (;;) {
                    //链表前一个
                    prev = p;
                    //当前
                    p = p.next;
                    //按照when排序
                    if (p == null || when < p.when) {
                        break;
                    }
                }
                //链表的下一个
                msg.next = p; 
                //前一个的下一个是当前
                prev.next = msg;
            }
        }
        return true;
    }

sendMessageXXX总结

enqueueMessage的核心操作是将Message对象按照when从小到大顺序插入到消息队列链表,并没有其它操作。例如示例中的Message顺序接口为
msg1 msg1.next->msg3
msg3 msg3.next->msg2
msg2 msg2.next->null

为啥MessageQueue采用链表结构存储

链表的插入和删除快,特别是在中间插入数据时。但是链表结构不适合查询操作

Looper的相关问题分析

1、 子线程中创建Handler直接new会出异常,原因如下
mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread that has not called Looper.prepare()");
        }
2、为啥主线程中不会报错,因为在ActivityThread的main方法中有如下代码
//prepareMainLooper最终调用了Looper的prepare()方法会自动为主线程创建应的Looper
Looper.prepareMainLooper();
//能让消息循环起来
Looper.loop();
3、 Looper.prepare()的源码
private static void prepare(boolean quitAllowed) {
        //sThreadLocal 能保证一个线程对应一个对象
        if (sThreadLocal.get() != null) {
            throw new RuntimeException("Only one Looper may be created per thread");
        }
        //当前线程绑定Looper对象
        sThreadLocal.set(new Looper(quitAllowed));
    }
4、 Looper.loop源码分析
public static void loop() {
        //得到当前Looper
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //Looper关联的详细队列
        final MessageQueue queue = me.mQueue;

        Binder.clearCallingIdentity();
        final long ident = Binder.clearCallingIdentity();
        //死循环
        for (;;) {
            Message msg = queue.next(); // might block
            //没有消息直接返回
            if (msg == null) {
                return;
            }
            try {
                //msg.target是在sendMessage时指定为当前的
                //Handler,这里会调用handlerMessage回调
                msg.target.dispatchMessage(msg);
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            //消息回收
            msg.recycleUnchecked();
        }
    }
相关标签: handler机制