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

结合源代码分析android的消息机制

描写叙述

结合几个问题去看源代码。

1.Handler, MessageQueue, Message, Looper, LocalThread这5者在android的消息传递过程中扮演了什么样的角色?
2.一个线程中能够有多个Handler吗?多个Looper呢?
3.整个消息处理过程。消息是怎么流动的?
4.为什么仅仅有UI线程能够更改UI?(就凭他叫UI线程?事实上也能够叫主线程或者ActivityThread)

開始看源代码

1.View的绘制都是从ViewRootImpl这个类開始,我们在这个类中找找。为什么异步线程不能更新UI。发现了这种方法

void checkThread() {
    if (mThread != Thread.currentThread()) {
        throw new CalledFromWrongThreadException(
                "Only the original thread that created a view hierarchy can touch its views.");
    }
}
当中mThread就是大名鼎鼎的UI线程,这段代码说明不是UI线程就直接抛异常,相当粗暴。

接着我们发现


@Override
public void requestFitSystemWindows() {
    checkThread();
    mApplyInsetsRequested = true;
    scheduleTraversals();
}

@Override
public void requestLayout() {
    if (!mHandlingLayoutInLayoutRequest) {
        checkThread();
        mLayoutRequested = true;
        scheduleTraversals();
    }
}
还有很多其它就不一一列举了。对UI的操作都调用了这个检查的方法,所以非UI线程不能更新UI。这样做有什么优点?大概有2点
a.防止耗时操作导致的ANR,严重影响体验
b.UI控件不是线程安全的,多线程訪问会出问题

2.接着看Handler,当我们new出一个Handler时。系统在干什么。

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;
}
这个构造器最直接。

首先须要一个Looper,哪里来的?在子线程中,我们通常要运行Looper.prepare()


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));
}
发现系统新建了一个Looper对象,而且存在了threadLocal中。当Looper创建的时候,同一时候创建了消息队列
private Looper(boolean quitAllowed) {
    mQueue = new MessageQueue(quitAllowed);
    mThread = Thread.currentThread();
}
当handler构造时。调用Looper.myLooper()方法,从threadLocal中取出新建的Looper对象。假设你没用调用Looper.myLooper(),运行下边代码就遇到那个熟悉的异常了。
if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }

在主线程中没用调用。为什么没有报错?由于ActivityThread帮你调了

Looper.prepareMainLooper();

ActivityThread thread = new ActivityThread();
thread.attach(false);

if (sMainThreadHandler == null) {
    sMainThreadHandler = thread.getHandler();
}

if (false) {
    Looper.myLooper().setMessageLogging(new
            LogPrinter(Log.DEBUG, "ActivityThread"));
}

// End of event ActivityThreadMain.
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
Looper.loop();
Looper.prepareMainLooper()和Looper.loop()都调了。

3.再看下Handler的post和send方法。Message怎么被Handler送进MessageQueue的。发现最后他们都进了这种方法

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
    msg.target = this;
    if (mAsynchronous) {
        msg.setAsynchronous(true);
    }
    return queue.enqueueMessage(msg, uptimeMillis);
}
通过enqueueMessage方法将消息体也就是Message对象压入MessageQueue中。

4,然后调用Looper.loop(),開始处理消息

/**
 * Run the message queue in this thread. Be sure to call
 * {@link #quit()} to end the 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
        Printer logging = me.mLogging;
        if (logging != null) {
            logging.println(">>>>> Dispatching to " + msg.target + " " +
                    msg.callback + ": " + msg.what);
        }

        msg.target.dispatchMessage(msg);

        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();
    }
}
一个死循环,然后不断通过queue.next()方法把Message从MessageQueue中取出来处理

5.将消息取出来后,通过调用msg.target.dispatchMessage(msg)来处理消息。msg.target指的是Handler对象,来详细看下:

/**
 * Handle system messages here.
 */
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}
这种方法说明当有Runnable对象(handler.post(new Runnable())设置)时,消息交给handleCallback()处理
private static void handleCallback(Message message) {
    message.callback.run();
}
直接调用了Runnable的run方法。这也解释了handler.post(new Runnable())时没有新建线程的问题。当有mCallBack(new Handler(new CallBack())时设置),调用callBack的方法handlerMessage()。都没有,则调用Handler的handlerMessage方法。

6.自此消息基本从 产生->增加队列->处理 过程基本走通了。

总结

1.非常多细节没讲到。主要是从源代码角度分析整个过程
2.handler能够在随意线程发送消息。这些消息会被加入到关联的MessageQueue上
3.消息终于会交给产生handler的线程处理。所以子线程能够持handler的引用更新UI
4.MessageQueue和Looper和当前线程相关
5.handler能够建多个,Looper仅仅能有一个
5.ThreadLocal是个存储类。从他保存新建的Looper对象能够看出,以后细说

遗留问题

1.handler的回调中明明打印的当前是子线程,为什么还是能够更新UI?
2.可是调用延时的方法后又不行了?

实验代码:
Log.e("---1---", String.valueOf(Thread.currentThread())
        + "\nThreadID:" + Thread.currentThread().getId());
new Thread(new Runnable() {
    @Override
    public void run() {
        try {
            Looper.prepare();
            Handler handler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    Log.e("---3---", String.valueOf(Thread.currentThread())
                    + "\nThreadID:" + Thread.currentThread().getId());
                    btn.setText("handlerMessage");
                }
            };
            Log.e("---2---", String.valueOf(Thread.currentThread())
                    + "\nThreadID:" + Thread.currentThread().getId());
            handler.sendEmptyMessage(0);
                      handler.sendEmptyMessageDelayed(0, 2000);
            handler.post(new Runnable() {
                @Override
                public void run() {
                    Log.e("---4---", String.valueOf(Thread.currentThread())
                            + "\nThreadID:" + Thread.currentThread().getId());
                    btn.setBackgroundColor(Color.YELLOW);
                }
            });
            Looper.loop();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}).start();
结果:
01-07 14:55:40.688 21362-21362/com.empty.animationtest E/---1---: Thread[main,5,main]
ThreadID:1
01-07 14:55:40.698 21362-21394/com.empty.animationtest E/---2---: Thread[Thread-37592,5,main]
                                                                 ThreadID:37592
01-07 14:55:40.698 21362-21394/com.empty.animationtest E/---3---: Thread[Thread-37592,5,main]
                                                                 ThreadID:37592
01-07 14:55:40.698 21362-21394/com.empty.animationtest E/---4---: Thread[Thread-37592,5,main]
                                                                 ThreadID:37592
01-07 14:55:42.698 21362-21394/com.empty.animationtest E/---3---: Thread[Thread-37592,5,main]
                                                                 ThreadID:37592
01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err: 01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err:     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6294)
01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err:     at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:878)
01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err:     at android.view.ViewGroup.invalidateChild(ViewGroup.java:4344)
01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err:     at android.view.View.invalidate(View.java:10957)
01-07 14:55:42.698 21362-21394/com.empty.animationtest W/System.err:     at android.view.View.invalidate(View.java:10912) 

结果分析:
运行到3,4确实是子线程,也完毕了UI的更新。

而延时的第二个3,不能成功更新UI,为什么?










相关文章:

  • mongodb入门安装
  • 【mysql】环境安装、服务启动、密码设置
  • 用 volume container 共享数据 - 每天5分钟玩转 Docker 容器技术(42)
  • uva 10806 Dijkstra, Dijkstra. (最小费最大流)
  • rsync 同步mac机器目录数据到windows2008R2
  • 全景展现智慧银川成就
  • oracle数据库未打开解决的方法
  • 【Unity笔记】物体的Transform操作:速度、旋转、平移
  • Linux rz sz
  • 【162天】黑马程序员27天视频学习笔记【Day02-上】
  • 分享一些PHP开发者实用工具(上)
  • 从TensorFlow到PyTorch:九大深度学习框架哪款最适合你?
  • jmeter添加自定义扩展函数之图片base64编码
  • Vue 2.3、2.4 知识点小结
  • 颜色模式
  • .pyc 想到的一些问题
  • [NodeJS] 关于Buffer
  • 【翻译】Mashape是如何管理15000个API和微服务的(三)
  • 【跃迁之路】【519天】程序员高效学习方法论探索系列(实验阶段276-2018.07.09)...
  • 【跃迁之路】【585天】程序员高效学习方法论探索系列(实验阶段342-2018.09.13)...
  • 30天自制操作系统-2
  • CentOS 7 防火墙操作
  • Docker 笔记(1):介绍、镜像、容器及其基本操作
  • HTML5新特性总结
  • jquery cookie
  • k8s 面向应用开发者的基础命令
  • maven工程打包jar以及java jar命令的classpath使用
  • MaxCompute访问TableStore(OTS) 数据
  • Python学习笔记 字符串拼接
  • React 快速上手 - 07 前端路由 react-router
  • Solarized Scheme
  • Xmanager 远程桌面 CentOS 7
  • 不发不行!Netty集成文字图片聊天室外加TCP/IP软硬件通信
  • 大整数乘法-表格法
  • 技术发展面试
  • 如何正确配置 Ubuntu 14.04 服务器?
  • PostgreSQL之连接数修改
  • ​iOS实时查看App运行日志
  • ​猴子吃桃问题:每天都吃了前一天剩下的一半多一个。
  • #if和#ifdef区别
  • #我与Java虚拟机的故事#连载15:完整阅读的第一本技术书籍
  • %3cscript放入php,跟bWAPP学WEB安全(PHP代码)--XSS跨站脚本攻击
  • (1)安装hadoop之虚拟机准备(配置IP与主机名)
  • (转)【Hibernate总结系列】使用举例
  • **python多态
  • *p++,*(p++),*++p,(*p)++区别?
  • .jks文件(JAVA KeyStore)
  • .NET 6 Mysql Canal (CDC 增量同步,捕获变更数据) 案例版
  • .net 后台导出excel ,word
  • .NET企业级应用架构设计系列之开场白
  • @ModelAttribute 注解
  • [ C++ ] 继承
  • [2013][note]通过石墨烯调谐用于开关、传感的动态可重构Fano超——
  • [c]统计数字
  • [CF543A]/[CF544C]Writing Code