举个栗子来分析handler原理

看了网上的一些handler原理分析,是从源码级别直接看的。但是总觉得没有从实战上分析吗,感觉有点蹩脚。这篇文章算是自己分析的,也参考了《android开发艺术探索》,还有网上的一些其他资料,如有侵权请私信

先来举个栗子吧

一般在使用handler的时候,用其来更新UI,也就是说在主线程进行更新界面操作,当时子线程请求网络数据,如此handler刚好派上用场。先看实例吧

public class MainActivity extends Activity {
 
    private TextView text;
    private Handler handler = new Handler() {
 
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    text.setText("使用Handler更新了界面");
                    break;
            }
        }
    };
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.id_text);
 
        new Thread("#Thread1") {
 
            @Override
            public void run() {
                //...你的业务逻辑;
                Message message = new Message();//发送一个消息,该消息用于在handleMessage中区分是谁发过来的消息;
                message.what = 1;
                handler.sendMessage(message);
            }
        }.start();
    }
}

以上的例子呢,应该算是handler使用的最普遍的,当然还有其它用法,handler创建在主线程中,也就是Activitythread,在"#Thread1"中执行耗时操作,在主线程中更新UI,创建handler。
在创建handler之前需要注意:
在创建handler之前,必须先在相同线程内创建一个Looper,每个线程中最多只能有一个 Looper 对象,由 Looper 来管理此线程里的 MessageQueue (消息队列)。



如果不在主线程创建handler的话,应该这么写代码:

new Thread("Thread#2"){
@override
  public void run(){
    Looper.prepare();
    Handler handler = new Handler();
    Looper.loop();
  }
}

首先利用Looper.prepare()创建looper,然后创建handler,然后调用Looper.loop()开启消息循环。这是在非UI线程,但是我们在之前的handler使用例子中并未简单looper的创建啊,其实looper 已经在activityThread当中给你创建完了。可以来看看源码

public static void main(String[] args) {
        、、、、、此处省略部分代码
        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

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

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

        AsyncTask.init();

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

        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

可以看出activitythread执行了两个looper方法

 Looper.prepareMainLooper();
 Looper.loop();

所以我们只需要创建handler就可以了。那我们接着看我们文章开头那个实例,重写了handler的handlemessage方法,然后新建线程,利用handler发送消息。然后主线程的handler就会接收到消息,并在handlemessage中处理消息。上面整体思路没问题吧,这也是最初在使用handler的时候,大家的通常思维,那handler到底是怎么切换线程的,从thread1切换到了主线程???
先上一张整体的流程图

handler消息机制.png

这张图是我自己画的,可能画的不太好,也看了一些大佬的流程图,毕竟我基础差,总觉得他们的图理解起来不是很容易。


MessaggeQueue类详解

根据我们的操作先来看啊,主线程已经准备就绪,handler创建完了,然后调用sendmessage方法,最后调用的事enqueuemessage()方法,然后就到了messgaeQueue类,这个类又是从哪来的呢????这个类其实是从Looper里面蹦出来的,在创建Looper的时候,就会生成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));
    }

    /**
     * Initialize the current thread as a looper, marking it as an
     * application's main looper. The main looper for your application
     * is created by the Android environment, so you should never need
     * to call this function yourself.  See also: {@link #prepare()}
     */
    public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

我们知道在主线程的main函数中,已经调用了prepareMainLooper()方法,而后prepareMainLooper()方法又调用了 prepare()方法,在这个方法里面,我们调用looper的构造函数,并将新建的looper存入到了ThreadLocal里面(ThreadLocal后边讲),然后我们来看这个looper的构造函数

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

可以清晰的看到Looper在构造函数中创建了MessageQueue,知道了MessageQueue的由来,我们简单来说一下MessageQueue这个类啊
enqueueMessage():这个是通过维护一个单链表,handler添加消息以后,MessageQueue会将消息添加到最后。
next():用于取出消息,并将消息传递给Looper 。注意这个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 (false) Log.v("MessageQueue", "Returning message: " + msg);
                        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("MessageQueue", "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;
        }
    }

Looper类详解

我们这时候来看看looper,looper是在主线程的,刚刚说过了,looper在handler创建之前就已经创建完成了,顺带把MessageQueue和looper.loop()方法都执行了。这时候我们来看看这个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();
        }
    }

和上面next方法一样,这块也是个死循环,一直在等待messagequeue的消息。等它拿到消息以后,就会调用msg.target.dispatchMessage(msg);这行代码,这行代码其实就是调用了handler的dispatchMessage方法,后边经过一些列的判断会调用handler的handleMessage()方法。这是整体过程。

总结

下面从别的文章上抄来的图,简单粗暴。很明显就能看出如何切换线程的,首先主线程就相当于A线程,B线程就相当于#Thread1
POST就相当于在thread1里面使用handler发送消息,然后把消息放在messageQueue当中,主线程里面的Looper就回调用loop方法,一直从messagequeue类的next方法中获取消息,然后再次调用handler消化这个消息。

image.png


引用的技术文章
https://blog.csdn.net/AdobeSolo/article/details/75195394
https://mp.weixin.qq.com/s/D1v7b5CUT-3JMhxR6iCpcA
https://blog.csdn.net/CHENYUFENG1991/article/details/46910675
《android开发艺术探索》

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

推荐阅读更多精彩内容