首先明确两个概念:
1、init进程:是Linux内核启动的第一个用户级进程。主要有两个作用:a、启动Android系统的关键服务;b、作为上述关键服务的守护进程,确保不被杀死(通过socket的方式完成进程间通信,init进程会不断给每一个关键服务发送消息,正常情况下,init进程的read()方法会处于阻塞状态;如果某个关键服务被杀死,那么init进程的read()方法就会读取到这一状态,从而重启该服务)。需要特殊说明的是:init进程并不能重启所有的关键服务,比如zygote进程会孵化很多app进程,如果这样的进程被系统杀死,那么是无法通过init重启的,此时只能通过重启Android系统来解决
2、init进程和Android的关系:当Linux内核启动之后,通过启动用户级的init进程,来引导Android Framework的建立。因此init总是第一个进程,它的进程号固定为1
接下来,进入正题,先来一张图:
zygote启动后,会通过PMS进程扫描/data/app目录下所有的.apk文件,将AndroidManifest.xml的所有标签信息存档,从而建立一个缓存中心(Packages)
最后,看一下源代码:
main函数作为进程的入口,自然要从这里看起
public static PackageManagerService main (Context context, Installer installer, boolean factoryTest, boolean onlyCore) {
// Self-check for initial settings.
PackageManagerServiceCompilerMapping.checkProperties();
// 1、创建PMS对象
PackageManagerService m = new PackageManagerService(context, installer, factoryTest, onlyCore);
// 2、添加到ServiceManager中
ServiceManager.addService("package", m);
return m;
}
main()函数比较简单,首先创建PMS对象,然后添加到ServiceManager中。然后我们看一下PackageManagerService的构造方法:
/** Directory where installed applications are stored */
private static final FilesAppInstallDir = new File(Environment.getDataDirectory(), "app"); // /data/app目录
public PackageManagerService(Context context, Installer installer, boolean factoryTest, boolean onlyCore) {
......
scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
......
}
private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) {
scanDirLI(scanDir, parseFlags, scanFlags, currentTime);
}
private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) {
for (File file : files) {
final boolean isPackage = (isApkFile(file) || file.isDirectory()) && !PackageInstallerService.isStageName(file.getName());
if (!isPackage) {
// Ignore entries which are not packages continue;
continue;
}
parallelPackageParser.submit(file, parseFlags);
}
}
public void submit(File scanFile, int parseFlags) {
mService.submit(() -> {
ParseResult pr = new ParseResult();
try {
PackageParser pp = new PackageParser();
pp.setSeparateProcesses(mSeparateProcesses);
pp.setOnlyCoreApps(mOnlyCore);
pp.setDisplayMetrics(mMetrics);
pp.setCacheDir(mCacheDir);
pp.setCallback(mPackageParserCallback);
pr.scanFile = scanFile;
pr.pkg = parsePackage(pp, scanFile, parseFlags);
}catch (Throwable e) {
pr.throwable = e;
} finally {
Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
}
}
@VisibleForTestingprotected
PackageParser.Package parsePackage(PackageParser packageParser, File scanFile, int parseFlags) throws PackageParser.PackageParserException {
return packageParser.parsePackage(scanFile, parseFlags, true /* useCaches */);
}
public Package parsePackage(File packageFile, int flags, boolean useCaches) throws PackageParserException {
if (packageFile.isDirectory()) { // 显然packageFile就是扫描到的.apk文件
parsed = parseClusterPackage(packageFile, flags);
} else {
parsed = parseMonolithicPackage(packageFile, flags);
}
}
@Deprecatedpublic
Package parseMonolithicPackage(File apkFile, int flags) throws PackageParserException {
Package pkg = parseBaseApk(apkFile, assetLoader.getBaseAssetManager(), flags);
pkg.setCodePath(apkFile.getCanonicalPath());pkg.setUse32bitAbi(lite.use32bitAbi);
return pkg;
}
/** File name in an APK for the Android manifest. */
public static final String ANDROID_MANIFEST_FILENAME = "AndroidManifest.xml";
private Package parseBaseApk(File apkFile, AssetManager assets, int flags) throws PackageParserException {
XmlResourceParser parser = null;
int cookie = assets.findCookieForPath(apkPath);
parser = assets.openXmlResourceParser(cookie, ANDROID_MANIFEST_FILENAME);
Resources res = new Resources(assets, mMetrics, null);
String[] outError = new String[1];
Package pkg = parseBaseApk(apkPath, res, parser, flags, outError);
}
private Package parseBaseApk(String apkPath, Resources res, XmlResourceParser parser, int flags, String[] outError) {
return parseBaseApkCommon(pkg, null, res, parser, flags, outError);
}
private static final String TAG_MANIFEST = "manifest";
private static final String TAG_APPLICATION = "application";
private static final String TAG_PACKAGE_VERIFIER = "package-verifier";
private static final String TAG_OVERLAY = "overlay";
private static final String TAG_KEY_SETS = "key-sets";
private static final String TAG_PERMISSION_GROUP = "permission-group";
private static final String TAG_PERMISSION = "permission";
private static final String TAG_PERMISSION_TREE = "permission-tree";
private static final String TAG_USES_PERMISSION = "uses-permission";
private static final String TAG_USES_PERMISSION_SDK_M = "uses-permission-sdk-m";
private Package parseBaseApkCommon(Package pkg, SetacceptedTags, Resources res, XmlResourceParser parser, int flags, String[] outError) {
if (tagName.equals("activity")) {
// 此处的Activity extends Componentimplements Parcelable,它不是四大组件,位于PackageParser包
Activity a = parseActivity(owner, res, parser, flags, outError, cachedArgs, false, owner.baseHardwareAccelerated);
owner.activities.add(a);
} else if (tagName.equals("receiver")) {
// 在AndroidManifest.xml中,Activity和Receiver的标签属性一样,所以Google使用了相同的数据对象
Activity a = parseActivity(owner, res, parser, flags, outError, cachedArgs, true, false);
owner.receivers.add(a);
} else if (tagName.equals("service")) {
Service s = parseService(owner, res, parser, flags, outError, cachedArgs);
owner.services.add(s);
} else if (tagName.equals("provider")) {
Provider p = parseProvider(owner, res, parser, flags, outError, cachedArgs);
owner.providers.add(p);
} else if (tagName.equals("activity-alias")) {
Activity a = parseActivityAlias(owner, res, parser, flags, outError, cachedArgs);
owner.activities.add(a);
}
}
至此,Android启动流程也就基本结束了!