Activity启动流程分析(android-29),android webview

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 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.

《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》

【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整资料开源分享

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
    1. IBinder contextThread:传的value是mMainThread.getApplicationThread(),即当前APP进程,这样AMS进程才可以通过IBinder与App1进程通信(比如将结果返回,就需要binder通信)
    1. IBinder token:又见IBinder,那一定也是别的进程需要通过这个IBinder进行通信
    1. 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 IActivityTaskManagerSingleton =
new Singleton() {
@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() {
@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源码分析可能要重点分析这个类了

上一篇:Day03


下一篇:12_29日结