ActivityThread
翻译:它管理应用程序进程中主线程的执行,根据活动管理器的请求,在其上调度和执行活动、广播和其他操作。
ActivityThread是app启动的入口,会执行main方法:
public static void main(String[] args) {
//创建MainLooper
Looper.prepareMainLooper();
//创建ActivityThread,执行attach()方法,第一个参数代表是否是系统应用。
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
//sMainThreadHandler就是ActivityThread用于处理消息的handle
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
//执行 Looper.loop()
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
创建MainLooper,并储存到从sThreadLocal中。
Looper-》
//->Looper.prepareMainLooper
public static void prepareMainLooper() {
//创建looper,并储存
prepare(false);
synchronized (Looper.class) {
if (sMainLooper != null) {
throw new IllegalStateException("The main Looper has already been prepared.");
}
//获取looper
sMainLooper = myLooper();
}
}
//->Looper.prepare
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));
}
//->Looper.myLooper
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}
看下ActivityThread的成员变量:
public final class ActivityThread {
//ApplicationThread是ActivityThread的内部类,其实现IApplicationThread.Stub的接口
//Binder通信的时候,他的代理对象在服务端,用来和系统服务交互,并将服务端的消息发送到客户端,也就是ActivityThread。
final ApplicationThread mAppThread = new ApplicationThread();
//从sThreadLocal.get()到刚才创建的mainLopper对象
final Looper mLooper = Looper.myLooper();
//用于发送和处理消息的handle ,继承Handle
final H mH = new H();
}
继续看下attach方法:
//上面调用处传进来了第一个参数是false,表示是否是系统应用,第二个参数是时间。
private void attach(boolean system, long startSeq) {
if (!system) {//不是系统应用
//这里创建的mgr就是服务端ams在客户端的代理类,主要用于binder通信。
final IActivityManager mgr = ActivityManager.getService();
//这里会创建application,并且会将客户端的ApplicationThread的对象传递给服务段,进行一个绑定,用来binder通信
mgr.attachApplication(mAppThread, startSeq);
} else {//是系统应用
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
}
}
也就是说,向ams发送创建Applicaiton的请求和ams绑定客户端ApplicationThread对象的操做都在这里面。
继续跟进看下ActivityManagerService-》attachApplication
public final void attachApplication(IApplicationThread thread) {
synchronized (this) {
int callingPid = Binder.getCallingPid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid);
Binder.restoreCallingIdentity(origId);
}
}
ActivityManagerService-》attachApplicationLocked
private boolean attachApplicationLocked(IApplicationThread thread, int pid) {
if (app.instr != null) {
thread.bindApplication(processName, appInfo, providers,
app.instr.mClass,
profilerInfo, app.instr.mArguments,
app.instr.mWatcher,
app.instr.mUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial);
} else {
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial);
}
return true;
}
很明显,通过 IApplicationThread 又将代码回调到了 Client 端。
看ApplicationThread-》bindApplication方法:开始发送H.BIND_APPLICATION的消息了。当然接受的地方就是在ActivityThread里面了。
public final void bindApplication(... ...) {
sendMessage(H.BIND_APPLICATION, data);
}
// 根据消息机制,我们在 ActivityThread#H 中寻找消息处理
public void handleMessage(Message msg) {
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
}
我们先了解下这个服务端给我们的AppBindData是个什么:
首先他也是ActivityThread的内部类,看下的成员都有啥。
static final class AppBindData {
LoadedApk info;//关于当前加载的 .apk 的本地状态。
String processName;//进程名称
ApplicationInfo appInfo; //检索有关特定应用程序的信息。这对应于从 AndroidManifest.xml 的标记收集的信息。
ComponentName instrumentationName;//instrumentation名字,通过源码我猜是ams通过我们的应用信息生成的,然后让我们按照这个名称去创建队员的instrumentation。因为反射生成Instrumentation就是按照的这个名字。
}
继续看下拿这个AppBindData去干啥了:
ActivityThread-》handleBindApplication
/
private void handleBindApplication(AppBindData data) {
final InstrumentationInfo ii;
if (data.instrumentationName != null) {
ii = new ApplicationPackageManager(null, getPackageManager())
.getInstrumentationInfo(data.instrumentationName, 0);
} else {
ii = null;
}
// 根据上层调用传入的参数,决定初始化 mInstrumentation 实例的方式
// 1. 使用 ClassLoader 初始化;
if (ii != null) {
final ApplicationInfo instrApp = new ApplicationInfo();
ii.copyTo(instrApp);
instrApp.initForUser(UserHandle.myUserId());
final LoadedApk pi = getPackageInfo(......);
final ContextImpl instrContext = ContextImpl.createAppContext(this, pi);
//利用这个AppBindData的instrumentationName去创建Instrumentation
try {
final ClassLoader cl = instrContext.getClassLoader();
mInstrumentation = (Instrumentation)
cl.loadClass(data.instrumentationName.getClassName()).newInstance();
}
final ComponentName component = new ComponentName(ii.packageName, ii.name);
mInstrumentation.init(... ...);
} else {
//2. InstrumentationInfo==null,直接 new 对象
mInstrumentation = new Instrumentation();
}
try {
// 调用 makeApplication 去创建 Application 对象,info就是LoadedApk。
Application app = data.info.makeApplication(data.restrictedBackupMode, null);
mInitialApplication = app;
// 初始化 application 对象后,通过 mInstrumentation 调用 application 的 onCreate 方法
mInstrumentation.callApplicationOnCreate(app);
}
}
创建Application 对象:
LoadedApk-》makeApplication
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
java.lang.ClassLoader cl = getClassLoader();
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
// 入参的 instrumentation 为 null,使用 ActivityThread 的 mInstrumentation
app = mActivityThread.mInstrumentation.newApplication(cl, appClass, appContext);
appContext.setOuterContext(app);
return app;
}
实际还是在Instrumentation中创建Application。
Instrumentation-》newApplication
public Application newApplication(ClassLoader cl, String className, Context context) {
return newApplication(cl.loadClass(className), context);
}
static public Application newApplication(Class> clazz, Context context){
Application app = (Application)clazz.newInstance();
app.attach(context);
return app;
}
接下来再看一下Activity启动的时候,ActivityThread做了什么?
当我们调用startActivity的时候,最后通过Instrumentation.execStartActivity()方法,里面会去获取ams在客户端的代理类,跟AMS进行Binder通信,ams会去调用自己的startActivity()方法,ams处理完成后,通过在服务端的ApplicationThread的代理类将启动事件传递到ApplicationThread中,ApplicationThread通过发送handler消息到ActivityThread,然后ActivityThread收到消息后处理启动Activity的逻辑。
也就是说针对Activity的相关的操作,最后都要到这里去执行。
查看==ActivityThread.performLaunchActivity()==:
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
//创建Activity,还是mInstrumentation创建的。还是发射。
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
}
//执行activity的attach方法
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, window, r.configCallback,
r.assistToken);
//这个方法会去执行 activity.performCreate(icicle);接着就是activiy的onCreate方法了,参数是Bundle。
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
}
Activity创建后取执行attach方法了,之后执行oncreate方法。我们看下attach方法:
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
attachBaseContext(context);
mFragments.attachHost(null /*parent*/);
mWindow = new PhoneWindow(this, window, activityConfigCallback); mWindow.getLayoutInflater().setPrivateFactory(this);
mMainThread = aThread;
mInstrumentation = instr;
mToken = token;
mAssistToken = assistToken;
mIdent = ident;
mApplication = application;
mIntent = intent;
mReferrer = referrer;
mComponent = intent.getComponent();
mActivityInfo = info;
mTitle = title;
mParent = parent;
mEmbeddedID = id;
mWindow.setWindowManager(
(WindowManager) context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
if (mParent != null) {
mWindow.setContainer(mParent.getWindow());
}
mWindowManager = mWindow.getWindowManager();
}
可以看到,fragment也进行attach操作了,phoneWindow也是这时候创建的,window的LayoutInflater也是这时候创建的,然后将一些参数进行了应用赋值。最后给windon设置了setWindowManager。
最后总结一下,ActivityThread它管理应用程序进程中主线程的执行,根据活动管理器的请求,在其上调度和执行活动、广播和其他操作。~~~~~
最后,睡觉啪啪啪~~~