揭秘最新android studio instant run(一
问题引出
android studio 3.0之后的instant run和2.0有了一些变化,其中一个变化便是2.0的时候需要生成一个BootStrapApplication,在其中执行一些classloader的初始化和委托工作等等(具体我就不展开了,这篇文章写的不错深入理解Android Instant Run运行机制),但是3.0之后去掉了, 多了一个InstantRunContentProvider,源码里面是这样说的
/**
* Content Provider that abuses a quirk of early Android initialization to start the instant run
* service very early, before Application.onCreate(): content providers get initialized before
* Application.onCreate() is called.
*
* ActivityThread initializes the application by creating and binding the Application object,
* which we don't want to replace right now, creating content providers, and _then_ calling
* Application.onCreate(), so by starting the IR server in the ContentProvider, we initialize
* early without risking the ANR we'd get by doing an explicit service start.
*
* A ContentProvider also simplifies the client code, which doesn't have to do anything special
* (like am startservice) in order to cause the instant run server to start on
* application startup.
*/
大意就是既然ContentProvider的初始化是先于Application.onCreate(),那我就在content providers 的oncreate里面做一些事情好了,于是我们可以看到

此处执行了server的create函数。好了,我们的开篇就到这里,第一个问题就是:ContentProvider的初始化真的先于Application 么?
接下来我们就从源码和实践两个方面验证一下,
一、首先看下源码
对于Activity的启动流程,很多文章也讲过,这里也不再赘述,以找到我们问题的答案为主,一切从ActivityThread的main函数入手:
1.<ActivityThread> attach

2.<ActivityThread> attachApplication

3.<ActivityManagerService> attachApplication

你是不是想问ActivityManagerService和IActivityManager的关系?这里先不说,大家看文末的源码,查看下ActivityManagerService的继承关系就明白了
4.<ActivityManagerService> attachApplicationLocked

这个函数比较长,我截个开头,然后截一段后面的关键

5.<ActivityThread> bindApplication

这个函数比较长,我截个开头,然后截一段后面的关键

此处发了个消息交给handler处理了, 继续截图

6.<ActivityThread> handleBindApplication

********************************我是分割线***********************************************************
第六点这里就是本文的关键了,此处表明ContentProvider的onCreate确实是先于Application的的onCreate执行的。
当然你说我没看到onCreate啊,别急下面的截图为你诠释,展开installContentProviders和callApplicationOnCreate最终会看到oncreate的
********************************我是分割线***********************************************************
7.<ActivityThread> installContentProviders installProvider

installProvider

attachInfo

8.<Instrumentation> callApplicationOnCreate

二、实践验证
首先我们再看一遍InstantRunContentProvider的onCreate方法

好了,既然谷歌大神已经在这里打了日志了,真是天助我也,验证就变得异常简单了,我们只需要新建一个工程,开启instant run,然后新建一个Application,在其中的onCreate方法中打个日志,看下二者的时间先后即可,我的Application里面的代码如下,

验证结果如下:

验证的结果也表明确实ContentProvider的初始化真的先于Application,好了,揭秘最新android studio instant run(一)就到这里了,喜欢的朋友帮忙点赞哦