一、创建Application
-
首先
ActivityThread
main()
方法public static void main(String[] args){ ... //初始化Looper Looper.prepareMainLooper(); ... //实例化一个ActivityThread ActivityThread thread = new ActivityThread(); //这个方法最后就是为了发送出创建Application的消息 thread.attach(false); ... Looper.loop(); //主线程进入无限循环状态,等待接收消息 }
-
ActivityThread
对象thread.attach(false)
public void attach(boolean system){ ... //获得IActivityManager实例,他是一个ActivityManagerProxy的示例 final IActivityManager mgr = ActivityManagerNative.getDefault(); try { //这里是关键。mAppThread是一个ApplicationThread实例,具体的在下面说 mgr.attachApplication(mAppThread); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } ... }
-
mgr.attachApplication(mAppThread)
public void attachApplication(IApplicationThread app) throws RemoteException{ Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); data.writeInterfaceToken(IActivityManager.descriptor); //把IApplicationThread 的对象app写到了data里, //app就是mAppThread,mAppThread是什么看后面分析 data.writeStrongBinder(app.asBinder()); //重点在这里,用mRemote把dare传输出去 mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0); reply.readException(); data.recycle(); reply.recycle(); }
-
mRemote
是什么?看
ActivityManagerProxy
的构造方法,注意上面的mgr是一个ActivityManagerProxy
的对象public ActivityManagerProxy(IBinder remote){ mRemote = remote; }
而
ActivityManagerProxy
对象的创建是在ActivityManagerNative
的静态方法asInterface
里调用的static public IActivityManager asInterface(IBinder obj) { if (obj == null) { return null; } ... //这里 return new ActivityManagerProxy(obj); }
obj
即ActivityManagerProxy
的mRemote
对象又是方法外传入的,我们继续看调用private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() { protected IActivityManager create() { //mRemote对象就是下面的IBinder b,它是一个ActivityManagerService的实例 IBinder b = ServiceManager.getService("activity"); ... IActivityManager am = asInterface(b); //调用了上面的方法。 ... return am; } };
也就是说
mRemote
是一个ActivityManagerService
的实例对象, -
ActivityManagerService
的 对transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0)
的处理我们 在 3 [回到“3”] 调用了
mRemote.transact(ATTACH_APPLICATION_TRANSACTION, data, reply, 0)
方法,而mRemote
是一个ActivityManagerService
的实例对象ActivityManagerService
继承ActivityManagerNative
对象,而ActivityManagerNative
对象继承Binder
,而Binder
的transact方法的处理就是调用它的onTransact
方法public final boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { ... boolean r = onTransact(code, data, reply, flags); ... return r; }
也就是说它会调用
mRemote
的onTransact
方法,而在
ActivityManagerService
的onTransact
方法里public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { if (code == SYSPROPS_TRANSACTION){...} try { return super.onTransact(code, data, reply, flags); } catch (RuntimeException e) { ... } }
没有对
ATTACH_APPLICATION_TRANSACTION
进行处理,而是交给了他的父类ActivityManagerNative
进行处理ActivityManagerNative
的onTransact
方法@Override public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { switch (code){ case ATTACH_APPLICATION_TRANSACTION: { data.enforceInterface(IActivityManager.descriptor); //从data里取出app,也就是2 里的mAppThread IApplicationThread app = ApplicationThreadNative.asInterface( data.readStrongBinder()); if (app != null) { //看这里,转到attachApplication去处理了 attachApplication(app); } reply.writeNoException(); return true; } }
attachApplication(app)
方法public final void attachApplication(IApplicationThread thread) { int callingPid = Binder.getCallingPid(); ... attachApplicationLocked(thread, callingPid); ... }
继续跳转到
attachApplicationLocked
方法private final boolean attachApplicationLocked(IApplicationThread thread , int pid) { ... thread.bindApplication(); ... }
经过一系列的操作后调用了
thread.bindApplication()
发出初始化Applicationd
的消息 -
视野回到2:
mgr.attachApplication(mAppThread)
这里的mAppThread
到底是个啥?mAppThread
是ActivityThread
的变量final ApplicationThread mAppThread = new ApplicationThread();
而
ApplicationThread
类private class ApplicationThread extends ApplicationThreadNative{ ... }
是一个
ActivityThread
中的一个内部类,它继承自ApplicationThreadNative
public abstract class ApplicationThreadNative extends Binder implements IApplicationThread{ ... //无参构造函数 public ApplicationThreadNative() { //这是Binder的 attachInterface(this, descriptor); } ... }
那么很明显,
ApplicationThread
最终也是一个Binder
!由于实现了IApplicationThread
接口,所以它也是一个IApplicationThread
,这就跟 5 [回到“5”]里面的最终调用对应起来了下面是
Binder
的attachInterface()
方法,单纯的进行了赋值public void attachInterface(IInterface owner, String descriptor) { mOwner = owner; mDescriptor = descriptor; }
-
ApplicationThread
的bindApplication
方法public final void bindApplication(String processName, ApplicationInfo appInfo, List<ProviderInfo> providers, ComponentName instrumentationName, ProfilerInfo profilerInfo, Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher, IUiAutomationConnection instrumentationUiConnection, int debugMode, boolean enableBinderTracking, boolean trackAllocation, boolean isRestrictedBackupMode, boolean persistent, Configuration config, CompatibilityInfo compatInfo, Map<String, IBinder> services, Bundle coreSettings){ ... sendMessage(H.BIND_APPLICATION, data); }
他最终发送了一个
H.BIND_APPLICATION
消息,而这个消息被handler
分发,最终由handleBindApplication
方法处理private void handleBindApplication(AppBindData data) { ... mInstrumentation = (Instrumentation) cl.loadClass(data.instrumentationName.getClassName()) .newInstance(); //通过反射初始化一个Instrumentation仪表。 ... Application app = data.info.makeApplication(data.restrictedBackupMode, null); //通过LoadedApp命令创建Application实例 mInitialApplication = app; ... mInstrumentation.callApplicationOnCreate(app); //让仪器调用Application的onCreate()方法 ... }
可以看到他在里面创建了
Application
对象。然后是
mInstrumentation.callApplicationOnCreate
方法public void callApplicationOnCreate(Application app) { app.(); }
此时
Application
进入了我们熟悉的onCreate
生命周期 -
makeApplication
怎么创建了对象首先要知道
data.info
为LoadedApk
类型的对象,我们去这个类看makeApplication
方法public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) { ... String appClass = mApplicationInfo.className; //获取Application的类名。明显是要用反射了。 ... ContextImpl appContext = ContextImpl.createAppContext(mActivityThread , this); //留意下Context app = mActivityThread.mInstrumentation .newApplication( cl, appClass, appContext); //通过仪表创建Application ... }
方法里获取了
Application
的类名,然后交给了Instrumentation
去创建对象Instrumentation
的newApplication
方法static public Application newApplication(Class<?> clazz , Context context) throws InstantiationException , IllegalAccessException , ClassNotFoundException { Application app = (Application)clazz.newInstance(); //反射创建,简单粗暴 app.attach(context); //关注下这里,Application被创建后第一个调用的方法。 //目的是为了绑定Context。 return app; }
Instrumentation
直接用反射创建了Application
对象,然后调用了app.attach(context)
方法绑定Context
。Application
的attach
final void attach(Context context) { //注意这个方法是一个可以比onCreate更早被调用的方法 attachBaseContext(context); mLoadedApk = ContextImpl.getImpl(context).mPackageInf; }
二、创建Activity
-
再次回到
ActivityManagerService
的attachApplication
方法(在“5”处),这次我们多看一点代码private final boolean attachApplicationLocked(IApplicationThread thread, int pid) { ...... try { ...... //1.发送启动Application thread.bindApplication(...); ...... } catch (Exception e) { ...... return false; } ...... if (normalMode) { try { //2.启动activity if (mStackSupervisor.attachApplicationLocked(app)) { didSomething = true; } } catch (Exception e) { ... } } ...... return true; }
上面代码可以看到
thread.bindApplication
创建Application
对象后,在正常模式下调用mStackSupervisor.attachApplicationLocked(app)
方法去创建一个Activity
mStackSupervisor
是一个ActivityStackSupervisor
类型的示例下面是
attachApplicationLocked
方法boolean attachApplicationLocked(ProcessRecord app) throws RemoteException { ... try { //调用realStartActivityLocked方法真正启动activity if (realStartActivityLocked(hr, app, true, true)) { didSomething = true; } } catch (RemoteException e) { ... } ... return didSomething; }
然后是
realStartActivityLocked
方法final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException { ...... try { ...... app.thread.scheduleLaunchActivity(...); ...... } catch (RemoteException e) { ...... } ...... return true; }
app.thread
就是我们熟悉的ApplicationThread
(见 “6”) -
ApplicationThread
的scheduleLaunchActivity()
@Override public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) { ... //将消息交给H类型的mH处理 sendMessage(H.LAUNCH_ACTIVITY, r); }
跟
bindApplication
类似发送一个H.LAUNCH_ACTIVITY
消息最终这个消息被被
handler
分发给了ApplicationThread
的handleLaunchActivity
方法private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) { ...... //1.执行Activity的初始化及oncreate方法 Activity a = performLaunchActivity(r, customIntent); if (a != null) { ...... //2.执行Activity的onResume方法 handleResumeActivity(r.token, false, r.isForward,!r.activity.mFinished && !r.startsNotResumed); ...... } else { ...... } }
ApplicationThread
的performLaunchActivity
方法private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ...... Activity activity = null; try { ... //1.创建activity activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent); ... } catch (Exception e) { ... } try { //2.创建Application,实质上Application已经创建,只是获得已有的Application 实例 Application app = r.packageInfo.makeApplication(false, mInstrumentation); ...... if (activity != null) { //3.创建context Context appContext = createBaseContextForActivity(r, activity); ...... //4.将Context和Application 与activity关联起来,完成activity的初始化 activity.attach(appContext, this, getInstrumentation(), r.token, r.ident, app, r.intent, r.activityInfo, title, r.parent, r.embeddedID, r.lastNonConfigurationInstances, config, r.referrer, r.voiceInteractor); //5.调用activity的oncreate方法 if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } ...... } catch (SuperNotCalledException e) { ... } return activity; }
实际创建
Activity
这里还是使用Instrumentation
的对象,而mInstrumentation.newActivity
方法跟newApplication
方法一样。用反射创建出
Activity
创建出Activity
后performLaunchActivity
方法开始执行使用mInstrumentation
调用Activity
的声明周期
三、简述,
-
ActivityThread
main
方法,创建一个ActivityThread
对象 -
ActivityThread
对象调用attach
方法创建并绑定Application
-
attach
方法里获取到ActivityManagerProxy
对象mgr
,调用其attachApplication
方法,其中传入ApplicationThread
类型的参数mAppThread
,ApplicationThread
实现了Binder
-
attachApplication
方法 使用ActivityManagerProxy
对象的属性mRemote
通过Binder
机制远程调用ApplicationThread
的bindApplication
方法,mRemote
是ActivityManagerService
类型的远程IBinder
对象
attachApplication
方法 使用ActivityManagerService
通过Binder机制远程调用其attachApplication
方法,attachApplication
方法通过传递过来的对象mAppThread
通过Binder
机制远程调用ApplicationThread
的bindApplication
方法
-
bindApplication
方法使用Handler
机制发送H.BIND_APPLICATION
消息,消息被mH
分发处理后使用Instrumentation
通过反射出Application
对象,并调用其生命 -
attachApplication
在创建完Application
对象后,使用上述类似的机制远程调用ApplicationThread
的scheduleLaunchActivity
方法 -
scheduleLaunchActivity
方法同样使用Handler
发送H.LAUNCH_ACTIVITY
消息,后面同Application
的创建一样,使用Instrumentation
通过反射创建Activity
对象,然后调用其生命周期