Android源码解析-异步任务

android源码解析-异步消息

android异步消息中我们常用的就是如下方式

先创建一个handler实例:

private Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        //处理message返回结果
};

接着开启一个线程:

new Thread(new Runnable() {
        @Override
        public void run() {
        handler.sendEmptyMessage(2);
        }
    }).start();

我们执行了handler.sendEmptyMessage();方法,但是在主线程接到了返回结果,下面我们来探究一下原因.

原因探究

我们先看Handler.class的构造方法

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的实例和MessageQueue的引用对象.创建了Looper的实例也就找到了线程对应的looper和MessageQueue,因为一个MessageQueue对应的只有一个Looper.中间有一句mLooper = Looper.myLooper(); 我们稍后再看.
接下来看Handler调用的sendMessage方法。你会发现所有的方法调用的都是sendMessageAtTime()方法,那我们就看一下sendMessageAtTime()方法吧:

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

Handler的sendMessageAtTime()调用了queue.enqueueMessage()方法也就是messageQueue的入队方法。
我们看一下enqueueMessage:

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
}

我们看到handler把自己的实例放进了msg的target这个到后边会用到,接下来看MessageQueue类的enqueueMessage()方法:

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

里边的for循环就是把消息放到messagequeue里的方法,根据when时间顺序.
至此handler就把sendmessage中的message发送到messagequeue中.其中判断了之前我们定义到msg里的handler实例.
那么MessageQueue是在哪里维护的呢?
看上边的Handler构造方法我们发现mQueue = mLooper.mQueue;这个行代码.
也就是说MessageQueue是在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));
}

再看一下构造方法:

private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
}

实际上在子线程必须执行Looper.prepare()是因为需要通过sThreadLocal.set(new Looper(quitAllowed));建立Lopper与sThreadLocal的关系.我们再回看Handler的构造方法mLooper = Looper.myLooper(); 这个方法.

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

我们看到直接return了sThreadLocal.get() 这就说明了为什么要执行Looper.prepare(),因为需要先建立和sThreadLocal的关系.

接下来看 Looper.loop();方法是执行从enqueueMessage取出消息.


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()方法.如果有消息就继续执行.然后执行消息分发msg.target.dispatchMessage(msg);,可以看到msg.target就是我们最开始在enqueueMessage步骤把handler.如果没消息就休息等待.

下面看一下dispatchMessage:

public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
            handleCallback(msg);
            } else {
            if (mCallback != null) {
                    if (mCallback.handleMessage(msg)) {
                            return;
                            }
                    }
                handleMessage(msg);
            }
    }

最后分发完方法后执行了handleMessage回调方法.handleMessage方法我们再熟悉不过了.就是我们new Handler创建的回调.

总结

Handler通过初始化创建了Looper和实例化了MessageQueue,Looper创建的时候需要先执行Looper.propar(),通过handler构造方法匹配了本地ThreadLocal和线程-Looper-MessageQueue三者的对应关系.
handler通过sendMessage方法执行MessageQueue的enqueueMessage()方法,实现了往MessageQueue插入消息.
Looper.loop()方法从MessageQueue中取出消息.由for循环执行queue.next()方法,然后执行Handler的消息分发msg.target.dispatchMessage(msg);,也就是我们new Handler的回调方法.

一些题外话

android中启动关于线程和线程间通信的方法有很多,万变不离其宗,这里就简单的讲下:

1.关于Handler.post()
(1)Handler.post();,这个方法的常用场景是我们在子线程完成,子线程中,调用post()方法后可以再方法内写ui操作的东西,,切记不要在子线程实例化的Handler执行post()再操作UI,举个例子在其他子线程1实例化的Handler,在子线程2执行post()操作ui,那么还会报错告诉你"工作线程不能操作UI"的错误.
(2)这个方法的实现原理并不是新开启线程或者怎么样,原理还是异步消息,把Handler封装到Message里作为传递然后跨线程执行.具体请看源码,由于不太复杂们这里就不贴了.

2.关于HandlerThread

HandlerThread handlerThread = new HandlerThread("HandlerThread");
        handlerThread.start();
        Handler handler_thread = new Handler(handlerThread.getLooper(), new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                //线程内耗时操作
                return false;
            }
        });
        handler_thread.sendEmptyMessage();

源码解析
(1)当执行handlerThread.start();方法时候,执行了HandlerThreadrun()方法,里边执行了Looper.prepare();Looper.loop();,又是熟悉的配方.在这一步建立了Looper/MessageQueue/threadLocal之前的关系,并且执行了Looper.loop()方法,线程处于阻塞状态。当我们发送一个消息的时候就会被执行。

3.关于IntentService:
(1)继承自Service,它可以理解为就是一个Service,只不过融合了HandlerThread。
(2)继承IntentService创建自己的服务的时候会重写onHandleIntent()方法,因为这个方法就是在IntentService源码中Handler的handleMessage() 里实现的方法。
(3)源码在onCreate()中实现了HandlerThread并且执行了start方法,然后new了ServiceHandler对象。
(4)在onStart()中发送消息。
(5)在onStartCommand()中调用了onStart()方法。
(6)总结:这样整个过程就通了,onCreate()创建HandlerThread,每次启动服务都会调用onStartCommand()也就实现了发送消息。然后onHandleIntent()回调处理线程耗时操作。

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

推荐阅读更多精彩内容