在涉及到一个包的装置进程的时候,往往都绕不开PackageManagerService
,它是Android体系中最常用的服务之一。首要负责体系中Package的办理,按钮开关怎么接运用程序的装缓存视频变成本地视频置、卸载、信息查询等作业。
开端前想先了解下什么是PMS(Android 11):
一、 PMS的发动进程
PMS也是在s缓存是什么意思ystemSshell命令erver
中创立的,涉及到PMS的创立部分:
//SystemServer
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
......
//创立PMS目标
try {
Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
} finally {
Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
}
//PMS是不是初次发动
mFirstBoot = mPackageManagerService.isFirstBoot();
mPackageManager = mSystemContext.getPackageManager();
}
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
......
//完结dex优化
mPackageManagerService.updatePackagesIfNeeded();
//完结磁盘维护
mPackageManagerService.performFstrimIfNeeded();
//通知体系进入安排妥当状况
mPackageManagerService.systemReady();
}
在这个发动进程git教程中,PMS的main函数
是整个的中心,现在咱们就优先级英文持续进行剖析:
public static PackageManagerService main(Context context, Installer installer,
boolean factoryTest, boolean onlyCore) {
//对PMS目标
PackageManagerService m = new PackageManagerService(injector, onlyCore, factoryTest);
t.traceEnd(); // "create package manager"
//将 package 服务注册到 ServiceManager,这是 binder 服务的常规注册流程
ServiceManager.addService("package", m);
final PackageManagerNative pmn = m.new PackageManagerNative();
ServiceManager.addService("package_native", pmn);
return m;
}
main办法的代码不多,首要是调用到了PMS的结构函数,而由于PMS中做了很多作业,这也便是Android发动速度慢的首要原因之一。
在其结构办法中,首要的作业是扫描Android体系中几个目标文件夹中的apk,之后树立合适的数据结构和办理如Package信息,四大组件信息,权限信缓存是什么意思息等各种信息。PKM按钮拼音S的作业流程能够分为五个阶段来剖析:
public PackageManagerService(Injector injector, boolean onlyCore, boolean factoryTest) {
......
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
SystemClock.uptimeMillis());
......
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
startTime);
......
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
SystemClock.uptimeMillis());
......
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
SystemClock.uptimeMillis());
......
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
SystemClock.uptimeMillis());
}
能够看到体系依据EventLog将PKMS的初始化分为shell是什么意思中文以下几个阶段:
-
BOshell什么意思OT_PROGRESS_PMS_START
发动阶段 -
BOOT_PROGRESS_PMS_SYSTEM_SCAN_START
发动阶段 -
BOOT_PROGRESS_PMS_DATA_SCAN优先级_START
发动阶段 -
BOOT_PROGRESS_PMS_SCAN_END
发动阶段 -
BOshell命令OTgiti轮胎_PROGRESS_PMS_READY
发动阶段
1.1 BOOT_PROGRESS_PMS_START 阶段
PackageManager.disableApplicationInfoCache();
PackageManager.disablePackageInfoCache();
PackageManager.corkPackageInfoCache();
final TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing",
Trace.TRACE_TAG_PACKAGE_MANAGER);
mPendingBroadcasts = new PendingPackageBroadcasts();
mInjector = injector;
mInjector.bootstrap(this);
mLock = injector.getLock();
mInstallLock = injector.getInstallLock();
LockGuard.installLock(mLock, LockGuard.INDEX_PACKAGES);
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
SystemClock.uptimeMillis());
if (mSdkVersion <= 0) {
Slog.w(TAG, "**** ro.build.version.sdk not set!");
}
mContext = injector.getContext();
mFactoryTest = factoryTest; //开机模式
mOnlyCore = onlyCore; //是否对包做dex优化
mMetrics = new DisplayMetrics(); //分辨率的装备
mInstaller = injector.getInstaller(); //保存installer目标
// Create sub-components that provide services / data. Order here is important.
t.traceBegin("createSubComponents");
// Expose private service for system components to use.
mPmInternal = new PackageManagerInternalImpl();
LocalServices.addService(PackageManagerInternal.class, mPmInternal);
mUserManager = injector.getUserManagerService();
mComponentResolver = injector.getComponentResolver();
mPermissionManager = injector.getPermissionManagerServiceInternal();
//创立setting目标
mSettings = injector.getSettings();
//权限办理服务
mPermissionManagerService = (IPermissionManager) ServiceManager.getService("permissionmgr");
mIncrementalManager =
(IncrementalManager) mContext.getSystemService(Context.INCREMENTAL_SERVICE);
PlatformCompat platformCompat = mInjector.getCompatibility();
mPackageParserCallback = new PackageParser2.Callback() {
@Override
public boolean isChangeEnabled(long changeId, @NonNull ApplicationInfo appInfo) {
return platformCompat.isChangeEnabled(changeId, appInfo);
}
@Override
public boolean hasFeature(String feature) {
return PackageManagerService.this.hasSystemFeature(feature, 0);
}
};
// CHECKSTYLE:ON IndentationCheck
t.traceEnd();
t.traceBegin("addSharedUsers");
//增加system phone log nfc bluetooth shell se net networkstack这8种shareUserId带mSetting
mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
mSettings.addSharedUserLPw("android.uid.se", SE_UID,
ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
mSettings.addSharedUserLPw("android.uid.networkstack", NETWORKSTACK_UID,
ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
t.traceEnd();
String separateProcesses = SystemProperties.get("debug.separate_processes");
if (separateProcesses != null && separateProcesses.length() > 0) {
if ("*".equals(separateProcesses)) {
mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
mSeparateProcesses = null;
Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
} else {
mDefParseFlags = 0;
mSeparateProcesses = separateProcesses.split(",");
Slog.w(TAG, "Running with debug.separate_processes: "
+ separateProcesses);
}
} else {
mDefParseFlags = 0;
mSeparateProcesses = null;
}
//DexOpt的优化
mPackageDexOptimizer = new PackageDexOptimizer(mInstaller, mInstallLock, mContext,
"*dexopt*");
mDexManager =
new DexManager(mContext, this, mPackageDexOptimizer, mInstaller, mInstallLock);
//mArt虚拟机办理服务
mArtManagerService = new ArtManagerService(mContext, this, mInstaller, mInstallLock);
mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
mViewCompiler = new ViewCompiler(mInstallLock, mInstaller);
getDefaultDisplayMetrics(mInjector.getDisplayManager(), mMetrics);
t.traceBegin("get system config");
SystemConfig systemConfig = SystemConfig.getInstance();
mAvailableFeatures = systemConfig.getAvailableFeatures();
ApplicationPackageManager.invalidateHasSystemFeatureCache();
t.traceEnd();
mProtectedPackages = new ProtectedPackages(mContext);
mApexManager = ApexManager.getInstance();
mAppsFilter = mInjector.getAppsFilter();
final List<ScanPartition> scanPartitions = new ArrayList<>();
final List<ApexManager.ActiveApexInfo> activeApexInfos = mApexManager.getActiveApexInfos();
for (int i = 0; i < activeApexInfos.size(); i++) {
final ScanPartition scanPartition = resolveApexToScanPartition(activeApexInfos.get(i));
if (scanPartition != null) {
scanPartitions.add(scanPartition);
}
}
mDirsToScanAsSystem = new ArrayList<>();
mDirsToScanAsSystem.addAll(SYSTEM_PARTITIONS);
mDirsToScanAsSystem.addAll(scanPartitions);
Slog.d(TAG, "Directories scanned as system partitions: " + mDirsToScanAsSystem);
// CHECKSTYLE:OFF IndentationCheck
synchronized (mInstallLock) {
// writer
synchronized (mLock) {
//发动packageManger线程,负责apk的装置、卸载
mHandlerThread = new ServiceThread(TAG,
Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
mHandlerThread.start();
mHandler = new PackageHandler(mHandlerThread.getLooper());
//进程记载handler
mProcessLoggingHandler = new ProcessLoggingHandler();
//watchdog监听ServiceThread是否超时,
Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
//mInstant运用注册
mInstantAppRegistry = new InstantAppRegistry(this);
//同享lib库装备
ArrayMap<String, SystemConfig.SharedLibraryEntry> libConfig
= systemConfig.getSharedLibraries();
final int builtInLibCount = libConfig.size();
for (int i = 0; i < builtInLibCount; i++) {
String name = libConfig.keyAt(i);
SystemConfig.SharedLibraryEntry entry = libConfig.valueAt(i);
addBuiltInSharedLibraryLocked(entry.filename, name);
}
// Now that we have added all the libraries, iterate again to add dependency
// information IFF their dependencies are added.
long undefinedVersion = SharedLibraryInfo.VERSION_UNDEFINED;
for (int i = 0; i < builtInLibCount; i++) {
String name = libConfig.keyAt(i);
SystemConfig.SharedLibraryEntry entry = libConfig.valueAt(i);
final int dependencyCount = entry.dependencies.length;
for (int j = 0; j < dependencyCount; j++) {
final SharedLibraryInfo dependency =
getSharedLibraryInfoLPr(entry.dependencies[j], undefinedVersion);
if (dependency != null) {
getSharedLibraryInfoLPr(name, undefinedVersion).addDependency(dependency);
}
}
}
//读取装置相关SELinux策略
SELinuxMMAC.readInstallPolicy();
t.traceBegin("loadFallbacks");
FallbackCategoryProvider.loadFallbacks();
t.traceEnd();
t.traceBegin("read user settings");
//读取并解析/data/system下的XML文件
mFirstBoot = !mSettings.readLPw(mInjector.getUserManagerInternal().getUsers(false));
t.traceEnd();
//清理代码途径不存在的孤立软件包
final int packageSettingCount = mSettings.mPackages.size();
for (int i = packageSettingCount - 1; i >= 0; i--) {
PackageSetting ps = mSettings.mPackages.valueAt(i);
if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists())
&& mSettings.getDisabledSystemPkgLPr(ps.name) != null) {
mSettings.mPackages.removeAt(i);
mSettings.enableSystemPackageLPw(ps.name);
}
}
//假如不是时候初次发动,也不是CORE运用,则仿制预编译的DEX文件
if (!mOnlyCore && mFirstBoot) {
requestCopyPreoptedFiles();
}
//获取资装备
String customResolverActivityName = Resources.getSystem().getString(
R.string.config_customResolverActivity);
if (!TextUtils.isEmpty(customResolverActivityName)) {
mCustomResolverComponentName = ComponentName.unflattenFromString(
customResolverActivityName);
}
//获取扫描开端的时刻
long startTime = SystemClock.uptimeMillis();
在第一阶段首要做了初始化的作业,为gitee后续做扫描作业的预备。这儿边你或许会发现一个复杂的数据结构Setting优先级表s以及它的addShareUserL按钮的工作原理Pw
函数。而Settiing
在里边又起了什么效果?
1.1.1 Setting
首要咱们先剖析addShareUserLPw
函数:
//运用了体系进程运用的用户id
mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
这儿边涉及到SYSTEM_UID
:
UID为用户ID的缩写,GID为用户组ID的缩写,这两个概念均与按钮拼音Linux体系中进程的权限办理有关。一般说来,每一个进程都会有一个对应的UID(即表示按钮开关该进程属于哪个user,不同user有不同权限)。一个进程也可分属不同的用户组(每个用户组都有对应的权限)。
接着咱们再来看下:
SharedUserSetting addSharedUserLPw(String name, int uid, int pkgFlags, int pkgPrivateFlags) {
//mSharedUsers是一个hashMap,key为字符串,值为SharedUserSetting目标
SharedUserSetting s = mSharedUsers.get(name);
if (s != null) {
if (s.userId == uid) {
return s;
}
PackageManagerService.reportSettingsProblem(Log.ERROR,
"Adding duplicate shared user, keeping first: " + name);
return null;
}
//创立一个新的ShareUserSettiing目标,并设置userId为uid
s = new SharedUserSetting(name, pkgFlags, pkgPrivateFlags);
s.userId = uid;
if (registerExistingAppIdLPw(uid, s, name)) {
mSharedUsers.put(name, s);
return s;
}
return null;
}
在这个办法里边会git教程创立ShareUserSetting
目标并增加到Settings
的成员变量mShareUsers
中。在Android体系中,多个package能够经过设置shareUserId特点
能够在同一个进程中运转,同享同一个UID;
或许会问ShareuserSetting缓存的视频在哪
是什么?能够从Androidshell脚本编程100例fManifest.xml
中找到:
<manifestxmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.systemui"
coreApp="true"
android:sharedUserId="android.uid.system"
android:process="system">
在这个里边声明晰一个android:shareUserId
的特点,它有两个效果:
- 两个或按钮开关怎么接多个缓存的视频在哪声明统一中
shareUserIds
的APK可同享互相的数据,而且可运转在同一进程中 - 经过声明特定的
shareUserIds
,该APK所在进程将赋予指定的UID
1.2 BOOT_PROGRESS_PMS_SYSTEM_SCAN_START阶段
经过前面阶段的预备,PKMS服务相关的初始化环境已经构建OK,现在要开端真实干活开端体按钮开关怎么接系扫描阶段了。这一部分首要做了:
-
从
init.rc
中获取环境变量BOOT按钮英文CLASSPATH按钮拼音
和SYSTEMSERV按钮开关符号ERCLASSPATH
; -
关于旧版别晋级的情况,将装置时获取权限变更为运转时请求权限;
-
扫描sshell命令ystem/vendor/product/odm/oem等目录的priv-app、app、overlay包;
-
铲除装置时优先级调度算法临时文件以及其他不必要的信息。
long startTime = SystemClock.uptimeMillis();
//写入开端扫描体系运用的日志
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
startTime);
//获取环境变量,init.rc
final String bootClassPath = System.getenv("BOOTCLASSPATH");
final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
if (bootClassPath == null) {
Slog.w(TAG, "No BOOTCLASSPATH found!");
}
if (systemServerClassPath == null) {
Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
}
//获取system/framework目录
File frameworkDir = new File(Environment.getRootDirectory(), "framework");
// 获取内部版别
final VersionInfo ver = mSettings.getInternalVersion();
// 判别fingerprint是否有更新
mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint);
if (mIsUpgrade) {
logCriticalInfo(Log.INFO,
"Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT);
}
// 关于Android M之前版别晋级上来的情况,需将体系运用程序权限从装置晋级到运转时
mPromoteSystemApps =
mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1;
// 关于Android N之前版别晋级上来的情况,需像初次发动一样处理package
mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N;
mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1;
mIsPreQUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.Q;
// 在扫描之前保存预先存在的体系package的称号,不希望自动为新体系运用颁发运转时权限
if (isDeviceUpgrading()) {
mExistingPackages = new ArraySet<>(mSettings.mPackages.size());
for (PackageSetting ps : mSettings.mPackages.values()) {
mExistingPackages.add(ps.name);
}
}
// 预备解析package的缓存
mCacheDir = preparePackageParserCache();
// 设置flag,而不在扫描装置时更改文件途径
int scanFlags = SCAN_BOOTING | SCAN_INITIAL;
if (mIsUpgrade || mFirstBoot) {
scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE;
}
final int systemParseFlags = mDefParseFlags | PackageParser.PARSE_IS_SYSTEM_DIR;
final int systemScanFlags = scanFlags | SCAN_AS_SYSTEM;
PackageParser2 packageParser = new PackageParser2(mSeparateProcesses, mOnlyCore,
mMetrics, mCacheDir, mPackageParserCallback);
ExecutorService executorService = ParallelPackageParser.makeExecutorService();
mApexManager.scanApexPackagesTraced(packageParser, executorService);
//扫描以下途径
for (int i = mDirsToScanAsSystem.size() - 1; i >= 0; i--) {
final ScanPartition partition = mDirsToScanAsSystem.get(i);
if (partition.getOverlayFolder() == null) {
continue;
}
scanDirTracedLI(partition.getOverlayFolder(), systemParseFlags,
systemScanFlags | partition.scanFlag, 0,
packageParser, executorService);
}
scanDirTracedLI(frameworkDir, systemParseFlags,
systemScanFlags | SCAN_NO_DEX | SCAN_AS_PRIVILEGED, 0,
packageParser, executorService);
if (!mPackages.containsKey("android")) {
throw new IllegalStateException(
"Failed to load frameworks package; check log for warnings");
}
for (int i = 0, size = mDirsToScanAsSystem.size(); i < size; i++) {
final ScanPartition partition = mDirsToScanAsSystem.get(i);
if (partition.getPrivAppFolder() != null) {
scanDirTracedLI(partition.getPrivAppFolder(), systemParseFlags,
systemScanFlags | SCAN_AS_PRIVILEGED | partition.scanFlag, 0,
packageParser, executorService);
}
scanDirTracedLI(partition.getAppFolder(), systemParseFlags,
systemScanFlags | partition.scanFlag, 0,
packageParser, executorService);
}
mOverlayConfig = OverlayConfig.initializeSystemInstance(
consumer -> mPmInternal.forEachPackage(
pkg -> consumer.accept(pkg, pkg.isSystem())));
// Prune any system packages that no longer exist.
final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>();
final List<String> stubSystemApps = new ArrayList<>();
//删去不存在的package
if (!mOnlyCore) {
// do this first before mucking with mPackages for the "expecting better" case
final Iterator<AndroidPackage> pkgIterator = mPackages.values().iterator();
while (pkgIterator.hasNext()) {
final AndroidPackage pkg = pkgIterator.next();
if (pkg.isStub()) {
stubSystemApps.add(pkg.getPackageName());
}
}
final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
while (psit.hasNext()) {
PackageSetting ps = psit.next();
// 假如不是体系运用,则不被允许disable
if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
continue;
}
// 假如运用被扫描,则不允许被擦除
final AndroidPackage scannedPkg = mPackages.get(ps.name);
if (scannedPkg != null) {
// 假如体系运用被扫描且存在disable运用列表中,则只能经过OTA晋级增加
if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
logCriticalInfo(Log.WARN,
"Expecting better updated system app for " + ps.name
+ "; removing system app. Last known"
+ " codePath=" + ps.codePathString
+ ", versionCode=" + ps.versionCode
+ "; scanned versionCode=" + scannedPkg.getLongVersionCode());
removePackageLI(scannedPkg, true);
mExpectingBetter.put(ps.name, ps.codePath);
}
continue;
}
if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
psit.remove();
logCriticalInfo(Log.WARN, "System package " + ps.name
+ " no longer exists; it's data will be wiped");
// Assume package is truly gone and wipe residual permissions.
mPermissionManager.updatePermissions(ps.name, null);
// Actual deletion of code and data will be handled by later
// reconciliation step
} else {
// we still have a disabled system package, but, it still might have
// been removed. check the code path still exists and check there's
// still a package. the latter can happen if an OTA keeps the same
// code path, but, changes the package name.
final PackageSetting disabledPs =
mSettings.getDisabledSystemPkgLPr(ps.name);
if (disabledPs.codePath == null || !disabledPs.codePath.exists()
|| disabledPs.pkg == null) {
possiblyDeletedUpdatedSystemApps.add(ps.name);
} else {
// We're expecting that the system app should remain disabled, but add
// it to expecting better to recover in case the data version cannot
// be scanned.
mExpectingBetter.put(disabledPs.name, disabledPs.codePath);
}
}
}
}
final int cachedSystemApps = PackageCacher.sCachedPackageReadCount.get();
......
在这类能够看到进行了扫描指定目录写下的apk文件,这个是PKMS的三大中心功能,它会经过调用Packa优先级geParser来完结对运用App中Apk按钮的工作原理的AndroidManifest.xml
的文件的优先级排序c语言解析,生成 Application
,activity
,servicshell翻译e
,broadcast
,provider
等四大组件信息,并将上述解析得到的四大组件信息注册到PKMS中,供Android体系查询并运按钮英文翻译用。
1.3 BOOT_PROGRESS_PMS_DATA_SCAN_START阶段
在这儿不仅仅解析中心运用的情况下,还处理data目录的运用信息,及时更新,去除不必要的数据。
if (!mOnlyCore) {
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
SystemClock.uptimeMillis());
scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0,
packageParser, executorService);
}
packageParser.close();
List<Runnable> unfinishedTasks = executorService.shutdownNow();
if (!unfinishedTasks.isEmpty()) {
throw new IllegalStateException("Not all tasks finished before calling close: "
+ unfinishedTasks);
}
if (!mOnlyCore) {
// 移除经过OTA删去的更新体系运用程序的禁用package设置
// 假如更新不再存在,则彻底删去该运用。不然,吊销其体系权限
for (int i = possiblyDeletedUpdatedSystemApps.size() - 1; i >= 0; --i) {
final String packageName = possiblyDeletedUpdatedSystemApps.get(i);
final AndroidPackage pkg = mPackages.get(packageName);
final String msg;
mSettings.removeDisabledSystemPackageLPw(packageName);
......
}
//保证希望在userdata分区上显示的一切体系运用程序实践显示
// 假如从未呈现过,需求回滚以康复体系版别
for (int i = 0; i < mExpectingBetter.size(); i++) {
final String packageName = mExpectingBetter.keyAt(i);
if (!mPackages.containsKey(packageName)) {
final File scanFile = mExpectingBetter.valueAt(i);
......
mSettings.enableSystemPackageLPw(packageName);
try {
//扫描APK
scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null);
} catch (PackageManagerException e) {
Slog.e(TAG, "Failed to parse original system package: "
+ e.getMessage());
}
}
}
// 解压缩并装置任何存根体系运用程序。有必要最终履行此操作以保证替换或禁用一切存根
installSystemStubPackages(stubSystemApps, scanFlags);
......
// 获取storage manager包名.
mStorageManagerPackage = getStorageManagerPackageName();
// 解决受维护的action过滤器。只允许setup wizard(开机向导)为这些action设置高优先级过滤器
mSetupWizardPackage = getSetupWizardPackageNameImpl();
mComponentResolver.fixProtectedFilterPriorities();
......
// 更新客户端以保证持有正确的同享库途径
updateAllSharedLibrariesLocked(null, null, Collections.unmodifiableMap(mPackages));
......
// 读取并更新要保存的package的前次运用时刻
mPackageUsage.read(mSettings.mPackages);
mCompilerStats.read();
1.4 BOOT_PROGRESS_PMS_SCAN_END阶段
首要做了:
- 当sdk版别不一致时,需求更新权限
- 当这是ota的初次发动giti,正常发动则需求清楚目缓存视频在手机哪里找录的缓存代码
- 当权限和其他默许项都完结更新,则清理相关信息
- 信息写回
pac优先级c语言kages.xml
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
SystemClock.uptimeMillis());
Slog.i(TAG, "Time to scan packages: "
+ ((SystemClock.uptimeMillis()-startTime)/1000f)
+ " seconds");
// // 假如自前次发动以来,平台SDK已改变,则需求重新颁发运用程序权限以捕获呈现的任何新权限
final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion);
if (sdkUpdated) {
Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to "
+ mSdkVersion + "; regranting permissions for internal storage");
}
mPermissionManager.updateAllPermissions(
StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated);
ver.sdkVersion = mSdkVersion;
// 假如这是第一次发动或来自Android M之前的版别的晋级,而且它是正常发动,那需求在一切已定义的用户中初始化默许的首选运用程序
if (!mOnlyCore && (mPromoteSystemApps || mFirstBoot)) {
for (UserInfo user : mInjector.getUserManagerInternal().getUsers(true)) {
mSettings.applyDefaultPreferredAppsLPw(user.id);
primeDomainVerificationsLPw(user.id);
}
}
// 在发动期间确实为体系用户预备存储,因为像SettingsProvider和SystemUI这样的中心体系运用程序无法等待用户发动
final int storageFlags;
if (StorageManager.isFileEncryptedNativeOrEmulated()) {
storageFlags = StorageManager.FLAG_STORAGE_DE;
} else {
storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
}
List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL,
UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */,
true /* onlyCoreApps */);
mPrepareAppDataFuture = SystemServerInitThreadPool.submit(() -> {
TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync",
Trace.TRACE_TAG_PACKAGE_MANAGER);
traceLog.traceBegin("AppDataFixup");
try {
mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL,
StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
} catch (InstallerException e) {
Slog.w(TAG, "Trouble fixing GIDs", e);
}
traceLog.traceEnd();
......
// 假如是在OTA之后初次发动,而且正常发动,那需求铲除代码缓存目录,但不铲除运用程序装备文件
if (mIsUpgrade && !mOnlyCore) {
Slog.i(TAG, "Build fingerprint changed; clearing code caches");
for (int i = 0; i < mSettings.mPackages.size(); i++) {
final PackageSetting ps = mSettings.mPackages.valueAt(i);
if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) {
// No apps are running this early, so no need to freeze
clearAppDataLIF(ps.pkg, UserHandle.USER_ALL,
FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL
| Installer.FLAG_CLEAR_CODE_CACHE_ONLY
| Installer.FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES);
}
}
ver.fingerprint = Build.FINGERPRINT;
}
// 装置Android-Q前的非体系运用程序在Launcher中躲藏他们的图标
if (!mOnlyCore && mIsPreQUpgrade) {
Slog.i(TAG, "Whitelisting all existing apps to hide their icons");
int size = mSettings.mPackages.size();
for (int i = 0; i < size; i++) {
final PackageSetting ps = mSettings.mPackages.valueAt(i);
if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
continue;
}
ps.disableComponentLPw(PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME,
UserHandle.USER_SYSTEM);
}
}
// 仅在权限或其它默许装备更新后铲除
mPromoteSystemApps = false;
// 一切变更均在扫描进程中完结
ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION;
//降级去读取
mSettings.writeLPr();
t.traceEnd();
1.5 BOOT_PROGRESS_PMS_READY阶段
- 初始化PackageInstallerService
- GC收回写下内存
EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
SystemClock.uptimeMillis());
if (!mOnlyCore) {
//PermissionController 掌管 缺陷许可证的颁发和角色办理,所以这是中心体系的一个关键部分
mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr();
......
mServicesExtensionPackageName = getRequiredServicesExtensionPackageLPr();
mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr(
PackageManager.SYSTEM_SHARED_LIBRARY_SHARED,
SharedLibraryInfo.VERSION_UNDEFINED);
} else {
mRequiredVerifierPackage = null;
mRequiredInstallerPackage = null;
mRequiredUninstallerPackage = null;
mIntentFilterVerifierComponent = null;
mIntentFilterVerifier = null;
mServicesExtensionPackageName = null;
mSharedSystemSharedLibraryPackageName = null;
}
// PermissionController hosts default permission granting and role management, so it's a
// critical part of the core system.
mRequiredPermissionControllerPackage = getRequiredPermissionControllerLPr();
mSettings.setPermissionControllerVersion(
getPackageInfo(mRequiredPermissionControllerPackage, 0,
UserHandle.USER_SYSTEM).getLongVersionCode());
......
// 阅览并更新dex文件的用法
// 在PM init完毕时履行此操作,以便一切程序包都已协调其数据目录
// 此时知道了包的代码途径,因此能够验证磁盘文件并构建内部缓存
// 运用文件预计很小,因此与其他活动(例如包扫描)比较,加载和验证它应该花费相当小的时刻
final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>();
for (int userId : userIds) {
userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList());
}
mDexManager.load(userPackages);
if (mIsUpgrade) {
FrameworkStatsLog.write(
FrameworkStatsLog.BOOT_TIME_EVENT_DURATION_REPORTED,
BOOT_TIME_EVENT_DURATION__EVENT__OTA_PACKAGE_MANAGER_INIT_TIME,
SystemClock.uptimeMillis() - startTime);
}
} // synchronized (mLock)
} // synchronized (mInstallLock)
// CHECKSTYLE:ON IndentationCheck
mModuleInfoProvider = new ModuleInfoProvider(mContext, this);
// Uncork cache invalidations and allow clients to cache package information.
PackageManager.uncorkPackageInfoCache();
// Now after opening every single application zip, make sure they
// are all flushed. Not really needed, but keeps things nice and
// tidy.
t.traceBegin("GC");
Runtime.getRuntime().gc();
t.traceEnd();
// 打开运用之后,及时收回处理
mInstaller.setWarnIfHeld(mLock);
// 上面的初始扫描在持有mPackage锁的同时对installd进行了屡次调用
PackageParser.readConfigUseRoundIcon(mContext.getResources());
mServiceStartWithDelay = SystemClock.uptimeMillis() + (60 * 1000L);
到这儿基本把PMS结构函数流程看了一遍,到BOOT_PEOGRESS_END
就算装置完毕了。
二、 APK的装置进程
一讲到装置流程,它有四种装置办法:
- 体系运用和预制运用装置,开机时完结,没有装置界面,在按钮英文
PKMS
的结构函数中欧冠完结装置 - 网络下载运用装置,经过运用商铺giti来完结,调shellfish用
PackageManager.inst按钮开关符号a优先级越小越优先吗llPackages()
,有装置界面 - ADB东西装置,没有装置界面,它经过发动pm脚本的办法,然缓存清理后调用
comgithub.android.commands.pm.Pm类优先级调度算法
,之后调用到PMS.ins优先级c语言tallStage()完结装置 - 第三方运用装置,经过SD卡里的APK文件装置,有装置界面,由
packageinstaller.apk
运用处理装置及卸载进程的界面
均是经过PackageInstallObserver来监听装置giti轮胎是否成功。
下面咱按钮拼音们经过点击下shell翻译载运用装置来了解装置的进程:
先说个大概:
- 1.将APK的信息经过IgitlabO流的办法写入到
PackageInstaller.Session
中。 - 2.调用
Packa优先级越小越优先吗geInstaller.Session
的commit办法,将APK的信息交由PKMS处理。 - 3.仿制APK
- 4.最终shell命令进行装置
在点击一个未装置的apk后,会弹出装置界面,点击确认按钮后,会进入PackageInstalle按钮英文rActivity
界面,后面会触发git命令bindUi办法优先级排序c语言,弹出底部装置界面。这个首要是由bindUi
构成,上面会有撤销和装置两个按钮,点击之后就会调用startInstall()
进按钮英文行装置
//PackageInstallerActivity.java
private void bindUi() {
mAlert.setIcon(mAppSnippet.icon);
mAlert.setTitle(mAppSnippet.label);
mAlert.setView(R.layout.install_content_view);
mAlert.setButton(DialogInterface.BUTTON_POSITIVE, getString(R.string.install),
(ignored, ignored2) -> {
if (mOk.isEnabled()) {
if (mSessionId != -1) {
mInstaller.setPermissionsResult(mSessionId, true);
finish();
} else {
//进行APK装置
startInstall();
}
}
}, null);
mAlert.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel),
(ignored, ignored2) -> {
// Cancel and finish
setResult(RESULT_CANCELED);
if (mSessionId != -1) {
//假如mSessionId存在,履行setPermissionsResult()完结撤销装置
mInstaller.setPermissionsResult(mSessionId, false);
}
finish();
}, null);
setupAlert();
......
}
//点击”装置“,跳转 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();
}
在startInstall
办法组装了一个Intent,并跳转到InstallIn按钮sta缓存视频变成本地视频lling
这个Activity,并关闭掉当时的PackageInstallerActivity
。在InstallInstalling
首要giti用于向包办理器发送包的信息并处理包办理的回调。
2.1 PackageInstall按钮开关怎么接er装置APK
在发动Instashell翻译llInstalling
后,进入onCreate
办法:
//InstallInstalling
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ApplicationInfo appInfo = getIntent()
.getParcelableExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO);
mPackageURI = getIntent().getData();
......
setupAlert();
requireViewById(R.id.installing).setVisibility(View.VISIBLE);
if (savedInstanceState != null) {
mSessionId = savedInstanceState.getInt(SESSION_ID);
mInstallId = savedInstanceState.getInt(INSTALL_ID);
try {
//.依据mInstallId向InstallEventReceiver注册一个观察者,launchFinishBasedOnResult会接收到装置事件的回调,无论装置成功或许失利都会关闭当时的Activity(InstallInstalling)。假如savedInstanceState为null,代码的逻辑也是相似的
InstallEventReceiver.addObserver(this, mInstallId,
this::launchFinishBasedOnResult);
} catch (EventResultPersister.OutOfIdsException e) {
// Does not happen
}
} else {
......
File file = new File(mPackageURI.getPath());
try {
PackageParser.PackageLite pkg = PackageParser.parsePackageLite(file, 0);
params.setAppPackageName(pkg.packageName);
params.setInstallLocation(pkg.installLocation);
params.setSize(
PackageHelper.calculateInstalledSize(pkg, false, params.abiOverride));
} catch (PackageParser.PackageParserException e) {
Log.e(LOG_TAG, "Cannot parse package " + file + ". Assuming defaults.");
Log.e(LOG_TAG,
"Cannot calculate installed size " + file + ". Try only apk size.");
params.setSize(file.length());
} catch (IOException e) {
Log.e(LOG_TAG,
"Cannot calculate installed size " + file + ". Try only apk size.");
params.setSize(file.length());
}
try {
//向InstallEventReceiver注册一个观察者回来一个新的mInstallId,
//其间InstallEventReceiver继承自BroadcastReceiver,用于接收装置事件并回调给EventResultPersister。
mInstallId = InstallEventReceiver
.addObserver(this, EventResultPersister.GENERATE_NEW_ID,
this::launchFinishBasedOnResult);
} catch (EventResultPersister.OutOfIdsException e) {
launchFailure(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, null);
}
try {
//PackageInstaller的createSession办法内部会经过IPackageInstaller与PackageInstallerService进行进程间通信,终究调用的是PackageInstallerService的createSession办法来创立并回来mSessionId
mSessionId = getPackageManager().getPackageInstaller().createSession(params);
} catch (IOException e) {
launchFailure(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, null);
}
}
mCancelButton = mAlert.getButton(DialogInterface.BUTTON_NEGATIVE);
mSessionCallback = new InstallSessionCallback();
}
}
在onCreate
中经过PackageInstaller
经过创立优先级越小越优先吗Session并回来mSesionId,接着会在onResume
中,会开启InstallingAsynTask,把包信息写入mSessionId对应的session,然后提交。
//InstallInstalling
protected void onResume() {
super.onResume();
// This is the first onResume in a single life of the activity
if (mInstallingTask == null) {
PackageInstaller installer = getPackageManager().getPackageInstaller();
//获取sessionInfo
PackageInstaller.SessionInfo sessionInfo = installer.getSessionInfo(mSessionId);
if (sessionInfo != null && !sessionInfo.isActive()) {
//创立内部类InstallingAsyncTask的目标,调用execute(),终究进入onPostExecute()
mInstallingTask = new InstallingAsyncTask();
mInstallingTask.execute();
} else {
// we will receive a broadcast when the install is finished
mCancelButton.setEnabled(false);
setFinishOnTouchOutside(false);
}
}
}
private final class InstallingAsyncTask extends AsyncTask<Void, Void,
PackageInstaller.Session> {
@Override
protected PackageInstaller.Session doInBackground(Void... params) {
PackageInstaller.Session session;
try {
session = getPackageManager().getPackageInstaller().openSession(mSessionId);
} catch (IOException e) {
return null;
}
session.setStagingProgress(0);
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];
......
}
}
return session;
} catch (IOException | SecurityException e) {
......
}
@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);
} else {
getPackageManager().getPackageInstaller().abandonSession(mSessionId);
if (!isCancelled()) {
launchFailure(PackageManager.INSTALL_FAILED_INVALID_APK, null);
}
}
}
}
在InstallingAsy缓存nc缓存视频合并appTask的doInBa优先级调度算法ckground()
里会依据包的Uri,将APK的信息经过IO流的办法写入到PackageInstallgitlaber.Session
中按钮英文,最终会在onPostExecute()
中调用PackageInstaller.Session
的缓存视频合并cgithubommit办法,进行装置。
在里边会看到一个PackageInstaller
,也便是APK装置器。而其真实ApplicationPackageManager的getPackageInstaller
中创立的:
//ApplicationPackageManager
@Override
public PackageInstaller getPackageInstaller() {
synchronized (mLock) {
if (mInstaller == null) {
try {
mInstaller = new PackageInstaller(mPM.getPackageInstaller(),
mContext.getPackageName(), getUserId());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
return mInstaller;
}
}
在这儿会传入mPM.getPacshell编程kageInstaller()
,也便是IpacageInstaller
的实例,其详细实现也便是Pa按钮开关怎么接ckageInstallerService
, 其经过IPC的办法。它在初始化的时候会读取/data/system目录下的install_sessions
文件,这个文件保存了体系未完结的Install Session
。PMS则会依据文件的内容创立PackageInstallerSession
目标并从giti插入到mSes优先级c语言sions中。
//PackageInstallerService.java
public PackageInstallerService(Context context, PackageManagerService pm,
Supplier<PackageParser2> apexParserSupplier) {
mContext = context;
mPm = pm;
mPermissionManager = LocalServices.getService(PermissionManagerServiceInternal.class);
mInstallThread = new HandlerThread(TAG);
mInstallThread.start();
mInstallHandler = new Handler(mInstallThread.getLooper());
mCallbacks = new Callbacks(mInstallThread.getLooper());
mSessionsFile = new AtomicFile(
new File(Environment.getDataSystemDirectory(), "install_sessions.xml"),
"package-session");
//这个文件保存了体系未完结的`Install Session`
mSessionsDir = new File(Environment.getDataSystemDirectory(), "install_sessions");
mSessionsDir.mkdirs();
mApexManager = ApexManager.getInstance();
mStagingManager = new StagingManager(this, context, apexParserSupplier);
}
再缓存视频合并app来看下Session
,是在于mSeesionId绑定的装置会话,代表shelly着一个在进行中的装置。Session类是对IPackageInstaller.openSession(sessionId) 获取的 PackageInstallerSession(体系服务端)的封装。
Session的创立和打开 详细实现是在 PackageInstallerService中,首github要是 初始化apk的装置信息及环境,缓存是什么意思并创立一个sessionId,将装置Se缓存文件夹名称ssion与sessionId优先级队列 进行绑定
接着咱们回到InstallingAsyncTask
中,在这儿调用了session.commit
办法:
//PackageInstaller
public void commit(@NonNull IntentSender statusReceiver) {
try {
//调用PackageInstallerSession的commit办法,进入到java结构层
mSession.commit(statusReceiver, false);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
//PackageInstallerSession.java
public void commit(@NonNull IntentSender statusReceiver, boolean forTransfer) {
......
//假如没有调用,则会话将被密封。此办法或许会被屡次调用以更新状况接收者验证调用者权限
if (!markAsSealed(statusReceiver, forTransfer)) {
return;
}
//不同的包
if (isMultiPackage()) {
final SparseIntArray remainingSessions = mChildSessionIds.clone();
final IntentSender childIntentSender =
new ChildStatusIntentReceiver(remainingSessions, statusReceiver)
.getIntentSender();
boolean sealFailed = false;
for (int i = mChildSessionIds.size() - 1; i >= 0; --i) {
final int childSessionId = mChildSessionIds.keyAt(i);
// seal all children, regardless if any of them fail; we'll throw/return
// as appropriate once all children have been processed
if (!mSessionProvider.getSession(childSessionId)
.markAsSealed(childIntentSender, forTransfer)) {
sealFailed = true;
}
}
if (sealFailed) {
return;
}
}
dispatchStreamValidateAndCommit();
}
private void dispatchStreamValidateAndCommit() {
mHandler.obtainMessage(MSG_STREAM_VALIDATE_AND_COMMIT).sendToTarget();
}
mSession
的类型为IP优先级排序c语言ackageInstallerSession
,这说明要经过IPackage优先级调度算法InstallerSession
来进行进程间的通信,终究会调用PackageInstallerSession
的commit
办法。
在这儿发送了一个MSG_STREAM_VALIDATE_AND_COMMIT
的信号,并在handler中进行处理:
public boolean handleMessage(Message msg) {
case MSG_STREAM_VALIDATE_AND_COMMIT:
handleStreamValidateAndCommit();
break;
case MSG_INSTALL:
handleInstall(); //
break;
......
}
private void handleStreamValidateAndCommit() {
......
if (unrecoverableFailure != null) {
onSessionVerificationFailure(unrecoverableFailure);
// fail other child sessions that did not already fail
for (int i = nonFailingSessions.size() - 1; i >= 0; --i) {
PackageInstallerSession session = nonFailingSessions.get(i);
session.onSessionVerificationFailure(unrecoverableFailure);
}
}
}
if (!allSessionsReady) {
return;
}
mHandler.obtainMessage(MSG_INSTALL).sendToTarget();
}
在handleStreamValidateAndCommit
又发送了音讯MSG_INSTALL
,实践上真真按钮符号实履行的是在handleInstall
中:
private void handleInstall() {
......
// 关于 multiPackage 会话,请在锁之外读取子会话,因为在持有锁的情况下读取子会话或许会导致死锁 (b123391593)。
List<PackageInstallerSession> childSessions = getChildSessionsNotLocked();
try {
synchronized (mLock) {
installNonStagedLocked(childSessions);
}
} catch (PackageManagerException e) {
final String completeMsg = ExceptionUtils.getCompleteMessage(e);
Slog.e(TAG, "Commit of session " + sessionId + " failed: " + completeMsg);
destroyInternal();
dispatchSessionFinished(e.error, completeMsg, null);
}
}
private void installNonStagedLocked(List<PackageInstallerSession> childSessions)
throws PackageManagerException {
......
if (!success) {
sendOnPackageInstalled(mContext, mRemoteStatusReceiver, sessionId,
isInstallerDeviceOwnerOrAffiliatedProfileOwnerLocked(), userId, null,
failure.error, failure.getLocalizedMessage(), null);
return;
}
mPm.installStage(installingChildSessions);
} else {
mPm.installStage(installingSession);
}
}
最终履行到了PMS
的优先级installStage
办法。缓存在上述的进程中,经过PackageInstallershell翻译
保持了Session
,把装置包写入到Session
,真实的装置进程就要来看PMS了。
2.2 PMS履行装置
//PackageManagerService.java
void installStage(List<ActiveInstallSession> children)
throws PackageManagerException {
//创立了类型未INIT_COPY的音讯
final Message msg = mHandler.obtainMessage(INIT_COPY);
//创立InstallParams,它对应于包的装置数据
final MultiPackageInstallParams params =
new MultiPackageInstallParams(UserHandle.ALL, children);
params.setTraceMethod("installStageMultiPackage")
.setTraceCookie(System.identityHashCode(params));
msg.obj = params;
Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStageMultiPackage",
System.identityHashCode(msg.obj));
Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
System.identityHashCode(msg.obj));
//将InstallParams经过音讯发送出去
mHandler.sendMessage(msg);
}
handler对INIT_COPY的音讯进行处理:
//PackageManagerService.java
void doHandleMessage(Message msg) {
switch (msg.what) {
case INIT_COPY: {
HandlerParams params = (HandlerParams) msg.obj;
if (params != null) {
if (DEBUG_INSTALL) Slog.i(TAG, "init_copy: " + params);
Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
System.identityHashCode(params));
Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy");
//履行APK仿制动作
params.startCopy();
Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
}
break;
}
......
}
final void startCopy() {
if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
handleStartCopy();
handleReturnCode();
}
在这儿调用了两个办法handleStartCopy
和handleReturnCode
,其实现是在InstallParams按钮开关符号
中。github中文官网网页
在handleStartCopy
,做了以下操作:
- 检查空间巨细,假如空间不够则开释无用空间
- 掩盖原有装置位置的文件,并依据回来成果来确认函数的回来值,并设置installFlags
- 确认是否有任何已装置的包验证器,如有,则推迟检测。首要分三步:首要新建一个验证Intent,然后设置相关的信息,之后获取验证器列表,最终向每个验证器发送验证Intent
public void handleStartCopy() {
......
//解析包 回来最小的细节:pkgName、versionCode、装置所需空间巨细、获取装置位置等
pkgLite = PackageManagerServiceUtils.getMinimalPackageInfo(mContext,
origin.resolvedPath, installFlags, packageAbiOverride);
......
//掩盖原有装置位置的文件,并依据回来成果来确认函数的回来值,并设置installFlags。
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) {
ret = PackageManager.INSTALL_FAILED_INVALID_APK;
} else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_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;
mEnableRollbackCompleted = 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);
......
}
}
然后来看下handleReturnCode
办法:
@Override
void handleReturnCode() {
......
if (mRet == PackageManager.INSTALL_SUCCEEDED) {
//履行APKcopy仿制
mRet = mArgs.copyApk();
}
//履行装置
processPendingInstall(mArgs, mRet);
}
}
APK的copy进程是怎么仿制的:
//packageManagerService.java
int copyApk() {
Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
try {
return doCopyApk();
} finally {
Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
}
}
private int doCopyApk() {
......
int ret = PackageManagerServiceUtils.copyPackage(
origin.file.getAbsolutePath(), codeFile);
......
return ret;
}
//持续追踪下去,他会到PackagemanagerSeriveUtils的copyFile办法
//PackagemanagerSeriveUtils
private static void copyFile(String sourcePath, File targetDir, String targetName)
throws ErrnoException, IOException {
if (!FileUtils.isValidExtFilename(targetName)) {
throw new IllegalArgumentException("Invalid filename: " + targetName);
}
Slog.d(TAG, "Copying " + sourcePath + " to " + targetName);
final File targetFile = new File(targetDir, targetName);
final FileDescriptor targetFd = Os.open(targetFile.getAbsolutePath(),
O_RDWR | O_CREAT, 0644);
Os.chmod(targetFile.getAbsolutePath(), 0644);
FileInputStream source = null;
try {
source = new FileInputStream(sourcePath);
FileUtils.copy(source.getFD(), targetFd);
} finally {
IoUtils.closeQuietly(source);
}
}
在这儿就经过文件流的操作,把Apk仿制到/data/app的目录下了。完毕完仿制之后,就要进入真实的装置了,流程如下:
//PackageManagerService.java
private void processPendingInstall(final InstallArgs args, final int currentStatus) {
if (args.mMultiPackageInstallParams != null) {
args.mMultiPackageInstallParams.tryProcessInstallRequest(args, currentStatus);
} else {
//装置成果
PackageInstalledInfo res = createPackageInstalledInfo(currentStatus);
//创立一个新线程来处理安转参数来进行装置
processInstallRequestsAsync(
res.returnCode == PackageManager.INSTALL_SUCCEEDED,
Collections.singletonList(new InstallRequest(args, res)));
}
}
//排队履行异步操作
private void processInstallRequestsAsync(boolean success,
List<InstallRequest> installRequests) {
mHandler.post(() -> {
if (success) {
for (InstallRequest request : installRequests) {
//进行检验,假如之前装置失利,则铲除无用信息
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
,接着内部履行到了i优先级表nstallPackagesLI
办法:
//PackageMmanagerSerice.java
private void installPackagesLI(List<InstallRequest> requests) {
.......
//剖析当时任何状况,剖析包并对其进行初始化验证
prepareResult =
preparePackageLI(request.args, request.installResult);
......
//依据预备阶段解析包的信息上下文,进一步解析
final ScanResult result = scanPackageTracedLI(
prepareResult.packageToScan, prepareResult.parseFlags,
prepareResult.scanFlags, System.currentTimeMillis(),
request.args.user, request.args.abiOverride);
.......
//验证扫描后包的信息好状况,保证装置成功
reconciledPackages = reconcilePackagesLocked(
reconcileRequest, mSettings.mKeySetManagerService);
//提交一切的包并更新体系状况。这是装置流中仅有能够修正体系状况的当地,有必要在此阶段之前确认一切可预测的过错
commitRequest = new CommitRequest(reconciledPackages,
mUserManager.getUserIds());
commitPackagesLocked(commitRequest);
.......
//完结APK装置
executePostCommitSteps(commitRequest);
}
由上面代码可知,installPackagesLI
首要做了以下事情:
- 剖析当时任何状况,剖析包并对其进行初优先级越小越优先吗始化验github中文官网网页证
- 依据预备阶段解析git教程包的信息上下文,进一步解析
- 验证扫描后包的信息好状况,保证装置成功
- 提交一缓存是什么意思切骚哦欧庙的包并更新体系状况
- 完结APK装置
在 preparePackageLI() 内运用按钮的文字符号 PackagePshell编程arser2.parsePackage() 解析AndgitiroidManifest.xml,获取四大组件等信息;运用ParsingPackag优先级排序c语言eUtils.getSigningDetails() 解析签名信息;重命名包终缓存视频变成本地视频究途径 等。
完结了解析和校验预备作业后,最终一步便是对apk的装置了。这儿调用了executePostCommitSteps
预备app数据,并履优先级最高的运算符行dex优化。
//PackageManagerService.java
private void executePostCommitSteps(CommitRequest commitRequest) {
//进行装置
prepareAppDataAfterInstallLIF(pkg);
.......
final boolean performDexopt =
(!instantApp || Global.getInt(mContext.getContentResolver(),
Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
&& !pkg.isDebuggable()
&& (!onIncremental);
//为新的代码途径预备运用程序装备文件
mArtManagerService.prepareAppProfiles(
pkg,
resolveUserIds(reconciledPkg.installArgs.user.getIdentifier()),
if (performDexopt) {
......
//其间分配了 dexopt 所需的库文件
PackageSetting realPkgSetting = result.existingSettingCopied
? result.request.pkgSetting : result.pkgSetting;
if (realPkgSetting == null) {
realPkgSetting = reconciledPkg.pkgSetting;
}
//履行dex优化
mPackageDexOptimizer.performDexOpt(pkg, realPkgSetting,
null /* instructionSets */,
getOrCreateCompilerPackageStats(pkg),
mDexManager.getPackageUseInfoOrDefault(packageName),
dexoptOptions);
Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
}
}
在prepareAppDataAfterInstallLIF
办法中,经过一系列的调用,最中会调用到 mInstaller.c缓存reateAppData
,这儿也是调用Installd
守护进程的进口缓存清理:
public class Installer extends SystemService {
@Override
public void onStart() {
if (mIsolated) {
mInstalld = null;
} else {
//经过Binder调用到进程installd
connect();
}
}
private void connect() {
IBinder binder = ServiceManager.getService("installd");
......
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);
}
}
}
能够看到终究调用了In优先级排序c语言stalld
的creategiticomfort是什么轮胎AppData
办法进行装置giti。Installer是Java层提供的Java API接口,Installd 则是在优先级最高的运算符init进程发动的具有root权限的Daemon优先级c语言进程。
在processIShellnstallRequestsAsync
最终一步时调用了restoreAndPostInstall
,在装置完结时会发送POST_INSTALL
音讯:
//PackageManagerService.java
private void restoreAndPostInstall(
int userId, PackageInstalledInfo res, @Nullable PostInstallData data) {
.......
if (!doRestore) {
if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token);
Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
mHandler.sendMessage(msg);
}
}
void doHandleMessage(Message msg) {
.......
case POST_INSTALL: {
.......
//处理装置成果
handlePackagePostInstall(parentRes, grantPermissions,
killApp, virtualPreload, grantedPermissions,
whitelistedRestrictedPermissions, autoRevokePermissionsMode,
didRestore, args.installSource.installerPackageName, args.observer,
args.mDataLoaderType);
}
}
private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions,
boolean killApp, boolean virtualPreload,
String[] grantedPermissions, List<String> whitelistedRestrictedPermissions,
int autoRevokePermissionsMode,
boolean launchedForRestore, String installerPackage,
IPackageInstallObserver2 installObserver, int dataLoaderType) {
......
sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
extras, 0 /*flags*/,
null /*targetPackage*/, null /*finishedReceiver*/,
updateUserIds, instantUserIds, newBroadcastWhitelist);
}
最git命令终发送了ACTION_PACKAGE_ADDED
广播,launch按钮拼音er接收到这个广播之后就会在桌面上增加运用图标了。
小结
本文首要讲缓存视频怎样转入相册了:
- APK的信息会经过流的办法写入到
PackageInstal按钮英文翻译ler.Session
中,并提交给PMS处理 - PMS经过向
PackageHandler
发送音讯来驱动APK的仿制和装置作业 - 仿制APK完结后,会开端进行装置APK的流程,包括装置前按钮开关符号的检查、装置APK和装置后的收尾作业
- 然后经过
Installer缓存视频在手机哪里找
进行装置,装置完结发送广播出来
参阅
-
Android包办理机制(五)APK是怎么被解析的
-
PackageM按钮的文字符号anashell命令gerService发动流程
-
Android包办理机制
-
Android 10.0 PackageManagerService(一)作shell命令业原理及发动流程-Android取经之路
-
[深化了解Android卷二 全文-第四章]深化了解PackageManagerService
-
“终于懂了”系列:APK装置进程 彻底解析!