Android线程间通信机制

借用别人的图如下:
这里写图片描述
1.Message
线程间通信就是在传递消息,Message就是消息的载体。常用的有四个字段:
arg1 , arg2 , what ,obj 。源代码如下:

 /**
     * User-defined message code so that the recipient can identify
     * what this message is about. Each {@link Handler} has its own name-space
     * for message codes, so you do not need to worry about yours conflicting
     * with other handlers.
     */
    public int what;

    /**
     * arg1 and arg2 are lower-cost alternatives to using
     * {@link #setData(Bundle) setData()} if you only need to store a
     * few integer values.
     */
    public int arg1;

    /**
     * arg1 and arg2 are lower-cost alternatives to using
     * {@link #setData(Bundle) setData()} if you only need to store a
     * few integer values.
     */
    public int arg2;

    /**
     * An arbitrary object to send to the recipient.  When using
     * {@link Messenger} to send the message across processes this can only
     * be non-null if it contains a Parcelable of a framework class (not one
     * implemented by the application).   For other data transfer use
     * {@link #setData}.
     *
     * <p>Note that Parcelable objects here are not supported prior to
     * the {@link android.os.Build.VERSION_CODES#FROYO} release.
     */
    public Object obj;

其中obj可以携带Object对象,其余三个可以携带整形数据。
2.MessageQueue
MessageQueue是消息队列,他主要用于存放所有通过Handler发送的消息(就是每个Message),这部分消息会一直存在于消息队列中,等待被处理。每个线程中只会有一个MessageQueue对象。
3.Looper
每个线程通过Handler发送的消息都保存在MessageQueue中,Looper通过调用loop()方法,就会进入到一个无限循环当中,然后每当发现MessageQueue中存在一条消息,就会将它取出,并传递到Handler的HandleMessage()方法中。每个线程中只会有一个Looper对象。
4.Handler
他主要用于发送和处理消息,一般使用senfMessage()方法,还有其他的sendXXX的方法,最终都是调用了sendMessageAtTime()方法,除了sendMessageAtFrontOfQueue()方法,只要实现了Looper的线程构建Handler类,那么这个Handler实例就获取该Looper线程MessageQueue实例的引用,Handler 在sendMessage()的时候就通过这个引用往消息队列里插入新消息。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值