点击上方胡飞洋可以关注哦~
最近在了解插件化技术:把未安装的插件apk 集成到 宿主App中,以取得减少宿主APK包体积等优点。也就是说,一个完整的APK 虽然不经过安装过程,但使用了插件化技术后却可以在宿主中使用其功能。
那么对应的,一个APK的完整安装过程是怎样的呢?用户通常能体验到的安装过程有两种:
image.png
先下载APK,然后是安装过程,过程中没有跳转到其他页面,可以说是一键安装。
image.png
这种通常是用户下载一个APK文件,然后手动点击,跳转到安装页面,提示这个APK的下载信息等,然后是安装包详情页面,展示 版本号、所需权限 等一些信息,最后是安装中的页面。我使用的是小米手机,对应的Activity信息如下,这其中PermissionInfoActivity是点击“应用权限”的权限详情页面。
com.miui.packageinstaller/com.miui.packageInstaller.NewPackageInstallerActivity: +220ms
com.miui.packageinstaller/com.miui.packageInstaller.NormalInstallReadyActivity: +97ms
com.miui.packageinstaller/com.android.packageinstaller.miui.PermissionInfoActivity: +97ms
com.miui.packageinstaller/com.miui.packageInstaller.InstallProgressActivity: +99ms
发现整个安装过程是执行在小米系统miui的"com.miui.packageinstaller"中,那么可想而知在原生Android系统也有对应的Activity。
APK包体越大,安装时间就越长,因为需要解析和校验的越多。无论哪种方式,安装完成后都会通知到 桌面应用Launcher,Launcher在桌面上添加一个App图标。这就是用户感受到的安装过程。
好了,APK安装过程 就讲完了!
—— 并没有😄,APK安装具体过程是怎样的?我们是Android应用开发者,read the source code!
阅读源码是一件痛苦的事情,一般需要结合其他资料一起理解。并且,重点掌握整体流程即可。
我们先来了解一个类:PackageManagerService(PMS),通过名字 你可能会想起 和四大组件紧密相关的 ActivityManagerService(AMS),它俩都是运行在SystemServer进程,App端和AMS、PMS进行交互都是通过Binder跨进程完成。AMS负责Activity等四大组件的管理,而PMS则负责 包package 的管理,APK的全称是Android Package,即PMS的作用就是管理APK。
除了这里的PMS,在之前相关文章中还介绍了 ActivityManagerService(AMS)、WindowManagerService(WMS)。
在平时开发中,我们会需要获取当前已安装的包的相关信息,例如已安装应用列表等,就可以在Activity中这么写:
PackageManager packageManager = getPackageManager();
// 获取所有已安装程序的包信息
List<PackageInfo> packages = packageManager.getInstalledPackages(0);
getPackageManager() 实际是Context的方法,具体实现是 ContextImpl 中:
@Override
public PackageManager getPackageManager() {
if (mPackageManager != null) {
return mPackageManager;
}
final IPackageManager pm = ActivityThread.getPackageManager();
final IPermissionManager permissionManager = ActivityThread.getPermissionManager();
if (pm != null && permissionManager != null) {
// Doesn't matter if we make more than one instance.
return (mPackageManager = new ApplicationPackageManager(this, pm, permissionManager));
}
return null;
}
注意获取到的 PackageManager 实际是 ApplicationPackageManager,构造方法中传入了 通过 ActivityThread 获取的 IPackageManager、IPermissionManager。并且查看ApplicationPackageManager,会发现 基本所有方法都是对 传入的 pm的封装:
public List<PackageInfo> getInstalledPackagesAsUser(int flags, int userId) {
try {
//调用PM的对应方法
ParceledListSlice<PackageInfo> parceledList =
mPM.getInstalledPackages(updateFlagsForPackage(flags, userId), userId);
if (parceledList == null) {
return Collections.emptyList();
}
return parceledList.getList();
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
我们再看看 ActivityThread.getPackageManager() 如何获取 IPackageManager :
public static IPackageManager getPackageManager() {
if (sPackageManager != null) {
return sPackageManager;
}
final IBinder b = ServiceManager.getService("package");
sPackageManager = IPackageManager.Stub.asInterface(b);
return sPackageManager;
}
到这里如果你对AMS的跨进程(IPC)比较熟,就会知道 这里同样是 为了IPC,即获取 SystemServer中 PMS 在App端的代理 IPackageManager。也就说,上面在Activity中通过getPackageManager()获取已安装应用列表,最后是IPC到了系统进程,在 PMS 中执行。类图如下:
image.png
那么 PMS 什么时候完成初始化的呢?因为 所有App运行都需要 这些系统服务,所以必然是 系统开机的时候 完成 PMS、AMS这些的初始化:
//SystemServer.java
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
...
// Here we go!
Slog.i(TAG, "Entered the Android system server!");
...
// Prepare the main looper thread (this thread).
Looper.prepareMainLooper();
...
// Start services.
startBootstrapServices(t); //系统开启中 具有复杂相互依赖性的 关键服务
startCoreServices(t); //没有复杂依赖的核心服务
startOtherServices(t); //其他服务
...
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
在开机系统启动时,zygote 进程会fork一个 SystemServer 进程然后执行上面main方法,这里进行大量的初始化,其中就包括 启动各种服务。这里我们看startBootstrapServices():
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
...
// Installer
Installer installer = mSystemServiceManager.startService(Installer.class);
...
//AMS
mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
mActivityManagerService.setInstaller(installer);
...
//PMS
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
...
}
发现这里开启了 AMS、PMS,并且都使用了Installer。Installer 看名字像是安装器,后面再做介绍。PMS的main方法内用构造方法创建了PMS实例,而它的构造方法内容特别多,我们关注其中一句调用scanDirTracedLI():
/** data/app,已安装app的目录 */
private static final File sAppInstallDir = new File(Environment.getDataDirectory(), "app");
public PackageManagerService(Injector injector, boolean onlyCore, boolean factoryTest){
...
//读取packages.xml中 上次的包信息,解析后将数据存放到mSettings中
mFirstBoot = !mSettings.readLPw(mInjector.getUserManagerInternal().getUsers(false));
...
//扫描 data/app
scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0,packageParser, executorService);
...
//把新的 mSettings 内容更新到 packages.xml
mSettings.writeLPr();
...
}
packages.xml
:记录系统中 所有安装的应用信息,包括基本信息、签名和权限。mSettings
:用来保存和PMS相关的一些设置,它保存的内容在解析应用时会用到。先读取packages.xml文件,解析后将数据存放到mSettings中,代表上次启动时的应用包信息。然后扫描所有APK目录并解析APK,最后更新packages.xml文件。而 packages.xml文件 是在 Settings 构造方法中创建。
data/app 是用户已安装App所在的目录,另外还有system/app存放 系统App。PMS构造方法中会对 这两个目录在内的多个目录进行扫描,我们这里可以猜想到这是开机时对所有已安装App的初始化。scanDirTracedLI()又走到scanDirLI(),那么就来详细看看怎么扫描的:
private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime,
PackageParser2 packageParser, ExecutorService executorService) {
...
ParallelPackageParser parallelPackageParser = new ParallelPackageParser(packageParser, executorService);
//并行解析所有package
for (File file : files) {
parallelPackageParser.submit(file, parseFlags);
}
...
//处理解析结果
for (; fileCount > 0; fileCount--) {
ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take();
addForInitLI(parseResult.parsedPackage, parseFlags, scanFlags, currentTime, null);
}
...
}
使用 ParallelPackageParser 对目录内的所有apk进行解析 然后使用 addForInitLI()处理解析结果parseResult。ParallelPackageParser 实际是对 PackageParser2 的使用上的封装,APK解析操作会走到 PackageParser2 的 parsePackage():
//PackageParser2.java
public ParsedPackage parsePackage(File packageFile, int flags, boolean useCaches) {
...
ParseResult<ParsingPackage> result = parsingUtils.parsePackage(input, packageFile, flags);
ParsedPackage parsed = (ParsedPackage) result.getResult().hideAsParsed();
...
return parsed;
}
这里parsingUtils 是 ParsingPackageUtils 的实例,继续看parsingUtils.parsePackage():
//ParsingPackageUtils.java
public ParseResult<ParsingPackage> parsePackage(ParseInput input, File packageFile,int flags){
//两个分支 都会走到parseBaseApk()
if (packageFile.isDirectory()) { //是目录
return parseClusterPackage(input, packageFile, flags);
} else {
return parseMonolithicPackage(input, packageFile, flags);
}
}
两个分支 都会走到parseBaseApk():
private ParseResult<ParsingPackage> parseBaseApk(ParseInput input, File apkFile,String codePath, AssetManager assets, int flags) {
...
XmlResourceParser parser = assets.openXmlResourceParser(cookie,PackageParser.ANDROID_MANIFEST_FILENAME)) {
final Resources res = new Resources(assets, mDisplayMetrics, null);
ParseResult<ParsingPackage> result = parseBaseApk(input, apkPath, codePath, res,parser, flags);
...
}
这里创建了 XmlResourceParser 实例,适用于解析APK的AndroidManifest.xml 文件,然后调用了重载的parseBaseApk():
private ParseResult<ParsingPackage> parseBaseApk(ParseInput input, String apkPath,
String codePath, Resources res, XmlResourceParser parser, int flags){
...
//创建ParsingPackage实例 用于承接解析结果
final ParsingPackage pkg = mCallback.startParsingPackage(pkgName, apkPath, codePath, manifestArray, isCoreApp);
//解析apk 结果存入 pkg,包括 所有的activity、sevice等信息
final ParseResult<ParsingPackage> result = parseBaseApkTags(input, pkg, manifestArray, res, parser, flags);
return input.success(pkg);
...
}
parseBaseApkTags()内部使用 XmlResourceParser 查找 AndroidManifest.xml中的 Application 标签,然后调用 parseBaseApplication() 来解析 APK中的基础 Application 节点树:
private ParseResult<ParsingPackage> parseBaseApplication(ParseInput input, ParsingPackage pkg, Resources res, XmlResourceParser parser, int flags){
...
//解析Application标签的属性:theme、AllowBackup 这些
parseBaseAppBasicFlags(pkg, sa);
...
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT && (type != XmlPullParser.END_TAG || parser.getDepth() > depth)) {
...
final ParseResult result;
String tagName = parser.getName();
boolean isActivity = false;
switch (tagName) {
case "activity":
isActivity = true;
case "receiver":
ParseResult<ParsedActivity> activityResult = ParsedActivityUtils.parseActivityOrReceiver(mSeparateProcesses, pkg, res, parser, flags, PackageParser.sUseRoundIcon, input);
if (activityResult.isSuccess()) {
ParsedActivity activity = activityResult.getResult();
if (isActivity) {
hasActivityOrder |= (activity.getOrder() != 0);
pkg.addActivity(activity); //添加Activity
} else {
hasReceiverOrder |= (activity.getOrder() != 0);
pkg.addReceiver(activity);//添加Receiver
}
}
result = activityResult;
break;
case "service":
ParseResult<ParsedService> serviceResult =
ParsedServiceUtils.parseService(mSeparateProcesses, pkg, res, parser, flags, PackageParser.sUseRoundIcon, input);
if (serviceResult.isSuccess()) {
ParsedService service = serviceResult.getResult();
hasServiceOrder |= (service.getOrder() != 0);
pkg.addService(service); //添加Service
}
result = serviceResult;
break;
case "provider":
ParseResult<ParsedProvider> providerResult = ParsedProviderUtils.parseProvider(mSeparateProcesses, pkg, res, parser, flags, PackageParser.sUseRoundIcon, input);
if (providerResult.isSuccess()) {
pkg.addProvider(providerResult.getResult());//添加Provider
}
result = providerResult;
break;
...
}...
}
...
return input.success(pkg);
}
这里就是解析Application的子节点——四大组件,并把信息存入ParsingPackage实例pkg中,最后转成 ParallelPackageParser.ParseResult。那么再回到 PMS构造方法,解析后调用了 addForInitLI(),这个方法逻辑复杂,有很多对系统应用的校验(包名修改、版本升级、签名手收集和校验),但我们只关注下面内容:
//PMS.java
private AndroidPackage addForInitLI(ParsedPackage parsedPackage,@ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime,@Nullable UserHandle user){
...
//继续扫描
final ScanResult scanResult = scanPackageNewLI(parsedPackage, parseFlags, scanFlags | SCAN_UPDATE_SIGNATURE, currentTime, user, null);
if (scanResult.success) {
synchronized (mLock) {
boolean appIdCreated = false;
try {
final String pkgName = scanResult.pkgSetting.name;
final Map<String, ReconciledPackage> reconcileResult = reconcilePackagesLocked(new ReconcileRequest( Collections.singletonMap(pkgName, scanResult), mSharedLibraries, mPackages, Collections.singletonMap(pkgName, getSettingsVersionForPackage(parsedPackage)), Collections.singletonMap(pkgName, getSharedLibLatestVersionSetting(scanResult))),mSettings.mKeySetManagerService);
appIdCreated = optimisticallyRegisterAppId(scanResult);
//提交包扫描结果、更新系统状态
commitReconciledScanResultLocked(reconcileResult.get(pkgName), mUserManager.getUserIds());
}
...
}
}...
return scanResult.pkgSetting.pkg;
}
调用scanPackageNewLI()继续扫描,主要是更新 packageSetting(PackageSetting主要包含了一个APP的基本信息,如安装位置,lib位置等信息)。然后调用reconcilePackagesLocked()进行一致化处理,调用commitReconciledScanResultLocked() 提交包扫描结果、更新系统状态,内部又调用了commitPackageSettings():
//向系统添加扫描完成的包。那么这个包对于系统成为可用状态。
private void commitPackageSettings(AndroidPackage pkg,@Nullable AndroidPackage oldPkg, PackageSetting pkgSetting,inal @ScanFlags int scanFlags, booleanchatty,ReconciledPackage reconciledPkg) {
final String pkgName = pkg.getPackageName();
...
synchronized (mLock) {
//添加到mSettings
mSettings.insertPackageSettingLPw(pkgSetting, pkg);
//添加到mPackages
mPackages.put(pkg.getPackageName(), pkg);
//添加组件到mComponentResolver:所有的四大组件信息添加到内部数据结构中
mComponentResolver.addAllComponents(pkg, chatty);
...
//记录权限到PermissionManagerService中
mPermissionManager.addAllPermissions(pkg, chatty);
...
//添加mInstrumentation
for (i = 0; i < collectionSize; i++) {
ParsedInstrumentation a = pkg.getInstrumentations().get(i);
a.setPackageName(pkg.getPackageName());
mInstrumentation.put(a.getComponentName(), a);...
}
...
}
也就是包信息记录在了PMS的属性中。也就是说,系统启动后,包信息记录在了PMS管理的内存中。
小结一下,系统启动后创建并启动了PMS,并且PMS完成了对所有存在APK的目录进行了扫描,解析所有APK的AndroidManifest.xml,然后进一步扫描APK 最后提交包扫描结果到 PMS 的属性中。
以上就是对 开机启动时 APK安装流程 的简单理解。那么,下面就来看看 APK安装普通流程。
上面提到,普通的应用安装过程 是执行在小米系统miui的"com.miui.packageinstaller"中,安装过程涉及几个Activity,我们来看看 如何使用代码 安装一个APK文件,以及原生Android系统是哪些Activity。
安装APK的代码如下:
File file = new File(getExternalFilesDir(null), "xxx.apk");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri apkUri =FileProvider.getUriForFile(this, "com.xxx.xxx.fileprovider", file);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
startActivity(intent);
Action是Intent.ACTION_VIEW,type是"application/vnd.android.package-archive",这次使用 api 30的 原生模拟器,Activity信息如下:
com.google.android.packageinstaller/com.android.packageinstaller.InstallStaging: +349ms
com.google.android.packageinstaller/com.android.packageinstaller.PackageInstallerActivity: +1s516ms
com.android.settings/.Settings$ManageAppExternalSourcesActivity: +385ms
com.google.android.packageinstaller/com.android.packageinstaller.InstallInstalling: +296ms
com.google.android.packageinstaller/com.android.packageinstaller.InstallSuccess: +375ms
过程截图如下:
image.png
我们从InstallStaging开始看起:
public class InstallStaging extends AlertActivity {
private @Nullable StagingAsyncTask mStagingTask;
private @Nullable File mStagedFile;
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState); ...
setupAlert(); //展示ui ...
}
protected void onResume() {...
mStagingTask = new StagingAsyncTask();
mStagingTask.execute(getIntent().getData()); //开启AsyncTask 读取 apk文件
}
}
protected void onSaveInstanceState(Bundle outState) {
outState.putString(STAGED_FILE, mStagedFile.getPath());
}
...
private final class StagingAsyncTask extends AsyncTask<Uri, Void, Boolean> {
protected Boolean doInBackground(Uri... params) {...
try (InputStream in = getContentResolver().openInputStream(packageUri)) {
...
try (OutputStream out = new FileOutputStream(mStagedFile)) {
byte[] buffer = new byte[1024 * 1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) >= 0) {...
out.write(buffer, 0, bytesRead);...
}
protected void onPostExecute(Boolean success) {
if (success) {
// Now start the installation again from a file
Intent installIntent = new Intent(getIntent());
installIntent.setClass(InstallStaging.this, DeleteStagedFileOnResult.class);
installIntent.setData(Uri.fromFile(mStagedFile));
if (installIntent.getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) {
installIntent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
}
installIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(installIntent); //读取完成后,启动 DeleteStagedFileOnResult
InstallStaging.this.finish();
} ...
}
}
}
只做了一件事,开启AsyncTask 读取 apk文件,然后 启动了activity DeleteStagedFileOnResult,这是个跳板页面,里面直接透传 intent 启动了 PackageInstallerActivity:
public class PackageInstallerActivity extends AlertActivity {
...
private int mSessionId = -1;
PackageManager mPm;
IPackageManager mIpm;...
PackageInstaller mInstaller;
PackageInfo mPkgInfo; //解析apk得到的PackageInfo
...
protected void onCreate(Bundle icicle) {
...
mPm = getPackageManager(); //ApplicationPackageManager
mInstaller = mPm.getPackageInstaller(); // mInstaller,安装器
final Intent intent = getIntent();
final Uri packageUri;
...
boolean wasSetUp = processPackageUri(packageUri); //解析APK
if (!wasSetUp) {
return;
}
// 初始化ui
bindUi();
//检查"未知来源安装",展示 安装确认 提示
checkIfAllowedAndInitiateInstall();
}
...
private boolean processPackageUri(final Uri packageUri) {
mPackageURI = packageUri;
final String scheme = packageUri.getScheme();
switch (scheme) {
...
case ContentResolver.SCHEME_FILE: {
File sourceFile = new File(packageUri.getPath());
//解析APK,注意参数是 GET_PERMISSIONS
mPkgInfo = PackageUtil.getPackageInfo(this, sourceFile,PackageManager.GET_PERMISSIONS);
//获取apk摘要:图标、名字
mAppSnippet = PackageUtil.getAppSnippet(this, mPkgInfo.applicationInfo, sourceFile);
...
} break;
...
}
return true;
}
//点击”安装“,跳转 InstallInstalling - 开始安装
private void startInstall() {
// Start subactivity to actually install the application
Intent newIntent = new Intent();
newIntent.putExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO, mPkgInfo.applicationInfo);
newIntent.setData(mPackageURI);
newIntent.setClass(this, InstallInstalling.class);
String installerPackageName = getIntent().getStringExtra( Intent.EXTRA_INSTALLER_PACKAGE_NAME);
...
if (installerPackageName != null) {
newIntent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, installerPackageName);
}
newIntent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivity(newIntent);
finish();
}
整体逻辑比较清晰:
我们先看包信息 PackageInfo 的解析过程——PackageUtil.getPackageInfo():
//PackageUtil.java
public static PackageInfo getPackageInfo(Context context, File sourceFile, int flags) {
...
return context.getPackageManager().getPackageArchiveInfo(sourceFile.getAbsolutePath(),flags);
}
继续看PackageManager的getPackageArchiveInfo():
//PackageManager.java
public PackageInfo getPackageArchiveInfo(@NonNull String archiveFilePath,@PackageInfoFlags int flags) {
...
ParseInput input = ParseTypeImpl.forParsingWithoutPlatformCompat().reset();
ParseResult<ParsingPackage> result = ParsingPackageUtils.parseDefault(input,
new File(archiveFilePath), 0, collectCertificates);
...
return PackageInfoWithoutStateUtils.generate(result.getResult(), null, flags, 0, 0, null,
new PackageUserState(), UserHandle.getCallingUserId());
}
调用了 ParsingPackageUtils 的静态方法parseDefault(),里面创建了 ParsingPackageUtils 实例,继续调用它的 parsePackage()。上面介绍的 PMS 构造方法中 解析APK 也是 ParsingPackageUtils的 parsePackage(),只是这里的 参数flags 是 PackageManager.GET_PERMISSIONS,只解析了权限信息。这里不再跟踪进去了。
最终解析 获取到了apk所有信息的 PackageInfo,然后 点击”安装“ 跳转到了 InstallInstalling。
直接看 InstallInstalling:
//两个逻辑:发送包到PMS、处理从PMS得到的安装结果
public class InstallInstalling extends AlertActivity {
...
//发送包到installer
private InstallingAsyncTask mInstallingTask;
//安装mSessionId
private int mSessionId;
...
protected void onCreate(@Nullable Bundle savedInstanceState) {
ApplicationInfo appInfo = getIntent().getParcelableExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO);
mPackageURI = getIntent().getData();
...
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
...
//安装结果监听。在收到安装结果的广播后 会调用此 Observer
mInstallId = InstallEventReceiver.addObserver(this, EventResultPersister.GENERATE_NEW_ID,this::launchFinishBasedOnResult);
...
//IPC:PackageInstaller 内部会通过 IPackageInstaller 走到PackageInstallerService 的 createSession 方法来创建
mSessionId = getPackageManager().getPackageInstaller().createSession(params);
...
}
}
...
protected void onResume() {
super.onResume();
if (mInstallingTask == null) {
PackageInstaller installer = getPackageManager().getPackageInstaller();
PackageInstaller.SessionInfo sessionInfo = installer.getSessionInfo(mSessionId);
if (sessionInfo != null && !sessionInfo.isActive()) {
//开启任务发送包信息到 session中,实际是
mInstallingTask = new InstallingAsyncTask();
mInstallingTask.execute();
}...
}
}
...
private void launchFinishBasedOnResult(int statusCode, int legacyStatus, String statusMessage) {
if (statusCode == PackageInstaller.STATUS_SUCCESS) {
launchSuccess(); //打开安装成功页面 InstallSuccess
} else {
launchFailure(legacyStatus, statusMessage); //安装失败页面 InstallFailed
}
}
...
//发送包到 installer
private final class InstallingAsyncTask extends AsyncTask<Void, Void,PackageInstaller.Session> {
@Override
protected PackageInstaller.Session doInBackground(Void... params) {
PackageInstaller.Session session;
...
session = getPackageManager().getPackageInstaller().openSession(mSessionId);
try {
File file = new File(mPackageURI.getPath());
try (InputStream in = new FileInputStream(file)) {
long sizeBytes = file.length();
//从session获取的输出流
try (OutputStream out = session.openWrite("PackageInstaller", 0, sizeBytes)) {
byte[] buffer = new byte[1024 * 1024];
while (true) {
int numRead = in.read(buffer);
...
out.write(buffer, 0, numRead);
if (sizeBytes > 0) {
float fraction = ((float) numRead / (float) sizeBytes);
session.addProgress(fraction);
}
}
return session;
}
...
}
@Override
protected void onPostExecute(PackageInstaller.Session session) {
if (session != null) {
Intent broadcastIntent = new Intent(BROADCAST_ACTION);
broadcastIntent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
broadcastIntent.setPackage(getPackageName());
broadcastIntent.putExtra(EventResultPersister.EXTRA_ID, mInstallId);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
InstallInstalling.this,mInstallId,broadcastIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
//包写入session后,进行提交
session.commit(pendingIntent.getIntentSender());
mCancelButton.setEnabled(false);
setFinishOnTouchOutside(false);
...
}
}
整体过程如下:
PackageInstaller,APK安装器,是在ApplicationPackageManager的 getPackageInstaller()中创建:
//是在ApplicationPackageManager的.java
public PackageInstaller getPackageInstaller() {
synchronized (mLock) {
if (mInstaller == null) {
mInstaller = new PackageInstaller(mPM.getPackageInstaller(), mContext.getPackageName(), getUserId());
...
}
return mInstaller;
}
}
是对 mPM.getPackageInstaller() 获取的 IPackageInstaller实例的封装,而 IPackageInstaller 在系统服务端的具体实现是 PackageInstallerService。
且 PackageInstallerService 的实例是在 PMS 的构造方法中创建的,初始化时会读取 /data/system 目录下的 install_sessions.xml 文件,这个文件中保存了系统中未完成的 Install Session。PMS 会根据文件的内容创建 PackageInstallerSession 对象并插入到 mSessions 中。
PackageInstaller 提供了 应用安装、更新、移除的能力,当然具体实现是 IPC 到了 PackageInstallerService中。
Session,是与 mSessionId绑定的安装会话,代表一个进行中的安装。Session类是对 IPackageInstaller.openSession(sessionId) 获取的 PackageInstallerSession(系统服务端)的封装。Session 管理安装的参数,并提供将安装包临时复制到特定路径(data/app-staging)的能力。
Session的创建和打开 具体实现是在 PackageInstallerService中,主要是 初始化apk的安装信息及环境,并创建一个sessionId,将安装Session与sessionId 进行绑定。(代码较多,就不放了)
我们重点看 把包信息写入mSessionId对应的session,然后提交
,回到 InstallInstalling 中,看到在 InstallingAsyncTask 中执行了对 APK包文件 的读取和写入操作,写入的输出流是 通过Session获取,也即是把 将APK文件写入了Session 。完成后 又调用了 session.commit(),具体实现是在PackageInstallerSession, 来看看:
//PackageInstallerSession.java
public void commit(@NonNull IntentSender statusReceiver, boolean forTransfer) {
...
dispatchStreamValidateAndCommit();
}
private void dispatchStreamValidateAndCommit() {
mHandler.obtainMessage(MSG_STREAM_VALIDATE_AND_COMMIT).sendToTarget();
}
发送了一个handler消息,最后执行在 handleStreamValidateAndCommit()中,然后里面又发送了消息MSG_INSTALL,这个执行在handleInstall():
private final Handler.Callback mHandlerCallback = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_STREAM_VALIDATE_AND_COMMIT:
handleStreamValidateAndCommit(); //
break;
case MSG_INSTALL:
handleInstall(); //
break;
...
}
return true;
}
};
private void handleInstall() {
...
List<PackageInstallerSession> childSessions = getChildSessionsNotLocked();
installNonStagedLocked(childSessions);
...
}
private void installNonStagedLocked(List<PackageInstallerSession> childSessions) {
final PackageManagerService.ActiveInstallSession installingSession = makeSessionActiveLocked();
...
//安装走到了 PMS 中
mPm.installStage(installingSession);
...
}
最后,安装过程走到了 PMS 的 installStage()。
目前为止,只是通过 PackageInstaller 维持了安装 Session,把安装包写入到 Session中,真正的安装过程是 PMS 来执行。
那就直接看 PMS 的 installStage():
//PMS
void installStage(ActiveInstallSession activeInstallSession) {
...
final Message msg = mHandler.obtainMessage(INIT_COPY);
final InstallParams params = new InstallParams(activeInstallSession);
msg.obj = params;
mHandler.sendMessage(msg);
}
mHandler 处理INIT_COPY是 params.startCopy():
//HandlerParams.java
final void startCopy() {
handleStartCopy();
handleReturnCode();
}
调用了两个方法实现是在 InstallParams 中:
public void handleStartCopy() {
int ret = PackageManager.INSTALL_SUCCEEDED;
...
PackageInfoLite pkgLite = null;
//解析包 返回最小的细节:pkgName、versionCode、安装所需空间大小、获取安装位置等
pkgLite = PackageManagerServiceUtils.getMinimalPackageInfo(mContext,origin.resolvedPath, installFlags, packageAbiOverride);
...
if (ret == PackageManager.INSTALL_SUCCEEDED) {
//以下是 获取安装位置失败情况
int loc = pkgLite.recommendedInstallLocation;
if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {//安装位置无效
ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
} else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {//已存在包
ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
} else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {//空间不够
ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
} else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {//apk无效
ret = PackageManager.INSTALL_FAILED_INVALID_APK;
} else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {//uri无效
ret = PackageManager.INSTALL_FAILED_INVALID_URI;
} else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {//
ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
} else {
...
}
final InstallArgs args = createInstallArgs(this);//安装参数
mVerificationCompleted = true;
mIntegrityVerificationCompleted = true;
mArgs = args;
//如果
if (ret == PackageManager.INSTALL_SUCCEEDED) {
final int verificationId = mPendingVerificationToken++;
//apk完整性校验
if (!origin.existing) {
PackageVerificationState verificationState =new PackageVerificationState(this);
mPendingVerification.append(verificationId, verificationState);
sendIntegrityVerificationRequest(verificationId, pkgLite, verificationState);
ret = sendPackageVerificationRequest(verificationId, pkgLite, verificationState);
...
}
...
mRet = ret; //赋值 returnCode
}
解析包返回最小的细节:pkgName、versionCode、安装所需空间大小;确认包安装位置;校验APK完整性。获取结果mRet。然后就看 handleReturnCode():
void handleReturnCode() {
if (mVerificationCompleted && mIntegrityVerificationCompleted && mEnableRollbackCompleted) {
...
//如果前面校验ok,这里执行apk拷贝
if (mRet == PackageManager.INSTALL_SUCCEEDED) {
mRet = mArgs.copyApk();
}
//执行安装
processPendingInstall(mArgs, mRet);
}
}
}
判断mRet,执行apk拷贝,然后执行安装。先看 mArgs.copyApk()如何拷贝:
//FileInstallArgs.java
int copyApk() {
return doCopyApk();
}
private int doCopyApk() {
//获取拷贝文件路径:/data/app
try {
final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0;
final File tempDir =
mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral);
codeFile = tempDir;
resourceFile = tempDir;
} catch (IOException e) {
Slog.w(TAG, "Failed to create copy file: " + e);
return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
}
//拷贝apk
int ret = PackageManagerServiceUtils.copyPackage(
origin.file.getAbsolutePath(), codeFile);
if (ret != PackageManager.INSTALL_SUCCEEDED) {
Slog.e(TAG, "Failed to copy package");
return ret;
}
final boolean isIncremental = isIncrementalPath(codeFile.getAbsolutePath());
final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
NativeLibraryHelper.Handle handle = null;
try {
handle = NativeLibraryHelper.Handle.create(codeFile);
//拷贝Native代码 即 .so文件
ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
abiOverride, isIncremental);
} catch (IOException e) {
Slog.e(TAG, "Copying native libraries failed", e);
ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
}...
return ret;
}
在FileInstallArgs中的copyApk()走到doCopyApk(),先获取了拷贝文件路径:/data/app,使用PackageManagerServiceUtils.copyPackage()进行APK拷贝,接着是 .so文件的拷贝。也就是说,把发送到 Session暂存目录 data/app-staging 的APK 拷贝到了 /data/app。
接着看执行安装processPendingInstall(mArgs, mRet):
//PMS.java
private void processPendingInstall(final InstallArgs args, final int currentStatus) {
...
//res,用于存 安装结果
PackageInstalledInfo res = createPackageInstalledInfo(currentStatus);
processInstallRequestsAsync(res.returnCode == PackageManager.INSTALL_SUCCEEDED,Collections.singletonList(new InstallRequest(args, res)));
...
}
//安装操作 使用handler入队
private void processInstallRequestsAsync(boolean success, List<InstallRequest>installRequests) {
mHandler.post(() -> {
if (success) {
for (InstallRequest request : installRequests) {
//安装前检验:returnCode不为INSTALL_SUCCEEDED就移除拷贝的apk等
request.args.doPreInstall(request.installResult.returnCode);
}
synchronized (mInstallLock) {
//安装:解析apk
installPackagesTracedLI(installRequests);
}
for (InstallRequest request : installRequests) {
//同安装前检验
request.args.doPostInstall(request.installResult.returnCode, request.installResult.uid);
}
}
for (InstallRequest request : installRequests) {
//安装后续:备份、可能的回滚、发送安装完成先关广播
restoreAndPostInstall(request.args.user.getIdentifier(), request.installResult, new PostInstallData(request.args, request.installResult, null));
}
});
}
这里我们先重点看安装过程,installPackagesTracedLI() 又走到 installPackagesLI():
private void installPackagesLI(List<InstallRequest> requests) {
...
try {
for (InstallRequest request : requests) {
final PrepareResult prepareResult;
//1.准备:分析当前安装状态,解析包并初始验证
prepareResult = preparePackageLI(request.args, request.installResult);
...
try {
//2.扫描:根据准备阶段解析的包信息上下文 进一步解析
final ScanResult result = scanPackageTracedLI(prepareResult.packageToScan, prepareResult.parseFlags,prepareResult.scanFlags, System.currentTimeMillis(),request.args.user, request.args.abiOverride);
...
//注册appId
createdAppId.put(packageName, optimisticallyRegisterAppId(result));
//保存version信息
versionInfos.put(result.pkgSetting.pkg.getPackageName(),getSettingsVersionForPackage(result.pkgSetting.pkg));
}
...
}
ReconcileRequest reconcileRequest = new ReconcileRequest(preparedScans, installArgs,installResults,prepareResults,mSharedLibraries,Collections.unmodifiableMap(mPackages), versionInfos,lastStaticSharedLibSettings);
CommitRequest commitRequest = null;
synchronized (mLock) {
Map<String, ReconciledPackage> reconciledPackages;
try {
//3.核对:验证扫描后的包信息和系统状态,确保安装成功
reconciledPackages = reconcilePackagesLocked(
reconcileRequest, mSettings.mKeySetManagerService);
} catch (ReconcileFailure e) {
for (InstallRequest request : requests) {
request.installResult.setError("Reconciliation failed...", e);
}
return;
}
try {
//4.提交:提交扫描的包、更新系统状态。这是唯一可以修改系统状态的地方,并且要对所有可预测的错误进行检测。
commitRequest = new CommitRequest(reconciledPackages,
mUserManager.getUserIds());
commitPackagesLocked(commitRequest);
success = true;
}
}
//安装成功的后续才做:准备app数据、编译布局资源、执行dex优化
executePostCommitSteps(commitRequest);
} ...
}
安装过程分四个阶段:
前三步主要是 解析和校验,第四部是把 包信息 提交到 PMS 内存数据结构中。其中解析和提交在上面的PMS初始化中 扫描apk目录后也是同样的过程。这里就不再展开跟踪了。
安装完成后,调用了 executePostCommitSteps() 准备app数据、执行dex优化:
private void executePostCommitSteps(CommitRequest commitRequest) {
...
for (ReconciledPackage reconciledPkg : commitRequest.reconciledPackages.values()) {
...
//提供目录结构/data/user/用户ID/包名/cache(/data/user/用户ID/包名/code_cache)
prepareAppDataAfterInstallLIF(pkg);
...
//是否要dex opt
final boolean performDexopt =
(!instantApp || Global.getInt(mContext.getContentResolver(),
Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
&& !pkg.isDebuggable()
&& (!onIncremental);
if (performDexopt) {
...
DexoptOptions dexoptOptions = new DexoptOptions(packageName,REASON_INSTALL,flags);
...
//执行dex优化:dexopt 是对 dex 文件 进行 verification 和 optimization 的操作,其对 dex 文件的优化结果变成了 odex 文件,这个文件和 dex 文件很像,只是使用了一些优化操作码(譬如优化调用虚拟指令等)。
mPackageDexOptimizer.performDexOpt(pkg, realPkgSetting,
null /* instructionSets */,
getOrCreateCompilerPackageStats(pkg),
mDexManager.getPackageUseInfoOrDefault(packageName),
dexoptOptions);
}...
}
}
这两个操作最终都是使用 Installer 对应的方法来操作。前面介绍 PMS 创建时传入了 Installer 的实例,而 Installer 继承自 SystemService 也是一个系统服务。这里来看下:
public class Installer extends SystemService {
public void onStart() {
if (mIsolated) {
mInstalld = null;
} else {
connect();
}
}
private void connect() {
IBinder binder = ServiceManager.getService("installd");
if (binder != null) {
try {
binder.linkToDeath(new DeathRecipient() {
@Override
public void binderDied() {
Slog.w(TAG, "installd died; reconnecting");
connect();
}
}, 0);
} catch (RemoteException e) {
binder = null;
}
}
if (binder != null) {
mInstalld = IInstalld.Stub.asInterface(binder);
try {
invalidateMounts();
} catch (InstallerException ignored) {
}
} else {
Slog.w(TAG, "installd not found; trying again");
BackgroundThread.getHandler().postDelayed(() -> {
connect();
}, DateUtils.SECOND_IN_MILLIS);
}
}
public long createAppData(String uuid, String packageName, int userId, int flags, int appId,
String seInfo, int targetSdkVersion) throws InstallerException {
if (!checkBeforeRemote()) return -1;
try {
return mInstalld.createAppData(uuid, packageName, userId, flags, appId, seInfo,
targetSdkVersion);
} catch (Exception e) {
throw InstallerException.from(e);
}
}
public void dexopt(String apkPath, int uid, @Nullable String pkgName, String instructionSet, int dexoptNeeded, @Nullable String outputPath ...) throws InstallerException {
...
if (!checkBeforeRemote()) return;
try {
mInstalld.dexopt(apkPath, uid, pkgName, instructionSet, dexoptNeeded, outputPath,
dexFlags, compilerFilter, volumeUuid, sharedLibraries, seInfo, downgrade,
targetSdkVersion, profileName, dexMetadataPath, compilationReason);
} catch (Exception e) {
throw InstallerException.from(e);
}
}
到这里安装完成,再回到 PMS 的 processInstallRequestsAsync(),最后调用restoreAndPostInstall()进行 备份、可能的回滚、发送安装完成先关广播:
private void restoreAndPostInstall(
int userId, PackageInstalledInfo res, @Nullable PostInstallData data) {
...
Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
mHandler.sendMessage(msg);
...
}
mHandler 使用 PMS的 handlePackagePostInstall()方法处理 POST_INSTALL:
到这里,APK的安装过程 就梳理完毕了,来回顾下:
未命名文件.png
本篇从用户感受的APK安装讲起,分别详细梳理了 包管理器服务——PackageManagerService 的服务开启、初始化扫描过程;然后分析了对应原生系统的安装过程及页面;接着就是详细分析了安装流程,包括创建Session 发送APK、PMS中的APK拷贝操作、包括APK解析校验和dexOpt等具体安装流程;最后是安装结果的发送。
内容确实很多,但是我们只需要重点了解 PMS的初始化、APK安装 的整体流程即可,无需关注繁杂的细节。
虽然耗费时不少时间阅读源码、也阅读了一些文章,但不免有错误和遗漏之处。欢迎讨论~