预览加载中,请您耐心等待几秒...
1/9
2/9
3/9
4/9
5/9
6/9
7/9
8/9
9/9

在线预览结束,喜欢就下载吧,查找使用更方便

如果您无法下载资料,请参考说明:

1、部分资料下载需要金币,请确保您的账户上有足够的金币

2、已购买过的文档,再次下载不重复扣费

3、资料包下载后请先用软件解压,在使用对应软件打开

HandlerLooper与MessageQueue源码分析 在Android中可以通过Handler来更新主线程中UI的变化,更新UI只能在主线程中进行更新,而为了让其他线程也能控制UI的变化,Android提供了一种机制Handler、Looper与MessageQueue一同协作来达到其他线程更新UI的目的。 作者:idisfkj来源:HYPERLINK"https://segmentfault.com/a/1190000007216273"\t"_blank"segmentfault|2016-10-2113:03 HYPERLINK"javascript:favorBox('open');"\o"一键收藏,随时查看,分享好友!"\t"_self"收藏 HYPERLINK"javascript:;"分享 在Android中可以通过Handler来更新主线程中UI的变化,更新UI只能在主线程中进行更新,而为了让其他线程也能控制UI的变化,Android提供了一种机制Handler、Looper与MessageQueue一同协作来达到其他线程更新UI的目的。 一般我们会在主线程中通过如下方法定义一个Handler privateHandlermHandler=newHandler(){ @Override publicvoidhandleMessage(Messagemsg){ tv.setText("mHandlerchangeUI"); super.handleMessage(msg); } }; 一般都见不到Looper与MessageQueue的,那么它们都是在哪里调用与如何协作的呢?在主线程不会显式的调用Looper而是会在ActivityThread.main方法中默认调用。 publicstaticvoidmain(String[]args){ Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,"ActivityThreadMain"); SamplingProfilerIntegration.start(); //CloseGuarddefaultstotrueandcanbequitespammy.We //disableithere,butselectivelyenableitlater(via //StrictMode)ondebugbuilds,butusingDropBox,notlogs. CloseGuard.setEnabled(false); Environment.initForCurrentUser(); //Setthereporterforeventlogginginlibcore EventLogger.setReporter(newEventLoggingReporter()); //MakesureTrustedCertificateStorelooksintherightplaceforCAcertificates finalFileconfigDir=Environment.getUserConfigDirectory(UserHandle.myUserId()); TrustedCertificateStore.setDefaultUserDirectory(configDir); Process.setArgV0("<pre-initialized>"); Looper.prepareMainLooper();//创建Looper ActivityThreadthread=newActivityThread(); thread.attach(false); if(sMainThreadHandler==null){ sMainThreadHandler=thread.getHandler(); } if(false){ Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG,"ActivityThread")); } //EndofeventActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop();//开启Looper循环 thrownewRuntimeException("Mainthreadloopunexpectedlyexited"); } 如上代码,调用了Looper.prepareMainLooper()方法,在主线程中创建了一个Looper,不信的话我们再查看该方法做了什么 Looper pr