首页 > 系统相关 >【framework】应用进程启动流程

【framework】应用进程启动流程

时间:2023-03-19 17:22:58浏览次数:52  
标签:... java String int 流程 final framework 进程 app

1 前言

Activity启动流程 中介绍了从点击桌面上应用快捷方式到 Activity 的 onCreate() 方法调用流程,本将介绍应用进程的启动流程。由于应用进程启动流程复杂,本文按进程将其拆分为3个部分展开介绍:

  • system_server 进程:介绍从 AMS.LocalService(startProcess方法)到 ZygoteState(connect 方法)的调用流程;
  • zygote 进程:介绍从 ZygoteInit(main方法)到 ActivityThread(main方法)的调用流程;
  • 应用进程:介绍从 ActivityThread(main 方法)到 Application(onCreate 方法)的调用流程。

​ 为区分不同进程,将 system_server 进程、zygote 进程、应用进程分别标识为深蓝色、绿色、紫色。

2 源码分析

2.1 ActivityManagerInternal 初始化流程

(1)请求启动应用进程的入口

​ /frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
	final WindowProcessController wpc = mService.getProcessController(r.processName, r.info.applicationInfo.uid);
	...
    //判断应用进程是否已创建,即 IApplicationThread 是否为空
	if (wpc != null && wpc.hasThread()) {
		try {
            //启动 Activity
			realStartActivityLocked(r, wpc, andResume, checkConfig);
			return;
		}
	}
	try {
		...
		//应用进程不存在,通知创建应用进程,mService 为 ATMS;mService.mAmInternal 为 ActivityManagerInternal 
		final Message msg = PooledLambda.obtainMessage(
				ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
				r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
		mService.mH.sendMessage(msg);
	}
	...
}

​ ActivityStackSupervisor 对象在 ATMS 的 initialize() 方法中创建,并将 ATMS 对象注入到 ActivityStackSupervisor 中。

​ PooledLambda.obtainMessage() 获取一个 Message,并为其指定 Callback,即执行 mService.mAmInternal 对象的 ActivityManagerInternal::startProcess 函数,函数入参为 r.processName、r.info.applicationInfo 等5个参数。由此可知,ActivityManagerInternal 的 startProcess() 方法是请求启动应用进程的起点。

​ ActivityManagerInternal 是抽象类,其实现类是 AMS 的内部类 LocalService。接下来将分析 ActivityManagerInternal 的创建流程和 ATMS 获取其对象的流程。

(2)ActivityManagerInternal 的创建

​ /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

private void start() {
	...
	LocalServices.addService(ActivityManagerInternal.class, new LocalService());
    //调用 ATMS 的 onActivityManagerInternalAdded 方法进一步初始化
	mActivityTaskManager.onActivityManagerInternalAdded();
	...
}

​ start() 方法被 AMS.Lifecycle 的 onStart() 方法调用,onStart() 方法又被 SystemServiceManager 的 startService() 方法调用。

(3)ATMS 获取 ActivityManagerInternal

​ /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java

public void onActivityManagerInternalAdded() {
	synchronized (mGlobalLock) {
		mAmInternal = LocalServices.getService(ActivityManagerInternal.class);
		...
	}
}

(4)LocalServices

​ /frameworks/base/core/java/com/android/server/LocalServices.java

public final class LocalServices {
    ...

    private static final ArrayMap<Class<?>, Object> sLocalServiceObjects = new ArrayMap<Class<?>, Object>();

    public static <T> T getService(Class<T> type) {
        synchronized (sLocalServiceObjects) {
            return (T) sLocalServiceObjects.get(type);
        }
    }

    public static <T> void addService(Class<T> type, T service) {
        synchronized (sLocalServiceObjects) {
            ...
            sLocalServiceObjects.put(type, service);
        }
    }
	
	...
}

​ 注意: LocalServices 用于管理服务;而 LocalService 是 AMS 的内部类,并继承 ActivityManagerInternal。

2.2 AMS 到 ZygoteState

​ 如图,深蓝色的类是在 system_server 进程中执行的,黄色的类是 Socket 跨进程通讯工具类。

img

(1)startProcess

​ /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.LocalService****.java

public void startProcess(String processName, ApplicationInfo info, boolean knownToBeDead, String hostingType, ComponentName hostingName) {
	try {
		...
		synchronized (ActivityManagerService.this) {
			startProcessLocked(processName, info, knownToBeDead, 0 , new HostingRecord(hostingType, hostingName), false, false, true);
		}
	}
	...
}

(2)startProcessLocked

​ /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService****.java

final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, 
			HostingRecord hostingRecord, boolean allowWhileBooting, boolean isolated, boolean keepIfLarge) {
    //mProcessList 在定义时就被初始化,即:final ProcessList mProcessList = new ProcessList()
	return mProcessList.startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingRecord, 
			allowWhileBooting, isolated, 0, keepIfLarge, null, null, null, null);
}

(3)startProcessLocked

​ /frameworks/base/services/core/java/com/android/server/am/ProcessList.java

final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, 
		HostingRecord hostingRecord, boolean allowWhileBooting, boolean isolated, int isolatedUid, 
		boolean keepIfLarge, String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
	...
	ProcessRecord app;
	if (!isolated) {
		app = getProcessRecordLocked(processName, info.uid, keepIfLarge);
		...
	}
	...
	if (app == null) {
		...
	} else {
		app.addPackage(info.packageName, info.longVersionCode, mService.mProcessStats);
		...
	}
	...
	final boolean success = startProcessLocked(app, hostingRecord, abiOverride);
	...
	return success ? app : null;
}

(4)startProcessLocked

​ /frameworks/base/services/core/java/com/android/server/am/ProcessList.java

final boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord, String abiOverride) {
	return startProcessLocked(app, hostingRecord, false, false, false, abiOverride);
}

(5)startProcessLocked

​ /frameworks/base/services/core/java/com/android/server/am/ProcessList.java

boolean startProcessLocked(ProcessRecord app, HostingRecord hostingRecord, boolean disableHiddenApiChecks, 
		boolean disableTestApiChecks, boolean mountExtStorageFull, String abiOverride) {
	...
	try {
		...
        //在 RuntimeInit 中会通过反射创建 ActivityThread 对象,后面会更名为 processClass、args.startClass
		final String entryPoint = "android.app.ActivityThread";
		return startProcessLocked(hostingRecord, entryPoint, app, uid, gids, runtimeFlags, 
			mountExternal, seInfo, requiredAbi, instructionSet, invokeWith, startTime);
	}
	...
}

(6)startProcessLocked

​ /frameworks/base/services/core/java/com/android/server/am/ProcessList.java

boolean startProcessLocked(HostingRecord hostingRecord, String entryPoint, ProcessRecord app, 
		int uid, int[] gids, int runtimeFlags, int mountExternal, String seInfo, 
		String requiredAbi, String instructionSet, String invokeWith, long startTime) {
	...
	final long startSeq = app.startSeq = ++mProcStartSeqCounter;
	...
	mPendingStarts.put(startSeq, app);

	if (mService.mConstants.FLAG_PROCESS_START_ASYNC) {
		...
		mService.mProcStartHandler.post(() -> {
			try {
				final Process.ProcessStartResult startResult = startProcess(app.hostingRecord,
						entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal,
						app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);
				synchronized (mService) {
					handleProcessStartedLocked(app, startResult, startSeq);
				}
			}
			...
		});
		return true;
	} else {
		try {
			final Process.ProcessStartResult startResult = startProcess(hostingRecord, entryPoint, app, uid, gids, 
					runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith, startTime);
			handleProcessStartedLocked(app, startResult.pid, startResult.usingWrapper, startSeq, false);
		}
		...
		return app.pid > 0;
	}
}

(7)startProcess

​ /frameworks/base/services/core/java/com/android/server/am/ProcessList.java

private Process.ProcessStartResult startProcess(HostingRecord hostingRecord, String entryPoint,
		ProcessRecord app, int uid, int[] gids, int runtimeFlags, int mountExternal,
		String seInfo, String requiredAbi, String instructionSet, String invokeWith, long startTime) {
	try {
		...
		else {
			startResult = Process.start(entryPoint, app.processName, uid, uid, gids, runtimeFlags, mountExternal,
					app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, app.info.dataDir, invokeWith, 
					app.info.packageName, app.mDisabledCompatChanges, new String[]{PROC_START_SEQ_IDENT + app.startSeq});
		}
		...
		return startResult;
	}
	...
}

(8)start

​ /frameworks/base/core/java/android/os/Process.java

public static ProcessStartResult start(final String processClass, final String niceName, int uid, int gid, @Nullable int[] gids,
		int runtimeFlags, int mountExternal, int targetSdkVersion, String seInfo, String abi, String instructionSet,
		String appDataDir, String invokeWith, String packageName, long[] disabledCompatChanges, String[] zygoteArgs) {
    //ZYGOTE_PROCESS 在定义时就被初始化:ZYGOTE_PROCESS = new ZygoteProcess()
	return ZYGOTE_PROCESS.start(processClass, niceName, uid, gid, gids, runtimeFlags, mountExternal, targetSdkVersion, 
			seInfo, abi, instructionSet, appDataDir, invokeWith, packageName, true, disabledCompatChanges, zygoteArgs);
}

(9)start

​ /frameworks/base/core/java/android/os/ZygoteProcess.java

public final Process.ProcessStartResult start(final String processClass, final String niceName, int uid, int gid, int[] gids, 
		int runtimeFlags, int mountExternal, int targetSdkVersion, String seInfo, String abi, String instructionSet, String appDataDir, 
		String invokeWith, String packageName, boolean useUsapPool, long[] disabledCompatChanges, String[] zygoteArgs) {
	...
	try {
		return startViaZygote(processClass, niceName, uid, gid, gids, runtimeFlags, mountExternal, targetSdkVersion, seInfo,
				abi, instructionSet, appDataDir, invokeWith, false, packageName, useUsapPool, disabledCompatChanges, zygoteArgs);
	}
	...
}

(10)startViaZygote

​ /frameworks/base/core/java/android/os/ZygoteProcess.java

private Process.ProcessStartResult startViaZygote(final String processClass, final String niceName, final int uid, 
		final int gid, final int[] gids, int runtimeFlags, int mountExternal, int targetSdkVersion, String seInfo, String abi, 
		String instructionSet, String appDataDir, String invokeWith, boolean startChildZygote, String packageName, 
		boolean useUsapPool, long[] disabledCompatChanges, String[] extraArgs) throws ZygoteStartFailedEx {
    //保存启动应用进程的参数
	ArrayList<String> argsForZygote = new ArrayList<>();
	...
	argsForZygote.add("--setuid=" + uid);
	argsForZygote.add("--setgid=" + gid);
	argsForZygote.add("--runtime-flags=" + runtimeFlags);
	...
	argsForZygote.add(processClass);
	...
	synchronized(mLock) {
		return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), useUsapPool, argsForZygote);
	}
}

​ openZygoteSocketIfNeeded() 方法建立与 zygote 进程的 socket 连接,并返回一个 ZygoteState 对象(ZygoteState 类是 ZygoteProcess 的内部类)。

(11)openZygoteSocketIfNeeded

​ /frameworks/base/core/java/android/os/ZygoteProcess.java

private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
	try {
		attemptConnectionToPrimaryZygote(); //主模式
		if (primaryZygoteState.matches(abi)) {
			return primaryZygoteState;
		}
		if (mZygoteSecondarySocketAddress != null) {
			attemptConnectionToSecondaryZygote(); //辅模式
			if (secondaryZygoteState.matches(abi)) {
				return secondaryZygoteState;
			}
		}
	}
	...
}

private void attemptConnectionToPrimaryZygote() throws IOException {
	if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
		//建立 Socket 连接
		primaryZygoteState = ZygoteState.connect(mZygoteSocketAddress, mUsapPoolSocketAddress);
		...
	}
}

private void attemptConnectionToSecondaryZygote() throws IOException {
	if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
		//建立 Socket 连接
		secondaryZygoteState = ZygoteState.connect(mZygoteSecondarySocketAddress, mUsapPoolSecondarySocketAddress);
		...
	}
}

(12)connect

​ /frameworks/base/core/java/android/os/ZygoteProcess.ZygoteState.java

static ZygoteState connect(LocalSocketAddress zygoteSocketAddress, LocalSocketAddress usapSocketAddress) throws IOException {
	DataInputStream zygoteInputStream;
	BufferedWriter zygoteOutputWriter;
	final LocalSocket zygoteSessionSocket = new LocalSocket();
	...
	try {
        //请求与服务端(zygote 进程)建立 socket 连接
		zygoteSessionSocket.connect(zygoteSocketAddress); //请求连接过程中会阻塞
        //获取 socket 输入和输出流
		zygoteInputStream = new DataInputStream(zygoteSessionSocket.getInputStream());
		zygoteOutputWriter = new BufferedWriter(new OutputStreamWriter(zygoteSessionSocket.getOutputStream()), Zygote.SOCKET_BUFFER_SIZE);
	}
	...
	return new ZygoteState(zygoteSocketAddress, usapSocketAddress, zygoteSessionSocket, zygoteInputStream, 
							zygoteOutputWriter, getAbiList(zygoteOutputWriter, zygoteInputStream));
}

​ 注意: LocalSocket 是客户端(system_server 进程)的 socket,与服务端(zygote 进程)建立 socket 连接,实现跨进程通讯;zygoteSocketAddress 指向了服务端 socket 地址。

(13)zygoteSendArgsAndGetResult

​ /frameworks/base/core/java/android/os/ZygoteProcess.java

private Process.ProcessStartResult zygoteSendArgsAndGetResult(ZygoteState zygoteState, 
		boolean useUsapPool, ArrayList<String> args) throws ZygoteStartFailedEx {
	...
	String msgStr = args.size() + "\n" + String.join("\n", args) + "\n";
	...
	if (useUsapPool && mUsapPoolEnabled && canAttemptUsap(args)) {
		try {
			return attemptUsapSendArgsAndGetResult(zygoteState, msgStr);
		}
		...
	}
    //准备向服务端(zygote 进程)发送启动应用程序进程的参数
	return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);
}

(14)attemptZygoteSendArgsAndGetResult

​ /frameworks/base/core/java/android/os/ZygoteProcess.java

private Process.ProcessStartResult attemptZygoteSendArgsAndGetResult(
		ZygoteState zygoteState, String msgStr) throws ZygoteStartFailedEx {
	try {
		//通过 Socket 通讯将 msgStr 传送给服务端(zygote 进程)
		final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
		final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;
		zygoteWriter.write(msgStr);
		zygoteWriter.flush();
		//返回值
		Process.ProcessStartResult result = new Process.ProcessStartResult();
		result.pid = zygoteInputStream.readInt();
		result.usingWrapper = zygoteInputStream.readBoolean();
		...
		return result;
	}
	...
}

2.3 ZygoteInit 到 ActivityThread

​ 如图,绿色的类是在 zygote 进程中执行的,紫色的类是待启动应用进程中执行的,黄色的类是 Socket 跨进程通讯工具类。

img

(1)main

​ frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

public static void main(String argv[]) {
	ZygoteServer zygoteServer = null;
	...
	Runnable caller;
	try {
		...
		String zygoteSocketName = "zygote";
		...
		//Zygote.PRIMARY_SOCKET_NAME: "zygote"
		final boolean isPrimaryZygote = zygoteSocketName.equals(Zygote.PRIMARY_SOCKET_NAME);
		...
		//创建 zygote 服务类
		zygoteServer = new ZygoteServer(isPrimaryZygote);
		...
		//等待 AMS 请求
		caller = zygoteServer.runSelectLoop(abiList);
	}
	...
	if (caller != null) {
        //通过反射调用 ActivityThread 的 main() 方法
		caller.run();
	}
}

(2)ZygoteServer

​ frameworks/base/core/java/com/android/internal/os/ZygoteServer.java

ZygoteServer(boolean isPrimaryZygote) {
	...
	if (isPrimaryZygote) {
        //new LocalServerSocket(fd)
		mZygoteSocket = Zygote.createManagedSocketFromInitSocket(Zygote.PRIMARY_SOCKET_NAME); //"zygote"
		mUsapPoolSocket = Zygote.createManagedSocketFromInitSocket(Zygote.USAP_POOL_PRIMARY_SOCKET_NAME);
	} else {
        //new LocalServerSocket(fd)
		mZygoteSocket = Zygote.createManagedSocketFromInitSocket(Zygote.SECONDARY_SOCKET_NAME); //"zygote_secondary"
		mUsapPoolSocket = Zygote.createManagedSocketFromInitSocket(Zygote.USAP_POOL_SECONDARY_SOCKET_NAME);
	}
	...
}

​ 说明:LocalServerSocket 是 socket 通讯的服务端。

(3)runSelectLoop

​ frameworks/base/core/java/com/android/internal/os/ZygoteServer.java

Runnable runSelectLoop(String abiList) {
	...
	ArrayList<ZygoteConnection> peers = new ArrayList<>();
	...
	while (true) { //死循环,等待接收客户端消息
		...
		int pollIndex = 0;
		...
		while (--pollIndex >= 0) {
            ...
			if (pollIndex == 0) {
				//new ZygoteConnection(mZygoteSocket.accept(), abiList)
				ZygoteConnection newPeer = acceptCommandPeer(abiList);
				peers.add(newPeer);
				...
			} else if (pollIndex < usapPoolEventFDIndex) {
				try {
					ZygoteConnection connection = peers.get(pollIndex);
					final Runnable command = connection.processOneCommand(this);
					if (mIsForkChild) {
						...
						return command;
					}
					...
				}
				...
			}
			...
		}
		...
	}
}

​ 说明:acceptCommandPeer() 方法中,会执行 new ZygoteConnection(mZygoteSocket.accept(), abiList),其中,mZygoteSocket.accept() 用于监听来自客户端(system_server 进程)的 connect 请求(没请求会阻塞),并返回一个 LocalSocket 对象,通过该对象可以实现与客户端跨进程通讯。

(4)ZygoteConnection

​ frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java

ZygoteConnection(LocalSocket socket, String abiList) throws IOException {
	mSocket = socket;
	this.abiList = abiList;
	//获取 socket 输入和输出流
	mSocketOutStream = new DataOutputStream(socket.getOutputStream());
	mSocketReader = new BufferedReader(new InputStreamReader(socket.getInputStream()), Zygote.SOCKET_BUFFER_SIZE);
	...
}

(5)processOneCommand

​ frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java

Runnable processOneCommand(ZygoteServer zygoteServer) {
	String[] args;
	try {
		//通过 Socket 获取应用进程启动参数
		args = Zygote.readArgumentList(mSocketReader);
	}
	...
	//应用进程启动参数
	ZygoteArguments parsedArgs = new ZygoteArguments(args);
	...
	//创建应用进程
	pid = Zygote.forkAndSpecialize(parsedArgs.mUid, parsedArgs.mGid, parsedArgs.mGids,
			parsedArgs.mRuntimeFlags, rlimits, parsedArgs.mMountExternal, parsedArgs.mSeInfo,
			parsedArgs.mNiceName, fdsToClose, fdsToIgnore, parsedArgs.mStartChildZygote,
			parsedArgs.mInstructionSet, parsedArgs.mAppDataDir, parsedArgs.mTargetSdkVersion);
	try {
		if (pid == 0) { //新建的子进程
			zygoteServer.setForkChild();
			...
			//处理应用程序进程:将 ActivityThread 的 main() 方法封装到 Runnable 中
			return handleChildProc(parsedArgs, childPipeFd, parsedArgs.mStartChildZygote);
		}
		...
	}
	...
}

(6)readArgumentList

​ frameworks/base/core/java/com/android/internal/os/Zygote.java

static String[] readArgumentList(BufferedReader socketReader) throws IOException {
	int argc;
	try {
		String argc_string = socketReader.readLine();
		...
		//接收的数据行数
		argc = Integer.parseInt(argc_string);
	}
	...
	String[] args = new String[argc];
	for (int arg_index = 0; arg_index < argc; arg_index++) {
		args[arg_index] = socketReader.readLine();
		...
	}
	return args;
}

(7)handleChildProc

​ frameworks/base/core/java/com/android/internal/os/ZygoteConnection.java

private Runnable handleChildProc(ZygoteArguments parsedArgs, FileDescriptor pipeFd, boolean isZygote) {
	...
	if (parsedArgs.mInvokeWith != null) {
		...
	} else {
		if (!isZygote) {
			return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion, parsedArgs.mDisabledCompatChanges, parsedArgs.mRemainingArgs, null);
		} else {
			return ZygoteInit.childZygoteInit(parsedArgs.mTargetSdkVersion, parsedArgs.mRemainingArgs, null);
		}
	}
}

(8)zygoteInit

​ frameworks/base/core/java/com/android/internal/os/ZygoteInit.java

public static final Runnable zygoteInit(int targetSdkVersion, long[] disabledCompatChanges, String[] argv, ClassLoader classLoader) {
	...
	ZygoteInit.nativeZygoteInit(); //启动 Binder 线程池
	return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv, classLoader);
}

​ 说明:ZygoteInit.nativeZygoteInit() 启动了 Binder 线程池,应用程序进程此后可以通过 Binder 实现跨进程通讯。

(9)applicationInit

​ frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

protected static Runnable applicationInit(int targetSdkVersion, long[] disabledCompatChanges, String[] argv, ClassLoader classLoader) {
	...
	final Arguments args = new Arguments(argv);
	...
	return findStaticMain(args.startClass, args.startArgs, classLoader);
}

(10)findStaticMain

​ frameworks/base/core/java/com/android/internal/os/RuntimeInit.java

protected static Runnable findStaticMain(String className, String[] argv, ClassLoader classLoader) {
	Class<?> cl;
	try {
		//获取 ActivityThread 类
		cl = Class.forName(className, true, classLoader);
	}
	...

	Method m;
	try {
		//获取 ActivityThread 的 main() 方法
		m = cl.getMethod("main", new Class[] { String[].class });
	}
	...
	return new MethodAndArgsCaller(m, argv);
}

(11)MethodAndArgsCaller

​ frameworks/base/core/java/com/android/internal/os/RuntimeInit.MethodAndArgsCaller.java

static class MethodAndArgsCaller implements Runnable {
	private final Method mMethod;
	private final String[] mArgs;

	public MethodAndArgsCaller(Method method, String[] args) {
		mMethod = method;
		mArgs = args;
	}

	public void run() {
		try {
            //通过反射调用 ActivityThread 的 main() 方法
			mMethod.invoke(null, new Object[] { mArgs });
		}
		...
	}
}

​ 由于 ActivityThread 的 main() 方法是静态方法,其调用不依赖于具体对象,因此 invoke(Object obj, Object... args) 方法的第一个参数为 null。封装好的 MethodAndArgsCaller,最终会返回给 ZygoteInit 的 main() 方法执行其 run() 方法。

2.4 ActivityThread 初始化

​ 如图,紫色的类是在待启动应用进程中执行的,深蓝色的类是 system_server 进程中执行的,黄色的类是指 AIDL 文件生成的接口(用于跨进程)。

img

(1)main

​ /frameworks/base/core/java/android/app/ActivityThread.java

public static void main(String[] args) {
	...
	//创建主线程 Looper
	Looper.prepareMainLooper();
	...
	ActivityThread thread = new ActivityThread();
    //第 1 个属性为 system,后面会用到
	thread.attach(false, startSeq);

	if (sMainThreadHandler == null) {
		//创建主线程 H 类:return mH, mH 在定义时就被初始化:final H mH = new H()
		sMainThreadHandler = thread.getHandler();
	}
	...
	//开启消息循环
	Looper.loop();
    ...
}

​ ActivityThread 的 main() 方法是应用程序进程启动的起点,在这里开启的消息循环(Looper),此后应用程序进程就可以实现跨线程通讯。

(2)构造方法

​ /frameworks/base/core/java/android/app/ActivityThread.java

ActivityThread() {
	//mResourcesManager 为 ResourcesManager 类
	mResourcesManager = ResourcesManager.getInstance();
}

(3)attach

​ /frameworks/base/core/java/android/app/ActivityThread.java

private void attach(boolean system, long startSeq) {
	sCurrentActivityThread = this;
	mSystemThread = system;
	if (!system) { //system  = false
		...
		//mAppThread 为 ApplicationThread 类型,在定义时就被初始化
		RuntimeInit.setApplicationObject(mAppThread.asBinder());
		//获取 AMS
		final IActivityManager mgr = ActivityManager.getService();
		try {
			mgr.attachApplication(mAppThread, startSeq);
		}
		...
	}
	...
}

(4)attachApplication

​ /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService****.java

public final void attachApplication(IApplicationThread thread, long startSeq) {
	synchronized (this) {
		int callingPid = Binder.getCallingPid();
		final int callingUid = Binder.getCallingUid();
		...
		attachApplicationLocked(thread, callingPid, callingUid, startSeq);
		...
	}
}

(5)attachApplicationLocked

​ /frameworks/base/services/core/java/com/android/server/am/ActivityManagerService****.java

private final boolean attachApplicationLocked(IApplicationThread thread, int pid, int callingUid, long startSeq) {
	ProcessRecord app;
	...
	try {
		...
		final ActiveInstrumentation instr2 = app.getActiveInstrumentation();
		if (mPlatformCompat != null) {
			...
		}
		if (app.isolatedEntryPoint != null) {
			...
		} else if (instr2 != null) {
			thread.bindApplication(processName, appInfo, providers, instr2.mClass, profilerInfo, instr2.mArguments,
					instr2.mWatcher, instr2.mUiAutomationConnection, testMode, mBinderTransactionTrackingEnabled, 
					enableTrackAllocation, isRestrictedBackupMode || !normalMode, app.isPersistent(),
					new Configuration(app.getWindowProcessController().getConfiguration()), app.compat, 
					getCommonServicesLocked(app.isolated), mCoreSettingsObserver.getCoreSettingsLocked(),
					buildSerial, autofillOptions, contentCaptureOptions, app.mDisabledCompatChanges);
		} else {
			//第 4 个参数为 ComponentName 类型,影响 Instrumentation 的创建方式
			thread.bindApplication(processName, appInfo, providers, null, profilerInfo, null, null, null, testMode,
					mBinderTransactionTrackingEnabled, enableTrackAllocation, isRestrictedBackupMode || !normalMode, 
					app.isPersistent(), new Configuration(app.getWindowProcessController().getConfiguration()),
					app.compat, getCommonServicesLocked(app.isolated), mCoreSettingsObserver.getCoreSettingsLocked(),
					buildSerial, autofillOptions, contentCaptureOptions, app.mDisabledCompatChanges);
            }
		...
		app.makeActive(thread, mProcessStats);
	}
	...
}

​ 说明: getCommonServicesLocked() 方法中将 WMS、DMS、IMS、PMS 等服务的 name 和 binder 添加到 mAppBindArgs(类型:ArrayMap<String, IBinder>)中,并将其返回。

(6)bindApplication

​ /frameworks/base/core/java/android/app/ActivityThread.****ApplicationThread.java

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 services, Bundle coreSettings,
		String buildSerial, AutofillOptions autofillOptions, ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
	if (services != null) {
		...
		// sCache.putAll(services), sCache 为 Map<String, IBinder> 类型
		ServiceManager.initServiceCache(services);
	}
	//relaunchAllActivities(false)
	setCoreSettings(coreSettings);
	AppBindData data = new AppBindData();
    ...
    data.instrumentationName = instrumentationName;
	...
    //ActivityThread 的内部类 H 类处理消息,将业务从 Binder 线程切换至主线程
	sendMessage(H.BIND_APPLICATION, data);
}

​ 说明:services 为 AMS 中传递过来的 mAppBindArgs 对象(类型:ArrayMap<String, IBinder>)

(7)handleMessage

​ /frameworks/base/core/java/android/app/ActivityThread.****H.java

public void handleMessage(Message msg) {
	...
	switch (msg.what) {
		case BIND_APPLICATION:
			...
			AppBindData data = (AppBindData)msg.obj;
			handleBindApplication(data);
			...
			break;
		...
	}
	...
}

(8)handleBindApplication

​ /frameworks/base/core/java/android/app/ActivityThread.java

private void handleBindApplication(AppBindData data) {
	...
	final InstrumentationInfo ii;
	...
	//创建 Application 的 Context
	final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
	...
	//ii 是否为 null,取决于 data.instrumentationName 是否为 null
	if (ii != null) {
		...
		//创建 Instrumentation 的 Context
		final ContextImpl instrContext = ContextImpl.createAppContext(this, pi, appContext.getOpPackageName());
		try {
			final ClassLoader cl = instrContext.getClassLoader();
			mInstrumentation = (Instrumentation) cl.loadClass(data.instrumentationName.getClassName()).newInstance();
		}
		...
		//注入 ActivityThread、Context、ComponentName 等
		mInstrumentation.init(this, instrContext, appContext, component, data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
		...
	} else {
		mInstrumentation = new Instrumentation();
		//注入 ActivityThread
		mInstrumentation.basicInit(this);
	}
	...
	Application app;
	...
	try {
		//创建 Application 对象
		app = data.info.makeApplication(data.restrictedBackupMode, null);
		...
		mInitialApplication = app;
		...
		try {
			mInstrumentation.onCreate(data.instrumentationArgs);
		}
		...
		try {
			//调用 Application 的 onCreate() 方法
			mInstrumentation.callApplicationOnCreate(app);
		}
		...
	}
	...
}

​ 声明:本文转自【framework】应用进程启动流程

标签:...,java,String,int,流程,final,framework,进程,app
From: https://www.cnblogs.com/zhyan8/p/17233657.html

相关文章

  • 【framework】InputChannel创建流程
    1前言IMS启动流程中介绍了IMS在Java层和Native层的初始化流程,以及创建NativeInputManager、InputManager、InputReader、InputDispatcher、EventHub等对象......
  • 【framework】surfaceflinger启动流程
    1前言​surfaceflinger的作用是合成来自WMS的Surface数据,并发送到显示设备。​SurfaceFlinger服务不同于AMS、WMS、IMP、PMS、DMS等服务,主要区别如下:......
  • 【Android】使用ContentProvider实现跨进程通讯
    1前言​ContentProvider即内容提供器,是Android四大组件之一,为App存取数据提供统一的对外接口,让不同的应用之间可以共享数据。​如图,Server端通过Content......
  • 温习:进程和线程的区别
    进程和线程的区别:1、定义不一样,进程是执行中的一段程序,线程是进程里执行中的任务,一个进程里可以有多个线程。2、一个线程只能属于一个进程。3、线程无地址空间,它包括在......
  • 第二章 - 进程
    2.1进程的定义、组成、组织、特征:2.1.1进程的定义:程序:一个指令序列定义:进程是进程实体的运行过程,是系统进行资源分配和调度的一个独立单位单道程序:一次只能处理......
  • Day 17 17.4 多进程实现
    多进程实现由于GIL的存在,python中的多线程其实并不是真正的多线程,如果想要充分地使用多核CPU的资源,在python中大部分情况需要使用多进程。multiprocessing包是Python......
  • java的流程控制-break continue
    breakcontinuebreak:在任何循环语句的主体部分,均可用break控制循环的流程。break用于强行退出循环,不执行循环中剩余的语句。(break也在switch语句中使用) continue:在......
  • Vue.js props配置(微信收款确认流程)
    视频直接修改外来数据props会产生警告props配置项1.功能:让组件接收外部传过来的数据2.传递数据:```<Demoname="xxx"/>```3.接收数据:1.第一种方式(只接收......
  • Linux进程调度的思考
    a.进程怎么载入到CPU中运行?b.当前进程正在运行,怎么确定是否要切换下一个进程?c.怎么选出下一个进程?d.选择进程的算法和优先级?e.介绍一下常用的算法调度逻辑?f.从......
  • java流程控制
    java流程控制Scanner对象通过新建Scanner类来获取用户的输入基本语法:Scannerscanner=newScanner(system.in)Stringstr=scanner.nextLine(),inti=scanner.ne......