答案是handler对象不会出问题,因为handler对象管理的Looper对象是线程安全的,不管是加入消息到消息队列和从队 列读出消息都是有同步对象保护的,具体请参考Looper.java文件。上例中没有修改handler对象,所以handler对象不可能会出现数据不 一致的问题。 通过上面的分析,我们可以得出如下结论: 1、如果通过工作线程刷新界面,...
Looper.prepareMainLooper(); if (sMainThreadHandler == null) { sMainThreadHandler = new Handler(); } ActivityThread thread = new ActivityThread(); thread.attach(false); // other codes... // 进入当前线程(此时是主线程)消息循环 Looper.loop(); // other codes... thread.detach(); // othe...
在主线程(UI线程)里,如果创建Handler时不传入Looper对象,那么将直接使用主线程(UI线程)的Looper对象(系统已经帮我们创建了);在其它线程里,如果创建Handler时不传入Looper对象,那么,这个Handler将不能接收处理消息。在这种情况下,通用的作法是: class LooperThread extends Thread { public Handler mHandler; public void...
如果不调用Looper.prepare()来创建消息队列,会报"java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()"的错误。 通过下图可以清晰显示出UI Thread, Worker Thread, Handler, Massage Queue, Looper之间的关系: 解释上图中的几个基本概念: 1.Message 消息对象,顾...
Handler 发送消息最终是调用Handler.enqueueMessage 代码语言:javascript 复制 privatebooleanenqueueMessage(@NonNull MessageQueue queue,@NonNull Message msg,long uptimeMillis){msg.target=this;msg.workSourceUid=ThreadLocalWorkSource.getUid();if(mAsynchronous){msg.setAsynchronous(true);}returnqueue.enqueueMessage(ms...
线程是默认没有Looper的,如果需要使用Handler则必须为线程创建Looper。(主线程ActivityThread创建时会初始化Looper,所以在主线程中默认可以使用Handler) ThreadLocal: Looper中还有一个ThreadLocal。ThreadLocal不是线程,它的作用是可以在每个线程中存储数据。 Handler创建的时候会采用当前线程的Looper来构造消息循环系统。
一、Looper 初始化 二、Looper 遍历消息队列 MessageQueue 三、完整 Looper 代码 一、Looper 初始化 Looper 是线程本地变量, 在每个线程中 , 可以通过线程调用ThreadLocal 变量的 get 方法获取该线程对应的对象副本 , 调用ThreadLocal 变量的 set 方法, 设置该线程对应类型的对象副本 ; ...
上面列出了 Handler 的一些成员变量:mLooper:线程的消息处理循环,注意:并非每一个线程都有消息处理循环,因此 Framework 中线程可以分为两种:有 Looper 的和无 Looper 的。为了方便 app 开发,Framework 提供了一个有 Looper 的 Thread 实现:HandlerThread。在前一篇《Thread的实现》中也提到了两种不同 Thread 的 run...
(R.id.tv_text); // 在UI线程中开启一个子线程 new Thread(new Runnable() { @Override public void run() { // 在子线程中初始化一个Looper对象 Looper.prepare(); handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { ...
handler.post(runnable); } }).start(); 二、源码分析 2.1、Handler 先从Handler构造函数开始 publicHandler(@NullableCallbackcallback,booleanasync){...mLooper=Looper.myLooper();if(mLooper==null){thrownewRuntimeException("Can't create handler inside thread "+Thread.currentThread()+" that has ...