Handler源码分析

Handler 已经被无数人分析过了 为什么这里还要写篇博文分析呢,因为那是别人的,自己分析的才是你自己的

handler作用:(下面这段话摘自谷歌文档)

There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own. 大概翻译一下: Handler有2个主要的作用:
(1)安排消息或Runnable在某个主线程中某个地方执行
(2)安排一个动作在不同的线程中执行

handler写法

子线程更新UI数据,需要使用如下代码发送消息给主线程处理:

//子线程中发送消息操作
Message message = handler.obtainMessage();
message.obj = "子线程更新的内容!";
handler.sendMessage(message);
最后会在主线程的Handler对象中执行handleMessage()方法:

Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Object msgStr = msg.obj;
if (msgStr != null) {
tv_content.setText((String) msgStr);
}
}
};

源码分析

为什么调用Handler就能在主线程更新UI呢?既然是源码分析就一步步的点进去看 首先看这一行代码做了什么

Message message = handler.obtainMessage();

调用了Message的obtain()方法

public static Message obtain(Handler h) {
//调用了Message类中的静态方法obtain();
Message m = obtain();
//把上面传递进来的handler对象赋值给了m对象中的target成员变量
m.target = h;
//返回了Message m对象
return m;
}

继续看obtain()方法:

public static Message obtain() {
//同步代码块中的内容先跳过,第一次发送消息时sPool为null
synchronized (sPoolSync) {
if (sPool != null) {
Message m = sPool;
sPool = m.next;
m.next = null;
m.flags = 0; // clear in-use flag
sPoolSize--;
return m;
}
}
//返回了一个Message对象
return new Message();

总结:Message message = handler.obtainMessage();调用该方法时最后返回了一个new出来的Message()对象。

接着看handler.sendMessage(message);

public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
最终会调用

public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
}

继续往下看enqueueMessage(queue, msg, uptimeMillis);

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的意义是当在死亡线程中发送message时就会失败
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;//将MessageQueue中的mMessage对象赋值给一个新变量p
    boolean needWake;
 //第一次进入的时候,mMessage是为null的,也就是说说p是null
    if (p == null || when == 0 || when < p.when) {
        // New head, wake up the event queue if blocked.
        msg.next = p;//把p赋值给了当前msg的下一个节点,看到这里就知道这里使用了链表
        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构造方法

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());
}
}

//从ThreadLocal取出与handler绑定的Looper
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
//赋值Looper的MessageQueue给Handler
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

依旧没有看到handleMessage这个方法的调用,研究了半天,原来在ActivityThread这个类中, Android应用启动的入口都是从ActivityThread这个类的main()方法开始的

public static final void main(String[] args) {
SamplingProfilerIntegration.start();

    Process.setArgV0("");

//看到了Looper 划重点
Looper.prepareMainLooper();
if (sMainThreadHandler == null) {
sMainThreadHandler = new Handler();
}

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

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

//看到了Looper 划重点
Looper.loop();

    if (Process.supportsProcesses()) {
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

    thread.detach();
    String name = (thread.mInitialApplication != null)
        ? thread.mInitialApplication.getPackageName()
        : "";
    Slog.i(TAG, "Main thread of " + name + " is now exiting");
}

先分析下Looper.prepareMainLooper();

public static void prepareMainLooper() {
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
sMainLooper = myLooper();
}
}

调用了prepare(false);以及 sMainLooper = myLooper();先看prepare()方法

private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
//使用ThreadLocal存储了一个新创建的Looper,而且该looper对象不允许退出
sThreadLocal.set(new Looper(quitAllowed));
}

Looper构造函数
private Looper(boolean quitAllowed) {
//创建一个MessageQueue对象并赋值给了自己的成员变量mQueue
mQueue = new MessageQueue(quitAllowed);
//把当前线程赋值给了成员变量mThread
mThread = Thread.currentThread();
}
再看看myLooper()

只是把刚刚存到ThreadLocal的Looper对象取了出来而已!

public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
到此,Looper.prepareMainLooper();方法已经全部执行完毕了!总结一下看他做了什么: 1.使用ThreadLocal存储了一个新创建的Looper,而且该looper对象不允许退出 2.创建一个MessageQueue对象并赋值给了自己的成员变量mQueue,把当前线程赋值给了成员变量mThread 3.取出Looper

还有Looper.loop();方法

public static void loop() {
//执行该方法就是获取了上面创建的Looper对象
final Looper me = myLooper();
//只要执行了上面的prepare方法,这里就不会取出null
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
//拿到了上面创建的MessageQueue对象
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);
    }

  
        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        try {

//在这里 msg消息对应的target调用了dispatchMessage(msg)方法!刚才我们看到的target就是对应的handler对象,也就是说调用了每条消息对应的handler对象的dispatchMessage(msg)方法
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}

    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();
}

}

注意,当线程loop起来是时,线程就一直在循环中。就是说Looper.loop()后面的代码就不能被执行了。想要执行,需要先退出loop,这也就是为什么Looper.loop();放在最后后面的原因

接下来就要看msg.target.dispatchMessage(msg);

public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
可以看出这里进行消息的处理

总结一下(采用面试问答形式)

问题一:Handler原理

1.最初在ActivityThread中,系统调用了一下Looper.prepareMainLooper();和Looper.loop()方法,所以在主线程中默认就会有一个Looper对象和与其绑定的MessageQueue对象。

2.通过obtain()获取Message对象(先从Message对象池中拿没有就new一个),并把Handler赋值给msg.target

3.sendToTarget()最终调用queue.enqueueMessage将消息插如MessageQueue中

4.Handler的构造方法,会首先得到当前线程中保存的Looper实例,进而与Looper实例中的MessageQueue相关联。

5、Looper.prepare()会在本线程中保存一个Looper对象,然后该对象中保存一个MessageQueue对象;因为Looper.prepare()在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。

6、Looper.loop()会让当前线程进入一个无限循环,不断从MessageQueue的实例中读取消息,然后回调msg.target.dispatchMessage(msg)方法。

问题二:一个线程中有几个Looper几个Handler

一个线程只有一个Looper可以有多个Handler

问题三;什么时候会进入阻塞状态

1.消息队列中有消息,但是消息指定了执行的时间,而现在还没有到这个时间,线程会进入等待状态。 2.当消息队列中没有消息时,它会使线程进入等待状态;

问题四:MessageQueue是什么时候创建的

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));
}
private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}

在线程主动调用Looper.prepare可以为当前线程主动创建一个Looper对象(主线程会自动生成一个Looper对象),MessageQueue在LOOper构造函数中创建

问题五:Handler是否会引发内存泄露

当Activity退出时消息队列中还有未处理的消息或者正在处理的消息 而消息队列中的Messager持有handler实例的引用(当使用内部类(包括匿名类)来创建Handler的时候,Handler对象会隐式地持有一个外部类对象(通常是一个Activity)的引用), 所以导致Activity的内存资源无法及时回收,引发内存泄露)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容