Android Handler原理

  1. Handler的使用:
    (1)子线程和主线程之间相互发送消息
    (2)执行延时任务

  2. 基本使用:

Looper.prepare();
Handler mHandler = new Handler() {  
    @Override public void handleMessage(@NonNull Message msg) {  
        super.handleMessage(msg);  
    }  
};  
mHandler.sendEmptyMessage(0);
Looper.loop();
  1. 原理概述:

Looper.prepare()会创建一个Looper对象,这个Looper对象是每个线程独有的,通过ThreadLocal保存。创建Looper对象时,会创建一个MessageQueue对象用于存放消息。Handler发送的消息Message会保存在这个MessageQueue中。

创建Handler对象时,会跟Looper对象相关联,默认的是跟本线程中Looper对象关联,也可以传入其他线程中的Looper对象。

Looper.loop()会开启一个死循环用于接收Handler发送过来的消息,然后执行相应的回调函数,一般是执行Handler的handleMessage方法。

  1. 原理详解
    Looper.prepare(), 通过ThreadLocal保存新的Looper对象。
83    public static void prepare() {  
84        prepare(true);  
85    }  
86  
87    private static void prepare(boolean quitAllowed) {  
88        if (sThreadLocal.get() != null) {  
89            throw new RuntimeException("Only one Looper may be created per thread");  
90        }  
91        sThreadLocal.set(new Looper(quitAllowed));  
92    } 

Looper的构造函数:创建MessageQueue对象,用于保存Handler发送的Message对象

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

Handler的构造函数,Handler有多个构造函数,主要用来初始化mLooper、mQueue、mCallBack、mAsynchronous对象。如果未传入参数,则使用当前线程的默认值。

227    public Handler(Looper looper, Callback callback, boolean async) {  
228        mLooper = looper;  
229        mQueue = looper.mQueue;  
230        mCallback = callback;  
231        mAsynchronous = async;  
232    }  

 
188    public Handler(Callback callback, boolean async) {  
189        if (FIND_POTENTIAL_LEAKS) {  
190            final Class<? extends Handler> klass = getClass();  
191            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&  
192                    (klass.getModifiers() & Modifier.STATIC) == 0) {  
193                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +  
194                    klass.getCanonicalName());  
195            }  
196        }  
197  
198        mLooper = Looper.myLooper();  
199        if (mLooper == null) {  
200            throw new RuntimeException(  
201                "Can't create handler inside thread that has not called Looper.prepare()");  
202        }  
203        mQueue = mLooper.mQueue;  
204        mCallback = callback;  
205        mAsynchronous = async;  
206    }  


113    public Handler() {  
114        this(null, false);  
115    }  
116  
  
127    public Handler(Callback callback) {  
128        this(callback, false);  
129    }  
130  
  
136    public Handler(Looper looper) {  
137        this(looper, null, false);  
138    }  
139  
  
147    public Handler(Looper looper, Callback callback) {  
148        this(looper, callback, false);  
149    }  
150  
  
167    public Handler(boolean async) {  
168        this(null, async);  
169    }

Handler发送消息:Handler通过一系列发送消息的方法将消息发送给Looper中的MessageQueue中

Handler的众多发送消息的方法最终都会走到同一个函数enqueueMessage:

638    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {  
639        msg.target = this;  //将msg.target赋值给了当前Handler对象
640        if (mAsynchronous) {  
641            msg.setAsynchronous(true);  
642        }  
643        return queue.enqueueMessage(msg, uptimeMillis);  
644    }  

这里可以看到将当前的msg对象加入了消息队列中国。并且将msg.target赋值给了当前Handler对象。

Looper.loop()方法:开启处理消息的无限循环

123    public static void loop() {  
124        final Looper me = myLooper();  //返回当前线程的Looper对象,保存在ThreadLocal中
125        if (me == null) {  
126            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");  
127        }  
128        final MessageQueue queue = me.mQueue;  // 拿到MessageQueue对象
129  
130        // Make sure the identity of this thread is that of the local process,  
131        // and keep track of what that identity token actually is.  
132        Binder.clearCallingIdentity();  
133        final long ident = Binder.clearCallingIdentity();  
134  
135        for (;;) {  //处理Handler发送消息的无线循环
136            Message msg = queue.next(); // might block  
137            if (msg == null) {  
138                // No message indicates that the message queue is quitting.  
139                return;  
140            }  
141  
142            // This must be in a local variable, in case a UI event sets the logger  
143            final Printer logging = me.mLogging;  
144            if (logging != null) {  
145                logging.println(">>>>> Dispatching to " + msg.target + " " +  
146                        msg.callback + ": " + msg.what);  
147            }  
148  
149            final long traceTag = me.mTraceTag;  
150            if (traceTag != 0) {  
151                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));  
152            }  
153            try {  
154                msg.target.dispatchMessage(msg);  //这里的msg.target就是Handler
155            } finally {  
156                if (traceTag != 0) {  
157                    Trace.traceEnd(traceTag);  
158                }  
159            }  
160  
161            if (logging != null) {  
162                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);  
163            }  
164  
165            // Make sure that during the course of dispatching the  
166            // identity of the thread wasn't corrupted.  
167            final long newIdent = Binder.clearCallingIdentity();  
168            if (ident != newIdent) {  
169                Log.wtf(TAG, "Thread identity changed from 0x"  
170                        + Long.toHexString(ident) + " to 0x"  
171                        + Long.toHexString(newIdent) + " while dispatching to "  
172                        + msg.target.getClass().getName() + " "  
173                        + msg.callback + " what=" + msg.what);  
174            }  
175  
176            msg.recycleUnchecked();  
177        }  
178    }  

Handler的dispatchMessage函数:

93    public void dispatchMessage(Message msg) {  
94        if (msg.callback != null) {  
95            handleCallback(msg);  
96        } else {  
97            if (mCallback != null) {  
98                if (mCallback.handleMessage(msg)) {  
99                    return;  
100                }  
101            }  
102            handleMessage(msg);  
103        }  
104    }  

如果有对应的callback对象,则执行相应的回调,否则执行Handler的handleMessage。

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