一、基础知识
1. binder机制简介
binder是进程间通信的一种方式。在操作系统中,分为内核空间和用户空间,每个app都运行在自己的用户空间,binder机制具体实现不做深入分析;
在binder机制中,进行进程通信的两方,可分别称他们为Cient进程和Server进程;Cient进程和Server进程是由具体场景而定的,一个进程即可以是Cient进程,也可以是Server进程。
2. ServiceManager
ServiceManager负责把Binder Server注册到一个容器中,这样当有Client进程想与Server进程通信时,ServiceManager就可以从查找表中找到Binder Server,并返回Binder Server的代理对象给Client进程。
3. ActivityManagerService
ActivityManagerService是一个系统服务进程,四大组件的启动方式都是通过binder的方式与ActivityManagerService通信完成的;
ActivityManagerService将自己注册到ServiceManager的代码如下(本文分析基于android-29源码):
public class ActivityManagerService extends IActivityManager.Stub {
public void setSystemProcess() {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
}
}
注册完成之后,其他进程就可通过如下方式获得ActivityManagerService的代理:
public class ActivityManager {
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
}
以上代码,可以看出ActivityManager封装了对ActivityManagerService的调用,通过ActivityManager.gerService()即可获得对ActivityManagerService的调用。
4. ActivityThread、ApplicationThread傻傻分不清楚
ActivityThread就是UI线程,是在APP启动时创建的;它包含一个static的main()方法如下所示(后面会详细分析):
public final class ActivityThread{
// 后面会重点分析
Instrumentation mInstrumentation;
public static void main(String[] args) {
// 省略部分代码...
Looper.prepareMainLooper();
// ...
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
// ...
Looper.loop();
}
private void attach(boolean system, long startSeq) {
mInstrumentation = new Instrumentation();
// ...
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
}
}
ApplicationThread是ActivityThread的内部类,并不是一个线程,可用来代表当前APP进程(可能这就是它叫Thread的原因吧),由以下代码可分析出app间进程通信时,获得另一个app进程也是通过binder来获取其代理实现的;
private class ApplicationThread extends IApplicationThread.Stub {
// 省略部分代码...
}
5. Instrumentation
instrumentation
英 [ˌɪnstrəmenˈteɪʃn] 美 [ˌɪnstrəmenˈteɪʃn]
n.(一套)仪器,仪表;器乐谱写
Instrumentation源码解释如下:
/**
* Base class for implementing application instrumentation code. When running
* with instrumentation turned on, this class will be instantiated for you
* before any of the application code, allowing you to monitor all of the
* interaction the system has with the application. An Instrumentation
* implementation is described to the system through an AndroidManifest.xml's
* <instrumentation> tag.
*/
可以大概理解为所有与application有关的调用都会通过Instrumentation这样一个仪器来方便地观察到;换句话说就是,所有有关application的调用实际上都会通过Instrumentation;看一下其源码就可以看到它里面完成了许多功能:
public class Instrumentation {
private ActivityThread mThread = null;
private MessageQueue mMessageQueue = null;
private List<ActivityMonitor> mActivityMonitors;
public Application newApplication(ClassLoader cl, String className, Context context) {}
public Activity newActivity(ClassLoader cl, String className,
Intent intent) {}
public void callActivityOnNewIntent(Activity activity, Intent intent) {}
public ActivityResult execStartActivity(){}
}
二、Activity启动流程分析
例如App1要启动App2的一个Activity;Activity启动流程分析如下:
1. App1中的SampleActivity1启动App2的SampleActivity2
public class SampleActivity1 {
public void onClick() {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.app2.sample");
startActivity(intent);
}
}
2. Activity源码分析
public class Activity {
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
public void startActivity(Intent intent, @Nullable Bundle options) {
// ...
startActivityForResult(intent, -1);
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) {
// 省略部分代码...
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this,intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData());
}
}
}
可以看到,Activity的startActivity最终都调用到了Instrumentation里面;
3. Instrumentation源码分析
继续分析Instrumentation的execStartActivity()方法:
public class Instrumentation {
/**
* 可以看到传递的参数中比较重要的几个:
* 1. context who:就是前面的SampleActivity1
* 2. IBinder contextThread:传的value是mMainThread.getApplicationThread(),即当前APP进程,这样AMS进程才可以通过IBinder与App1进程通信(比如将结果返回,就需要binder通信)
* 3. IBinder token:又见IBinder,那一定也是别的进程需要通过这个IBinder进行通信
* 4. Intent intent:启动参数
**/
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
// 省略部分代码...
try {
int result = ActivityTaskManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
}
可以看到,又继续调用到了ActivityTaskManager.getService().startActivity()里面。
ps. 在android-28源码中是调用到了ActivityManager.getService().startActivity()里面,更老版本android源码中是调用了ActivityManagerNative.getDefault(),原理都类似,都是调用返回一个代理,最终到了系统进程去执行后续调起逻辑。
4. ActivityTaskManager源码分析
@SystemService(Context.ACTIVITY_TASK_SERVICE)
public class ActivityTaskManager {
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
}
可以看出,ActivityTaskManager.getService()调用得到IBinder的proxy继续执行后续代码,这样就就调用到了系统进程里面继续执行;ActivityTaskManager是系统启动期间就注册的一个binder service,其注册代码如下:
@SystemApi
public final class SystemServiceRegistry {
static {
registerService(Context.ACTIVITY_TASK_SERVICE, ActivityTaskManager.class,
new CachedServiceFetcher<ActivityTaskManager>() {
@Override
public ActivityTaskManager createService(ContextImpl ctx) {
return new ActivityTaskManager(
ctx.getOuterContext(), ctx.mMainThread.getHandler());
}});
}
接下来继续分析系统进程中startActivity()的执行步骤;
5. ActivityTaskManagerService源码分析
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId,
boolean validateIncomingUser) {
// 省略部分代码...
// getActivityStartController().obtainStarter返回一个ActivityStarter对象,下面继续分析ActivityStarter
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId)
.execute();
}
}
6. ActivityStarter源码分析
ActivityStarter负责处理intent中flag、启动模式等参数;
class ActivityStarter {
int execute() {
try {
// ...
return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
mRequest.outActivity, mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup,
mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
} finally {
onExecutionComplete();
}
}
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
int result = START_CANCELED;
final ActivityStack startedActivityStack;
try {
mService.mWindowManager.deferSurfaceLayout();
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
}
// ...
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
// ...
mRootActivityContainer.resumeFocusedStacksTopActivities();
}
}
接下里继续到RootActivityContainer;
/**
* Root node for activity containers.
* TODO: This class is mostly temporary to separate things out of ActivityStackSupervisor.java. The
* intention is to have this merged with RootWindowContainer.java as part of unifying the hierarchy.
* 看样子这个类后面可能会被合入到RootWindowContainer里,不重点分析;
*/
class RootActivityContainer {
boolean resumeFocusedStacksTopActivities(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && (targetStack.isTopStackOnDisplay() || getTopDisplayFocusedStack() == targetStack)) {
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
}
}
7. ActivityStack源码分析
ActivityStack负责管理activity栈和activity的状态,包括根据activity栈的状态决定如何管理activity等,当然activity的启动也是由它来继续完成;
/**
* State and management of a single stack of activities.
*/
class ActivityStack extends ConfigurationContainer {
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mInResumeTopActivity) {
// Don't even start recursing.
return false;
}
boolean result = false;
try {
// Protect against recursion.
mInResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
}
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
// ...
if (next.attachedToProcess()) {
if (nextNext != next) {
// Do over!
mStackSupervisor.scheduleResumeTopActivities();
}
} else {
// Whoops, need to restart this activity!
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
}
}
8. StackSupervisor源码分析
// TODO: This class has become a dumping ground. Let's
// - Move things relating to the hierarchy to RootWindowContainer
// - Move things relating to activity life cycles to maybe a new class called ActivityLifeCycler
// - Move interface things to ActivityTaskManagerService.
// - All other little things to other files.
// 看样子这部分代码后面也会被RootWindowContainer里面,后面Android源码分析可能要重点分析这个类了 😢
public class ActivityStackSupervisor implements RecentTasks.Callbacks {
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
boolean knownToBeDead = false;
if (wpc != null && wpc.hasThread()) {
try {
// 重点分析
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
knownToBeDead = true;
}
}
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) {
// ...
// Create activity launch transaction
final ClientTransaction clientTransaction = ClientTransaction.obtain( proc.getThread(), r.appToken);
// 重点,这里先记住它的callback是LaunchActivityItem
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
r.icicle, r.persistentState, results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
r.assistToken));
// Schedule transaction. mService就是ActivityTaskManagerService
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
}
以上代码分析出,启动activity被封装成transaction由ActivityTaskManagerService中的ClientLifecycleManager进程处理;
9. ClientLifecycleManager源码分析
class ClientLifecycleManager {
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
// the transaction is executed on client in ActivityThread.
transaction.recycle();
}
}
代码比较明确,就是执行ClientTransaction的内容;接着分析ClientTransaction的代码:
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/** Target client. */
private IApplicationThread mClient;
public void schedule() throws RemoteException {
// 重点
mClient.scheduleTransaction(this);
}
}
以上代码可以看出,最终执行到了mCient的scheduleTransaction()方法;而mClient就是传过来的IApplicationThread,这样就完成了从ActivityTaskManagerService进程到App2进程的调用;
10. ActivityThread源码分析
前面说过ApplicationThread可以代表app所在进程,其他进程访问ApplicationThread是通过IApplicationThread形式的binder代理实现的;ApplicationThread是ActivityThread的内部类,scheduleTransaction()方法最终是由ActivityThread实现;
/**
* This manages the execution of the main thread in an
* application process, scheduling and executing activities,
* broadcasts, and other operations on it as the activity
* manager requests.
* 继承了ClientTransactionHandler,后面也用分析到
*/
public final class ActivityThread extends ClientTransactionHandler {
// 重点
final H mH = new H();
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
private class ApplicationThread extends IApplicationThread.Stub {
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
}
class H extends Handler {
// ...
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case BIND_APPLICATION:
// ...
break;
case EXIT_APPLICATION:
// ...
break;
case RECEIVER:
// ...
case CREATE_SERVICE:
// ...
case BIND_SERVICE:
// ...
case UNBIND_SERVICE:
// ...
case STOP_SERVICE:
// ...
case CONFIGURATION_CHANGED:
// ...
case DUMP_SERVICE:
// ...
// 省略...
case EXECUTE_TRANSACTION:
// 重点
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
break;
case RELAUNCH_ACTIVITY:
handleRelaunchActivityLocally((IBinder) msg.obj);
break;
case PURGE_RESOURCES:
schedulePurgeIdler();
break;
}
}
}
}
可见,最终是继承了Handler的内部类H来发送message,并最终由mH完成处理;可以看到H的handleMessage()里面有许多熟悉的消息都是在这里处理的;后面继续分析EXECUTE_TRANSACTION的情况,即mTransactionExecutor.execute(transaction);
11.TransactionExecutor源码分析
/**
* Class that manages transaction execution in the correct order.
* 事务特性:保证按正确的顺序执行
*/
public class TransactionExecutor {
public void execute(ClientTransaction transaction) {
// 省略部分...
final IBinder token = transaction.getActivityToken();
executeCallbacks(transaction);
executeLifecycleState(transaction);
}
public void executeCallbacks(ClientTransaction transaction) {
// 还记得StackSupervisor中说到的transaction的callback是LaunchActivityItem吗,那后续执行就到了LaunchActivityItem里面
item.execute(mTransactionHandler, token, mPendingActions);
}
LaunchActivityItem源码如下:
public class LaunchActivityItem extends ClientTransactionItem {
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
可见,最后又由client执行了handleLaunchActivity,这里的client就是前面的ActivityThread。
12. 又见ActivityThread
那么接下来,继续分析ActivityThread的handleLaunchActivity()吧!
public final class ActivityThread extends ClientTransactionHandler {
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
// ...
final Activity a = performLaunchActivity(r, customIntent);
return a;
}
/** Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// 省略部分代码...
ActivityInfo aInfo = r.activityInfo;
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
// 重点代码,可以看到实际上又是Instrumentation新建了activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
// ...
}
try {
if (activity != null) {
// ...
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);
// 又是Instrumentation,下面分析
mInstrumentation.callActivityOnCreate(activity, r.state);
r.activity = activity;
}
r.setState(ON_CREATE);
}
return activity;
}
}
里面比较重要的代码是Instrumentation的newActivity()和callActivityOnCreate()方法,下面接着分析;
13. 又见Instrumentation
public class Instrumentation {
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
String pkg = intent != null && intent.getComponent() != null
? intent.getComponent().getPackageName() : null;
// 重点,由AppComponentFactory完成Activity的初始化
return getFactory(pkg).instantiateActivity(cl, className, intent);
}
private AppComponentFactory getFactory(String pkg) {
if (pkg == null) {
return AppComponentFactory.DEFAULT;
}
if (mThread == null) {
return AppComponentFactory.DEFAULT;
}
LoadedApk apk = mThread.peekPackageInfo(pkg, true);
// This is in the case of starting up "android".
if (apk == null) apk = mThread.getSystemContext().mPackageInfo;
return apk.getAppFactory();
}
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
// 重点,这里就调用了Activity的performCreate()方法
activity.performCreate(icicle);
postPerformCreate(activity);
}
}
可以看到,Instrumentation通过AppComponentFactory完成Activity的初始化,然后调用了Activity的performCreate()方法;
14. Activity源码分析
public class Activity{
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
mCanEnterPictureInPicture = true;
restoreHasCurrentPermissionRequest(icicle);
if (persistentState != null) {
// onCreate()方法,重要看到亲人了!
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
mActivityTransitionState.readState(icicle);
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
mFragments.dispatchActivityCreated();
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
}
}
至此就完成了activity的启动!
三、 总结
The End
欢迎关注我,一起解锁更多技能:BC的主页~~💐💐💐
在线查看Android源码:cs.android.com/
Android源码下载:source.android.google.cn/setup/downl…
Anroid studio内源码查看方法:github.com/anggrayudi/…