当前位置: 首页 > news >正文

了解Handler,Looper, MessageQueue,Message的工作流程

Handler的作用

异步通信,消息传递

Handler的基本用法

Handler的用法,示例1、(子线程向主线程发送消息)

public class HandlerActivity extends AppCompatActivity {
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        Toast.makeText(HandlerActivity.this, "接收到了消息", Toast.LENGTH_SHORT).show();
    }
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_handler);

}

public void onClickView(View v) {
    switch (v.getId()) {
        case R.id.button: {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    Message msg = Message.obtain();
                    handler.sendMessage(msg);
                }
            };
            thread.start();
            break;
        }
    }
}
}

这个界面只有一个Button, 点击事件是:启动一个线程,在这个线程里使用handler,发送一个消息;这个消息不带任何数据。
Message: 这个可以使用new来生成,但是最好还是使用Message.obtain()来获取一个实例。这样便于消息池的管理。
handler初始化的时候,我们复写了handleMessage方法,这个方法用来接收,子线程中发过来的消息。

示例2、主线程向子线程发送消息

public class HandlerActivity extends AppCompatActivity {
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        Log.d("child", "----" + Thread.currentThread().getName());
    }
};
Handler childHandler = null;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_handler);
    Thread child = new Thread("child thread") {
        @Override
        public void run() {
            Looper.prepare();
            childHandler = new Handler(Looper.myLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    Log.d("child", "----" + Thread.currentThread().getName() + ",  " + msg.obj);
                }
            };
            Looper.loop();
        }
    };
    child.start();
}

public void onClickView(View v) {
    switch (v.getId()) {
        case R.id.button: {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    Message msg = Message.obtain();
                    handler.sendMessage(msg);
                }
            };
            thread.start();
            break;
        }
        case R.id.button1: {
            if (childHandler != null) {
                Message msg = Message.obtain(childHandler);
                msg.obj = "123---" + SystemClock.uptimeMillis();
                childHandler.sendMessage(msg);

            } else {
                Log.d("-----", "onClickView: child Handler is null");
            }

            break;
        }
    }
}
}

主线程向子线程发送消息时,我们需要使用的是handler,但是这个handler是需要在子线程中实例化,否则子线程无法接收到消息。
在child thread中准备的工作:

    1. Looper.prepare();
    1. 实例化childHandler的时候出入了一个Looper实例。
    1. Looper.loop()调用
      假如我们直接在子线程中直接实例化一个handler,而不传入Looper实例。程序会直接抛出异常:
      java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
      这个异常是在hanlder源码:

      public Handler(Callback callback, boolean async) {
      if (FIND_POTENTIAL_LEAKS) {
      final Class<? extends Handler> klass = getClass();
      if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
      (klass.getModifiers() & Modifier.STATIC) == 0) {
      Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
      klass.getCanonicalName());
      }
      }
      mLooper = Looper.myLooper();
      if (mLooper == null) {
      throw new RuntimeException(
      "Can't create handler inside thread that has not called Looper.prepare()");
      }

      mQueue = mLooper.mQueue;
      mCallback = callback;
      mAsynchronous = async;
      }
      出现的,从这里可知,在线程中实例化一个handler需要一个Looper实例。

      如果其他线程的实例出来的Looper会怎么样?

      首先看Looper源码中是怎么写的。Looper的构造方法是私有的,这样我们只能通过Looper的静态方法来实例化一个Looper.在Looper类中还有一个ThreadLocal<Looper> sThreadLocal 变量,而在上面的代码中使用了Looper.myLooper()方法来给handler一个Looper实例。

      * Looper.myLooper()

      public static @Nullable Looper myLooper() {
      return sThreadLocal.get();
      }

      这个方法返回了一个存放在ThreadLocal<Looper>中的Looper实例。

      为什么在调用Looper.myLooper()方法之前需要先调用 Looper.prepare()呢?

      Looper.prepare源码:

    public static void prepare() {
    prepare(true);
    }
    private static void prepare(boolean quitAllowed) {
    if (sThreadLocal.get() != null) {
    throw new RuntimeException("Only one Looper may be created per thread");
    }
    sThreadLocal.set(new Looper(quitAllowed));
    }
    方法很简单,就是检查sThreadLocal里面是否有有值,然后将Looper的实例存放到ThreadLocal,如果不为空,直接就是 RuntimeException 异常。这也保证了一个线程中只能有一个Looper实例。因此,Looper.prepare方法只能调用一次。

    那么ThreadLocal的作用是什么呢?

    在这个程序中,可以大概理解成线程间数据的隔离。意思就是我存放在ThreadLocal中的数据,只能在我本线程中可以获得到值,在其他线程中获取不到(其他线程中获取的是null)。
    这样就能得出,其他线程中的Looper,在本线程中通过Looper.myLooper()获取不到数据。

    那么为什么在主线程中不需要传入Looper实例呢?

    通过查找Android源码,可以知道在ActivityThread中main方法里面,UI线程已经初始化了Looper.prepareMainLooper();这样就在UI线程中有Looper实例了。当然在main方法的下面,也调用了Looper.loop()方法。

    Looper.loop()方法是做什么的

    public static void loop() {
    final Looper me = myLooper();
    if (me == null) {
    throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
    }
    final MessageQueue queue = me.mQueue;
    // Make sure the identity of this thread is that of the local process,
    // and keep track of what that identity token actually is.
    Binder.clearCallingIdentity();
    final long ident = Binder.clearCallingIdentity();

    **for (;;) {**
        **Message msg = queue.next(); // might block**
        if (msg == null) {
            // No message indicates that the message queue is quitting.
            return;
        }
    
        // This must be in a local variable, in case a UI event sets the logger
        final Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }
    
        final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
    
        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (slowDispatchThresholdMs > 0) {
            final long time = end - start;
            if (time > slowDispatchThresholdMs) {
                Slog.w(TAG, "Dispatch took " + time + "ms on "
                        + Thread.currentThread().getName() + ", h=" +
                        msg.target + " cb=" + msg.callback + " msg=" + msg.what);
            }
        }
    
        if (logging != null) {
            logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
        }
    
        // Make sure that during the course of dispatching the
        // identity of the thread wasn't corrupted.
        final long newIdent = Binder.clearCallingIdentity();
        if (ident != newIdent) {
            Log.wtf(TAG, "Thread identity changed from 0x"
                    + Long.toHexString(ident) + " to 0x"
                    + Long.toHexString(newIdent) + " while dispatching to "
                    + msg.target.getClass().getName() + " "
                    + msg.callback + " what=" + msg.what);
        }
    
        msg.recycleUnchecked();
    **}**

    }

这个方法里面,我们需要注意到:

  1. Looper me这个不允许为空
  2. for (;;)循环
  3. Message msg = queue.next()
  4. msg.target.dispatchMessage(msg);

  5. 在looper.loop方法里面,检查了本线程中的Looper实例,也对应了在调用looper.loop方法之前必须先调用looper.prepare方法。
  6. for循环是一个死循环,这个需要一直取出MessageQueue队列中的数据,也就是刚才所列的第三个 queue.next方法。这个方法会阻塞,直到有消息从消息队列中取出来。
    next方法源码:

    Message next() {
    // Return here if the message loop has already quit and been disposed.
    // This can happen if the application tries to restart a looper after quit
    // which is not supported.
    final long ptr = mPtr;
    if (ptr == 0) {
        return null;
    }
    int pendingIdleHandlerCount = -1; // -1 only during first iteration
    int nextPollTimeoutMillis = 0;
    for (;;) {
        if (nextPollTimeoutMillis != 0) {
            Binder.flushPendingCommands();
        }
    
        nativePollOnce(ptr, nextPollTimeoutMillis);
    
        synchronized (this) {
            // Try to retrieve the next message.  Return if found.
            final long now = SystemClock.uptimeMillis();
            Message prevMsg = null;
            Message msg = mMessages;
            if (msg != null && msg.target == null) {
                // Stalled by a barrier.  Find the next asynchronous message in the queue.
                do {
                    prevMsg = msg;
                    msg = msg.next;
                } while (msg != null && !msg.isAsynchronous());
            }
            if (msg != null) {
                if (now < msg.when) {
                    // Next message is not ready.  Set a timeout to wake up when it is ready.
                    nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);
                } else {
                    // Got a message.
                    mBlocked = false;
                    if (prevMsg != null) {
                        prevMsg.next = msg.next;
                    } else {
                        mMessages = msg.next;
                    }
                    msg.next = null;
                    if (DEBUG) Log.v(TAG, "Returning message: " + msg);
                    msg.markInUse();
                    return msg;
                }
            } else {
                // No more messages.
                nextPollTimeoutMillis = -1;
            }
    
            // Process the quit message now that all pending messages have been handled.
            if (mQuitting) {
                dispose();
                return null;
            }
    
            // If first time idle, then get the number of idlers to run.
            // Idle handles only run if the queue is empty or if the first message
            // in the queue (possibly a barrier) is due to be handled in the future.
            if (pendingIdleHandlerCount < 0
                    && (mMessages == null || now < mMessages.when)) {
                pendingIdleHandlerCount = mIdleHandlers.size();
            }
            if (pendingIdleHandlerCount <= 0) {
                // No idle handlers to run.  Loop and wait some more.
                mBlocked = true;
                continue;
            }
    
            if (mPendingIdleHandlers == null) {
                mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
            }
            mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
        }
    
        // Run the idle handlers.
        // We only ever reach this code block during the first iteration.
        for (int i = 0; i < pendingIdleHandlerCount; i++) {
            final IdleHandler idler = mPendingIdleHandlers[i];
            mPendingIdleHandlers[i] = null; // release the reference to the handler
    
            boolean keep = false;
            try {
                keep = idler.queueIdle();
            } catch (Throwable t) {
                Log.wtf(TAG, "IdleHandler threw exception", t);
            }
    
            if (!keep) {
                synchronized (this) {
                    mIdleHandlers.remove(idler);
                }
            }
        }
    
        // Reset the idle handler count to 0 so we do not run them again.
        pendingIdleHandlerCount = 0;
    
        // While calling an idle handler, a new message could have been delivered
        // so go back and look again for a pending message without waiting.
        nextPollTimeoutMillis = 0;
    }

    }

  7. queue.next方法,返回一个Message,而这个message会被传入到msg.target的dispatchMessage方法中。msg.target是一个handler,就是发送消息的实例。
    dispatchMessage(Message)源码:
    public void dispatchMessage(Message msg) {<br/>if (msg.callback != null) {<br/>handleCallback(msg);<br/>} else {<br/>if (mCallback != null) {<br/>if (mCallback.handleMessage(msg)) {<br/>return;<br/>}<br/>}<br/>handleMessage(msg);<br/>}<br/>}<br/>
    Handler初始化的时候,我们并没有传入msg.callback和mCallback这两个回调。所以这个方法最终执行的是handleMessage方法。
    上面我们分析了ThreadLocal,Looper,Message,MessageQueue,下面开始分析handler发送消息的方式。

    Handler发送消息

    Handler 通过sendMessage方法发送消息。这个方法最终调用的是

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {<br/>msg.target = this;<br/>if (mAsynchronous) {<br/>msg.setAsynchronous(true);<br/>}<br/>return queue.enqueueMessage(msg, uptimeMillis);<br/>}<br/>
参数:MessageQueue queue则是Handler中mQueue变量,这个变量在Handler(Callback callback, boolean async)初始化完成。它是Looper中一个final MessageQueue的变量,在初始化Looper的时候,就开始初始化MessageQueue。这也是一个线程中只有一个MessageQueue的原因.
Message msg 是封装的消息。
long uptimeMillis 延迟发送时间。
之前分析looper.loop方法的时候,说了msg.target.dispatchMessage, 这个target就是在这个方法里面赋值的。
从这个方法里面,可以知道handler的sendMessage,只是把消息(Message实例)添加到了queue队列中。

    boolean enqueueMessage(Message msg, long when) {
    if (msg.target == null) {
        throw new IllegalArgumentException("Message must have a target.");
    }
    if (msg.isInUse()) {
        throw new IllegalStateException(msg + " This message is already in use.");
    }
    synchronized (this) {
        if (mQuitting) {
            IllegalStateException e = new IllegalStateException(
                    msg.target + " sending message to a Handler on a dead thread");
            Log.w(TAG, e.getMessage(), e);
            msg.recycle();
            return false;
        }

        msg.markInUse();
        msg.when = when;
        Message p = mMessages;
        boolean needWake;
        if (p == null || when == 0 || when < p.when) {
            // New head, wake up the event queue if blocked.
            msg.next = p;
            mMessages = msg;
            needWake = mBlocked;
        } else {
            // Inserted within the middle of the queue.  Usually we don't have to wake
            // up the event queue unless there is a barrier at the head of the queue
            // and the message is the earliest asynchronous message in the queue.
            needWake = mBlocked && p.target == null && msg.isAsynchronous();
            Message prev;
            for (;;) {
                prev = p;
                p = p.next;
                if (p == null || when < p.when) {
                    break;
                }
                if (needWake && p.isAsynchronous()) {
                    needWake = false;
                }
            }
            msg.next = p; // invariant: p == prev.next
            prev.next = msg;
        }

        // We can assume mPtr != 0 because mQuitting is false.
        if (needWake) {
            nativeWake(mPtr);
        }
    }
    return true;
}

Handler, Looper, Message, MessageQueue之间的关系

通过handler发送Message,将Message压入MessageQueue队列中;而Looper.loop方法又在不停的循环这个消息队列,取出压入MessageQueue的Message, 然后dispatchMessage分发,最终会调用handler.handleMessage方法来处理发送过来的Message.


本文转自 墨宇hz 51CTO博客,原文链接:http://blog.51cto.com/zzhhz/2045446


相关文章:

  • 对BSD的新路由查找算法的理解
  • 验证文件中记录总行数是否与数据库文件同名表记录总数是否一致
  • 编写一个Linux虚拟网卡来实现类NVI
  • Windows下powershell可执行python
  • Css基本样式————文本
  • js 简单实现 LRU
  • DoS Attacks Prevention with TCP Intercept
  • NIOS2随笔——自定义IP(DPRAM)
  • Webpack入门教程十五
  • IPv6, DAD 工作原理详解
  • 解决configure: error: Please reinstall the libcurl distribution
  • tweak 支持第三方库
  • 第十一章 持有对象
  • 条件变量的接口函数和使用原则
  • C# DataGridView中DataGridViewComboBoxCell列,下拉框事件的处理【完美解决】
  • 《网管员必读——网络组建》(第2版)电子课件下载
  • Babel配置的不完全指南
  • co模块的前端实现
  • IP路由与转发
  • java 多线程基础, 我觉得还是有必要看看的
  • JAVA_NIO系列——Channel和Buffer详解
  • k8s如何管理Pod
  • laravel with 查询列表限制条数
  • maven工程打包jar以及java jar命令的classpath使用
  • select2 取值 遍历 设置默认值
  • Selenium实战教程系列(二)---元素定位
  • sublime配置文件
  • 从@property说起(二)当我们写下@property (nonatomic, weak) id obj时,我们究竟写了什么...
  • 给Prometheus造假数据的方法
  • 基于阿里云移动推送的移动应用推送模式最佳实践
  • 开年巨制!千人千面回放技术让你“看到”Flutter用户侧问题
  • 思否第一天
  • 原生JS动态加载JS、CSS文件及代码脚本
  • 掌握面试——弹出框的实现(一道题中包含布局/js设计模式)
  • 智能网联汽车信息安全
  • 最简单的无缝轮播
  • 《TCP IP 详解卷1:协议》阅读笔记 - 第六章
  • TPG领衔财团投资轻奢珠宝品牌APM Monaco
  • ​【原创】基于SSM的酒店预约管理系统(酒店管理系统毕业设计)
  • ​LeetCode解法汇总2583. 二叉树中的第 K 大层和
  • # 计算机视觉入门
  • (二)丶RabbitMQ的六大核心
  • (附源码)ssm户外用品商城 毕业设计 112346
  • (免费领源码)python#django#mysql公交线路查询系统85021- 计算机毕业设计项目选题推荐
  • (四)c52学习之旅-流水LED灯
  • (完整代码)R语言中利用SVM-RFE机器学习算法筛选关键因子
  • (中等) HDU 4370 0 or 1,建模+Dijkstra。
  • (转)es进行聚合操作时提示Fielddata is disabled on text fields by default
  • (转)Google的Objective-C编码规范
  • (转)Java socket中关闭IO流后,发生什么事?(以关闭输出流为例) .
  • (转)linux自定义开机启动服务和chkconfig使用方法
  • (转)scrum常见工具列表
  • (轉貼)《OOD启思录》:61条面向对象设计的经验原则 (OO)
  • .net CHARTING图表控件下载地址
  • .net mvc部分视图