Android知识总结
一、启动其他服务(startOtherServices)
Activity 启动
首先我们进入SystemServer
启动其他服务(startOtherServices)里面来启动 Launcher
:
private void startOtherServices(@NonNull TimingsTraceAndSlog t){
...
mActivityManagerService.systemReady(() -> { // 启动Launcher
Slog.i(TAG, "Making services ready");
t.traceBegin("StartActivityManagerReadyPhase");
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
t.traceEnd();
t.traceBegin("StartObservingNativeCrashes");
try {
mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
reportWtf("observing native crashes", e);
}
t.traceEnd();
// No dependency on Webview preparation in system server. But this should
// be completed before allowing 3rd party
final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
Future webviewPrep = null;
if (!mOnlyCore && mWebViewUpdateService != null) {
webviewPrep = SystemServerInitThreadPool.submit(() -> {
Slog.i(TAG, WEBVIEW_PREPARATION);
TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog();
traceLog.traceBegin(WEBVIEW_PREPARATION);
ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
mZygotePreload = null;
mWebViewUpdateService.prepareWebViewInSystemServer();
traceLog.traceEnd();
}, WEBVIEW_PREPARATION);
}
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
t.traceBegin("StartCarServiceHelperService");
mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
t.traceEnd();
}
t.traceBegin("StartSystemUI");
try {
// 启动 SystemUI
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
reportWtf("starting System UI", e);
}
t.traceEnd();
...
}
}, t);
t.traceEnd(); // startOtherService
}
执行ActivityManagerService@systemReady
方法,接下来的执行过程简要概况
- 简单执行步骤
--> systemReady @ActivityManagerService
--> mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
--> ActivityTaskManagerService @resumeTopActivities (ATMS 里面的内部类 LocalService实现了 ActivityTaskManagerInternal抽象类)
--> mRootWindowContainer.resumeFocusedStacksTopActivities(); @RootWindowContainer
--> focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions) @ActivityStack
--> resumeTopActivityInnerLocked(prev, options);
--> resumeNextFocusableActivityWhenStackIsEmpty(prev, options);
--> mRootWindowContainer.resumeHomeActivity(prev, reason, getDisplayArea()); @RootWindowContainer
--> startHomeOnTaskDisplayArea(...)
--> mService.getActivityStartController() @ActivityTaskManagerService
.startHomeActivity(homeIntent, aInfo, myReason,taskDisplayArea);@ActivityStartController
--> execute() @ActivityStarter //栈的管理相关
--> res = executeRequest(mRequest);
--> ActivityRecord sourceRecord = null; //启动方的 Activity 记录
--> ActivityRecord resultRecord = null; //要启动的 Activity 记录
--> startActivityUnchecked(...)
--> startActivityInner(...)
--> mRootWindowContainer.resumeFocusedStacksTopActivities(mTargetStack, mStartActivity, mOptions); @RootWindowContainer
--> result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); @ActivityStack
--> resumeTopActivityInnerLocked(prev, options);
--> mStackSupervisor.startSpecificActivity(next, true, false); @ActivityStackSupervisor
在ActivityStackSupervisor
的startSpecificActivity
方法是我们的重点
void startSpecificActivity(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()) {
//进程存在,走这边
//也就是当我们的APP启动后,Activity 的启动会走这里
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;
}
r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
final boolean isTop = andResume && r.isTopRunningActivity();
//进程不存在,走这里
//因为我们这里是 systemserver 进程,通过 lunch 启动我们的APP,此时进程是不存在的
mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}
重点
- 1、
进程存在
,start 启动 activity- 2、
进程不存在
,lunch 启动 activity
二、进程不存在流程(主要是和zygote通信)
当进程不存在时,AMS 创建 Socket,通知 Zygote 创建 APP 进程。执行步骤如下:
ActivityTaskManagerService@startProcessAsync
void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
String hostingType) {
try {
if (Trace.isTagEnabled(TRACE_TAG_WINDOW_MANAGER)) {
Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "dispatchingStartProcess:"
+ activity.processName);
}
// Post message to start process to avoid possible deadlock of calling into AMS with the
// ATMS lock held.
//走到 AMS 中获取参数
final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
isTop, hostingType, activity.intent.getComponent());
mH.sendMessage(m);
} finally {
Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
}
}
- ActivityManagerInternal::startProcess 启动进程
会执行ActivityManagerService
的内部类LocalService extends ActivityManagerInternal
的startProcess
方法
public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead,
boolean isTop, String hostingType, ComponentName hostingName) {
try {
if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "startProcess:"
+ processName);
}
synchronized (ActivityManagerService.this) {
//启动进程,并加锁
startProcessLocked(processName, info, knownToBeDead, 0 /* intentFlags */,
new HostingRecord(hostingType, hostingName, isTop),
ZYGOTE_POLICY_FLAG_LATENCY_SENSITIVE, false /* allowWhileBooting */,
false /* isolated */, true /* keepIfLarge */);
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
}
- 以下步骤省略
--> startProcessLocked
--> mProcessList.startProcessLocked @ProcessList
--> startProcess //启动进程
--> Process.start(...) @Process //进程启动
--> ZYGOTE_PROCESS.start(...) @ZygoteProcess
--> public static final ZygoteProcess ZYGOTE_PROCESS = new ZygoteProcess();
--> startViaZygote
--> zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),zygotePolicyFlags,argsForZygote);
--> openZygoteSocketIfNeeded //打开 Socket 建立连接
--> attemptConnectionToPrimaryZygote
--> ZygoteState.connect @ZygoteState
--> LocalSocket zygoteSessionSocket = new LocalSocket(); //创建 LocalSocket
--> zygoteSessionSocket.connect(zygoteSocketAddress); //建立连接
--> zygoteSendArgsAndGetResult //发送消息到 zygote
--> attemptUsapSendArgsAndGetResult
我们看startViaZygote@ZygoteProcess
建立通信建立过程
2.1、openZygoteSocketIfNeeded 建立 Socket 链接
private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
try {
//主 Zygote,主要和Zygote的位数有关。有32、64的Zygote
attemptConnectionToPrimaryZygote();
if (primaryZygoteState.matches(abi)) {
return primaryZygoteState;
}
if (mZygoteSecondarySocketAddress != null) {
//次 Zygote,主要和Zygote的位数有关。有32、64的Zygote
attemptConnectionToSecondaryZygote();
if (secondaryZygoteState.matches(abi)) {
return secondaryZygoteState;
}
}
} catch (IOException ioe) {
throw new ZygoteStartFailedEx("Error connecting to zygote", ioe);
}
throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
}
attemptConnectionToPrimaryZygote
private void attemptConnectionToPrimaryZygote() throws IOException {
if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
primaryZygoteState =
ZygoteState.connect(mZygoteSocketAddress, mUsapPoolSocketAddress); //建立链接
maybeSetApiBlacklistExemptions(primaryZygoteState, false);
maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
}
}
static ZygoteState connect(@NonNull LocalSocketAddress zygoteSocketAddress,
@Nullable LocalSocketAddress usapSocketAddress)
throws IOException {
DataInputStream zygoteInputStream;
BufferedWriter zygoteOutputWriter;
//创建 LocalSocket
final LocalSocket zygoteSessionSocket = new LocalSocket();
if (zygoteSocketAddress == null) {
throw new IllegalArgumentException("zygoteSocketAddress can't be null");
}
try {
zygoteSessionSocket.connect(zygoteSocketAddress); //建立连接
zygoteInputStream = new DataInputStream(zygoteSessionSocket.getInputStream());
zygoteOutputWriter =
new BufferedWriter(
new OutputStreamWriter(zygoteSessionSocket.getOutputStream()),
Zygote.SOCKET_BUFFER_SIZE);
} catch (IOException ex) {
try {
zygoteSessionSocket.close();
} catch (IOException ignore) { }
throw ex;
}
return new ZygoteState(zygoteSocketAddress, usapSocketAddress,
zygoteSessionSocket, zygoteInputStream, zygoteOutputWriter,
getAbiList(zygoteOutputWriter, zygoteInputStream));
}
2.2、zygoteSendArgsAndGetResult 发送消息到 zygote
private Process.ProcessStartResult zygoteSendArgsAndGetResult(
ZygoteState zygoteState, int zygotePolicyFlags, @NonNull ArrayList args)
throws ZygoteStartFailedEx {
for (String arg : args) {
if (arg.indexOf('\n') >= 0) {
throw new ZygoteStartFailedEx("Embedded newlines not allowed");
} else if (arg.indexOf('\r') >= 0) {
throw new ZygoteStartFailedEx("Embedded carriage returns not allowed");
}
}
String msgStr = args.size() + "\n" + String.join("\n", args) + "\n";
if (shouldAttemptUsapLaunch(zygotePolicyFlags, args)) {
try {
return attemptUsapSendArgsAndGetResult(zygoteState, msgStr);
} catch (IOException ex) {
Log.e(LOG_TAG, "IO Exception while communicating with USAP pool - "
+ ex.getMessage());
}
}
return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);
}
- 下面主要是通信
private Process.ProcessStartResult attemptUsapSendArgsAndGetResult(
ZygoteState zygoteState, String msgStr)
throws ZygoteStartFailedEx, IOException {
try (LocalSocket usapSessionSocket = zygoteState.getUsapSessionSocket()) {
final BufferedWriter usapWriter =
new BufferedWriter(
new OutputStreamWriter(usapSessionSocket.getOutputStream()),
Zygote.SOCKET_BUFFER_SIZE);
final DataInputStream usapReader =
new DataInputStream(usapSessionSocket.getInputStream());
usapWriter.write(msgStr); //写数据
usapWriter.flush();
Process.ProcessStartResult result = new Process.ProcessStartResult();
result.pid = usapReader.readInt();
// USAPs can't be used to spawn processes that need wrappers.
result.usingWrapper = false;
if (result.pid >= 0) {
return result;
} else {
throw new ZygoteStartFailedEx("USAP specialization failed");
}
}
}
三、zygote 创建 APP 进程
在ZygoteInit@main
方法里接受AMS发送过来的信息
public static void main(String argv[]) {
....
//启动一个死循环监听来自Client端的消息,即接收AMS传过来的消息
//接收到AMS信息后,创建APP进程
//反射执行 ActivityThread@main()方法
ZygoteServer caller = zygoteServer.runSelectLoop(abiList);
if (caller != null) {
//执行反射方法
caller.run();
}
}
- 以下为简要步骤
--> caller = zygoteServer.runSelectLoop(abiList); @ZygoteServer (里面会反射执行 ActivityThread@main)
--> pollReturnValue = Os.poll(pollFDs, pollTimeoutMs); //进入等待阻塞
--> ZygoteConnection connection = peers.get(pollIndex); //获取 ZygoteConnection
--> final Runnable command = connection.processOneCommand(this); //创建进程
--> processOneCommand @ZygoteConnection
--> pid = Zygote.forkAndSpecialize //创建进程 pid
--> handleChildProc //通过反射创建进程
--> handleChildProc
--> ZygoteInit.childZygoteInit @ZygoteInit
--> RuntimeInit.findStaticMain @RuntimeInit
--> MethodAndArgsCaller@run()
- 反射创建方法
private Runnable handleChildProc(ZygoteArguments parsedArgs,
FileDescriptor pipeFd, boolean isZygote) {
closeSocket();
Zygote.setAppProcessName(parsedArgs, TAG);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
if (parsedArgs.mInvokeWith != null) {
WrapperInit.execApplication(parsedArgs.mInvokeWith,
parsedArgs.mNiceName, parsedArgs.mTargetSdkVersion,
VMRuntime.getCurrentInstructionSet(),
pipeFd, parsedArgs.mRemainingArgs);
throw new IllegalStateException("WrapperInit.execApplication unexpectedly returned");
} else {
if (!isZygote) { //不是首次创建的进程
return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mDisabledCompatChanges,
parsedArgs.mRemainingArgs, null /* classLoader */);
} else { //首次创建的进程
return ZygoteInit.childZygoteInit(parsedArgs.mTargetSdkVersion,
parsedArgs.mRemainingArgs, null /* classLoader */);
}
}
}
3.1、进入ActivityThread@main
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
AndroidOs.install();
CloseGuard.setEnabled(false);
Environment.initForCurrentUser();
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
TrustedCertificateStore.setDefaultUserDirectory(configDir);
initializeMainlineModules();
Process.setArgV0("");
Looper.prepareMainLooper();
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
ActivityThread thread = new ActivityThread();
//建立 Binder 通道 (创建新线程)
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
//获取 handler
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
//这里循环执行,handler 发送消息执行应用的事件
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) { //非系统服务走这里,即启动我们的 app
android.ddm.DdmHandleAppName.setAppName("",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
final IActivityManager mgr = ActivityManager.getService();
try {
//应用的句柄发给AMS,句柄为 ApplicationThread
mgr.attachApplication(mAppThread, startSeq);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
// Watch for getting close to heap limit.
BinderInternal.addGcWatcher(new Runnable() {
@Override public void run() {
if (!mSomeActivitiesChanged) {
return;
}
Runtime runtime = Runtime.getRuntime();
long dalvikMax = runtime.maxMemory();
long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
if (dalvikUsed > ((3*dalvikMax)/4)) {
if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
+ " total=" + (runtime.totalMemory()/1024)
+ " used=" + (dalvikUsed/1024));
mSomeActivitiesChanged = false;
try {
ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
});
} else { //系统服务走这里
// Don't set application object here -- if the system crashes,
// we can't display an alert, we just want to die die die.
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
//创建两个 content ,一个是 system 的content,另一个是 app 的 content
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
ViewRootImpl.ConfigChangedCallback configChangedCallback
= (Configuration globalConfig) -> {
synchronized (mResourcesManager) {
// TODO (b/135719017): Temporary log for debugging IME service.
if (Build.IS_DEBUGGABLE && mHasImeComponent) {
Log.d(TAG, "ViewRootImpl.ConfigChangedCallback for IME, "
+ "config=" + globalConfig);
}
// We need to apply this change to the resources immediately, because upon returning
// the view hierarchy will be informed about it.
if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
null /* compat */,
mInitialApplication.getResources().getDisplayAdjustments())) {
updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
mResourcesManager.getConfiguration().getLocales());
// This actually changed the resources! Tell everyone about it.
if (mPendingConfiguration == null
|| mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
mPendingConfiguration = globalConfig;
sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
}
}
}
};
ViewRootImpl.addConfigCallback(configChangedCallback);
}
接下来执行因为APP进程已创建,会ActivityManagerService#attachApplication
方法
public final void attachApplication(IApplicationThread thread, long startSeq) {
if (thread == null) {
throw new SecurityException("Invalid application interface");
}
synchronized (this) {
int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
Binder.restoreCallingIdentity(origId);
}
}
- 以下为简单执行步骤
// 让AMS可以管理新的进程
--> attachApplicationLocked(thread, callingPid, callingUid, startSeq); @ActivityManagerService
//进入@ActivityThread 内部类 ApplicationThread 实现 IApplicationThread.Stub
//进行创建 application
--> thread.bindApplication
//@ActivityTaskManagerService 内部类 LocalService 实现 ActivityTaskManagerInternal
--> didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
--> mRootWindowContainer.attachApplication(wpc); @RootWindowContainer
--> RootWindowContainer::startActivityForAttachedApplicationIfNeeded @RootWindowContainer
--> mStackSupervisor.realStartActivityLocked @ActivityStackSupervisor
到这里我们可以看到在ActivityStackSupervisor
的startSpecificActivit
中分为进程存在和不存在的情况下,最终都走的是ActivityStackSupervisor@realStartActivityLocked
方法。
3.2、realStartActivityLocked执行过程
// 让AMS可以管理新的进程
--> attachApplicationLocked(thread, callingPid, callingUid, startSeq); @ActivityManagerService
//进入@ActivityThread 内部类 ApplicationThread 实现 IApplicationThread.Stub
--> thread.bindApplication
//@ActivityTaskManagerService 内部类 LocalService 实现 ActivityTaskManagerInternal
--> didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
--> mRootWindowContainer.attachApplication(wpc); @RootWindowContainer
--> RootWindowContainer::startActivityForAttachedApplicationIfNeeded @RootWindowContainer
--> mStackSupervisor.realStartActivityLocked @ActivityStackSupervisor
--> mStackSupervisor.realStartActivityLocked @ActivityStackSupervisor
//把 LaunchActivityItem 添加到 clientTransaction 事务管理中
--> clientTransaction.addCallback(LaunchActivityItem.obtain())
--> mService.getLifecycleManager().scheduleTransaction(clientTransaction); //执行事务
--> mService.getLifecycleManager() //在 ATMS 中获取 ClientLifecycleManager
--> scheduleTransaction(clientTransaction); @ClientLifecycleManager //执行事务
- 执行事务
#执行事务
--> scheduleTransaction(clientTransaction); @ClientLifecycleManager
--> transaction.schedule() @ClientTransaction
//ActivityThread 内部类 ApplicationThread 实现 IApplicationThread.Stub
--> mClient.scheduleTransaction(this); @ActivityThread
//ClientTransactionHandler 为 ActivityThread 的父类
--> scheduleTransaction @ClientTransactionHandler
//发送 EXECUTE_TRANSACTION 消息
--> sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); @ActivityThread
--> mH.sendMessage(msg); //ActivityThread 内部类 H()
--> mTransactionExecutor.execute(transaction); @TransactionExecutor
--> executeCallbacks(transaction); @TransactionExecutor
//LaunchActivityItem 继承 ClientTransactionItem,在上面添加事务中添加
--> item.execute(mTransactionHandler, token, mPendingActions); @LaunchActivityItem
//ClientTransactionHandler 为 ActivityThread 的父类
--> client.handleLaunchActivity(r, pendingActions, null /* customIntent */) @ActivityThread
--> performLaunchActivity(r, customIntent); @ActivityThread
--> mInstrumentation.newActivity //创建 Activity
--> activity.attach //绑定
--> mInstrumentation.callActivityOnCreate @Instrumentation
--> activity.performCreate(icicle); @Activity
--> onCreate
Android 启动流程
Android 生命周期管理类图