日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

从源码角度解析Android中APK安装过程

發(fā)布時間:2025/1/21 Android 70 豆豆
生活随笔 收集整理的這篇文章主要介紹了 从源码角度解析Android中APK安装过程 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

從源碼角度解析Android中APK的安裝過程

1. Android中APK簡介

Android應(yīng)用Apk的安裝有如下四種方式:

1.1 系統(tǒng)應(yīng)用安裝

沒有安裝界面,在開機時自動完成

1.2 網(wǎng)絡(luò)下載應(yīng)用安裝

沒有安裝界面,在應(yīng)用市場完成

1.3 ADB命令安裝

沒有安裝界面,通過命令直接安裝

1.4 外部設(shè)備安裝

有安裝界面,通過SD卡等外部設(shè)備安裝,由packageInstaller處理安裝邏輯

2. APK安裝涉及到的幾個常用目錄

  • system/app : 系統(tǒng)自帶的應(yīng)用程序,獲得root權(quán)限才能刪除

  • data/app : 用戶程序安裝目錄,安裝時會把apk文件復(fù)制到此目錄下

  • data/data : 存放應(yīng)用程序的數(shù)據(jù)

  • data/dalvik-cache : 將apk中的dex文件安裝到該目錄下(dex文件是dalvik虛擬機的可執(zhí)行文件,大小約為原始apk的四分之一)

3. APK安裝的四大步驟

(1)拷貝apk到指定的目錄

默認情況下,用戶安裝的apk首先會拷貝到/data/app下,用戶有訪問/data/app目錄的權(quán)限,但系統(tǒng)出廠的apk文件 會被放到/system分區(qū)下,包括/system/app,/system/vendor/app,以及/system/priv-app等。該分區(qū)需要 root權(quán)限的用戶才能訪問。

(2)加壓apk、拷貝文件、創(chuàng)建應(yīng)用的數(shù)據(jù)目錄

為了加快APP的啟動速度,apk在安裝的時候,會首先將APP的可執(zhí)行文件(dex)拷貝到/data/dalvik-cache目錄 下,緩存起來。再在/data/data/目錄下創(chuàng)建應(yīng)用程序的數(shù)據(jù)目錄(以應(yīng)用包名命令),用來存放應(yīng)用的數(shù)據(jù)庫、xml 文件、cache、二進制的so動態(tài)庫等。

(3)解析apk的AndroidManifest.xml文件

在安裝apk的過程中,會解析apk的AndroidManifest.xml文件,將apk的權(quán)限、應(yīng)用包名、apk的安裝位置、版本、 userID等重要信息保存在/data/system/packages.xml文件中。這些操作都是在PackageManagerService中完成 的。

(4)顯示icon圖標

應(yīng)用程序經(jīng)過PMS中的邏輯處理后,相當于已經(jīng)注冊好了,如果想要在Android桌面上看到icon圖標,則需要 Launcher將系統(tǒng)中已經(jīng)安裝的程序展現(xiàn)在桌面上。

4. APK安裝的預(yù)備知識點

(1)PackageManagerService是由SystemServer啟動,PMS負責應(yīng)用的安裝、卸載、權(quán)限檢查等工作

(2)在/system/app和/data/app目錄下的apk文件,PMS在啟動過程中,都會掃描安裝

(3)每次開機時,PMS都會在構(gòu)造函數(shù)中對指定目錄下的apk進行掃描,沒有安裝的apk就會觸發(fā)安裝。

(4) 本文的源碼是基于Android6.0

5. 系統(tǒng)應(yīng)用安裝

在創(chuàng)建PackageManagerService實例時,會在PMS的構(gòu)造函數(shù)中開始執(zhí)行安裝應(yīng)用程序的邏輯。在PMS的構(gòu)造函數(shù)中做了如下幾點重要操作。

(1)創(chuàng)建Settings對象,添加shareUserId

mSettings = new Settings(mPackages);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);

(2)通過PackageManagerService構(gòu)造函數(shù)參數(shù)獲取應(yīng)用安裝器Installer

mInstaller = installer;

(3)獲取SystemConfig實例,讀取“/system/etc/permissions/*.xml”資源文件

從資源文件中獲取mGlobalsGids(Group-ids)、mSystemPermissions(系統(tǒng)權(quán)限)、mAvailableFeatures(系統(tǒng)支持的features)屬性。

SystemConfig systemConfig = SystemConfig.getInstance();mGlobalGids = systemConfig.getGlobalGids();mSystemPermissions = systemConfig.getSystemPermissions();mAvailableFeatures = systemConfig.getAvailableFeatures();

(4)創(chuàng)建系統(tǒng)消息處理線程

mHandlerThread = new ServiceThread(TAG,Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);mHandlerThread.start();mHandler = new PackageHandler(mHandlerThread.getLooper());Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);

(5)執(zhí)行com.android.server.pm.Settings中的readLPw方法,讀取安裝包中的信息,并解析成對應(yīng)的數(shù)據(jù)結(jié)構(gòu)。

File dataDir = Environment.getDataDirectory();mAppDataDir = new File(dataDir, "data");mAppInstallDir = new File(dataDir, "app");mAppLib32InstallDir = new File(dataDir, "app-lib");mAsecInternalPath = new File(dataDir, "app-asec").getPath();mUserAppDataDir = new File(dataDir, "user");mDrmAppPrivateInstallDir = new File(dataDir, "app-private");sUserManager = new UserManagerService(context, this,mInstallLock, mPackages);// Propagate permission configuration in to package manager.ArrayMap<String, SystemConfig.PermissionEntry> permConfig= systemConfig.getPermissions();for (int i=0; i<permConfig.size(); i++) {SystemConfig.PermissionEntry perm = permConfig.valueAt(i);BasePermission bp = mSettings.mPermissions.get(perm.name);if (bp == null) {bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);mSettings.mPermissions.put(perm.name, bp);}if (perm.gids != null) {bp.setGids(perm.gids, perm.perUser);}}ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();for (int i=0; i<libConfig.size(); i++) {mSharedLibraries.put(libConfig.keyAt(i),new SharedLibraryEntry(libConfig.valueAt(i), null));}mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),mSdkVersion, mOnlyCore);

其中,讀取的重要文件有如下幾個:

  • packages.xml:記錄了系統(tǒng)中所有安裝應(yīng)用的信息,包括基本信息、簽名和權(quán)限。

  • packages-backup.xml:packages.xml的備份文件

  • packages.list:保存普通應(yīng)用的數(shù)據(jù)目錄和uid等信息

  • packages-stopped.xml:記錄系統(tǒng)中被強制停止運行應(yīng)用的信息。系統(tǒng)在強制停止某個應(yīng)用時,會將應(yīng)用的信息記錄到該文件中

  • packages-stopped-backup.xml:packages-stopped.xml的備份文件

這幾個目錄在創(chuàng)建Settings對象時就已經(jīng)被封裝成了對應(yīng)的File文件。

(6)執(zhí)行PMS中的scanDirLI方法掃描系統(tǒng)安裝目錄和非系統(tǒng)apk信息

File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM| PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);// Find base frameworks (resource packages without code).scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM| PackageParser.PARSE_IS_SYSTEM_DIR| PackageParser.PARSE_IS_PRIVILEGED,scanFlags | SCAN_NO_DEX, 0);// Collected privileged system packages.final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM| PackageParser.PARSE_IS_SYSTEM_DIR| PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);// Collect ordinary system packages.final File systemAppDir = new File(Environment.getRootDirectory(), "app");scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM| PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);// Collect all vendor packages.File vendorAppDir = new File("/vendor/app");try {vendorAppDir = vendorAppDir.getCanonicalFile();} catch (IOException e) {// failed to look up canonical path, continue with original one}scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM| PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);// Collect all OEM packages.final File oemAppDir = new File(Environment.getOemDirectory(), "app");scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM| PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);

其中,系統(tǒng)安裝目錄有:

  • /system/framework 系統(tǒng)庫

  • /system/app 默認的系統(tǒng)應(yīng)用

  • /vendor/app 廠商定制的應(yīng)用

非系統(tǒng)apk信息目錄:

  • /data/app/

  • /system/priv-app/

  • /data/app-private/

到此為止,PMS構(gòu)造函數(shù)中主要的邏輯操作就介紹完了。

繼續(xù)探究掃描安裝過程:

(1)深入到PackageManagerService—>scanDirLI方法中

private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {final File[] files = dir.listFiles();if (ArrayUtils.isEmpty(files)) {Log.d(TAG, "No files in app dir " + dir);return;}if (DEBUG_PACKAGE_SCANNING) {Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags+ " flags=0x" + Integer.toHexString(parseFlags));}for (File file : files) {final boolean isPackage = (isApkFile(file) || file.isDirectory())&& !PackageInstallerService.isStageName(file.getName());if (!isPackage) {// Ignore entries which are not packagescontinue;}try {scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,scanFlags, currentTime, null);//注釋1} catch (PackageManagerException e) {Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());// Delete invalid userdata appsif ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);if (file.isDirectory()) {mInstaller.rmPackageDir(file.getAbsolutePath());} else {file.delete();}}}} }

注釋1處,對于目錄中的每一個文件,如果是已apk作為后綴名的,就會調(diào)用PackageManagerService—>scanPackageLI方法進行掃描解析

(2)深入到PackageManagerService—>scanPackageLI方法中

private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,long currentTime, UserHandle user) throws PackageManagerException {if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);parseFlags |= mDefParseFlags;PackageParser pp = new PackageParser();//注釋1pp.setSeparateProcesses(mSeparateProcesses);pp.setOnlyCoreApps(mOnlyCore);pp.setDisplayMetrics(mMetrics);if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;}final PackageParser.Package pkg;try {pkg = pp.parsePackage(scanFile, parseFlags);//注釋2} catch (PackageParserException e) {throw PackageManagerException.from(e);}......省略...... // readersynchronized (mPackages) {//注釋3// Look to see if we already know about this package.String oldName = mSettings.mRenamedPackages.get(pkg.packageName);if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {// This package has been renamed to its original name. Let's// use that.ps = mSettings.peekPackageLPr(oldName);}// If there was no original package, see one for the real package name.if (ps == null) {ps = mSettings.peekPackageLPr(pkg.packageName);}// Check to see if this package could be hiding/updating a system// package. Must look for it either under the original or real// package name depending on our state.updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);}......省略...... PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags| SCAN_UPDATE_SIGNATURE, currentTime, user);//注釋4/** If the system app should be overridden by a previously installed* data, hide the system app now and let the /data/app scan pick it up* again.*/if (shouldHideSystemApp) {synchronized (mPackages) {mSettings.disableSystemPackageLPw(pkg.packageName);}}return scannedPkg; }

注釋1處:創(chuàng)建一個PackageParser實例。

注釋2處調(diào)用PackageParser的parsePackage函數(shù)來對apk安裝包的AndroidManifest.xml文件掃描和提取證書信息,然后構(gòu)建一個PackageParser.Package對象,并將其返回。

注釋3將解析返回的PackageParser對象中的信息保存到PMS中。

注釋4調(diào)用另一個重載的scanPackageLI方法來構(gòu)建一個PackageSetting對象,這個對象保存的信息最后會通過writeLPr寫入到/data/system/packages.xml文件中去。

(3)根據(jù)(2)中注釋2深入到PackageParser—>parsePackage方法中

public Package parsePackage(File packageFile, int flags) throws PackageParserException {if (packageFile.isDirectory()) {return parseClusterPackage(packageFile, flags);} else {return parseMonolithicPackage(packageFile, flags);} }

這里根據(jù)packageFile是否是目錄分別調(diào)用parseClusterPackage和parseMonolithicPackage去解析。

其中parseClusterPackage方法如下:

private Package parseClusterPackage(File packageDir, int flags) throws PackageParserException {final PackageLite lite = parseClusterPackageLite(packageDir, 0);if (mOnlyCoreApps && !lite.coreApp) {throw new PackageParserException(INSTALL_PARSE_FAILED_MANIFEST_MALFORMED,"Not a coreApp: " + packageDir);}final AssetManager assets = new AssetManager();try {...省略...final File baseApk = new File(lite.baseCodePath);final Package pkg = parseBaseApk(baseApk, assets, flags);//注釋1if (pkg == null) {throw new PackageParserException(INSTALL_PARSE_FAILED_NOT_APK,"Failed to parse base APK: " + baseApk);}...省略...pkg.codePath = packageDir.getAbsolutePath();return pkg;} finally {IoUtils.closeQuietly(assets);} }

parseMonolithicPackage方法如下:

public Package parseMonolithicPackage(File apkFile, int flags) throws PackageParserException {...省略...final AssetManager assets = new AssetManager();try {final Package pkg = parseBaseApk(apkFile, assets, flags);//注釋2pkg.codePath = apkFile.getAbsolutePath();return pkg;} finally {IoUtils.closeQuietly(assets);} }

從parseClusterPackage的注釋1和parseMonolithicPackage的注釋2可以看出都是調(diào)用parseBaseApk去解析。

繼續(xù)探究parseBaseApk方法:

private Package parseBaseApk(File apkFile, AssetManager assets, int flags)throws PackageParserException {...省略...try {res = new Resources(assets, mMetrics, null);assets.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,Build.VERSION.RESOURCES_SDK_INT);parser = assets.openXmlResourceParser(cookie, ANDROID_MANIFEST_FILENAME);final String[] outError = new String[1];final Package pkg = parseBaseApk(res, parser, flags, outError);//注釋1if (pkg == null) {throw new PackageParserException(mParseError,apkPath + " (at " + parser.getPositionDescription() + "): " + outError[0]);}...省略...} catch (PackageParserException e) {throw e;} catch (Exception e) {throw new PackageParserException(INSTALL_PARSE_FAILED_UNEXPECTED_EXCEPTION,"Failed to read manifest from " + apkPath, e);} finally {IoUtils.closeQuietly(parser);} }

注釋1處調(diào)用另一個重載的parseBaseApk方法對apk進行解析。

(4)根據(jù)(2)中注釋4深入到PackageManagerService—>另一個scanPackageLI方法中

private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {boolean success = false;try {final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,currentTime, user);//注釋1success = true;return res;} finally {if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {removeDataDirsLI(pkg.volumeUuid, pkg.packageName);}} }

由注釋1繼續(xù)深入PackageManagerService—>scanPackageDirtyLI方法中:

private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {final File scanFile = new File(pkg.codePath);......省略......// And now re-install the app.ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,HasSystemUidErrors = true;//注釋1......省略......//invoke installer to do the actual installationint ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,pkg.applicationInfo.seinfo);//注釋2if (ret < 0) {// Error from installerthrow new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,"Unable to create data dirs [errorCode=" + ret + "]");}......省略...... }

從注釋1和注釋2處看出調(diào)用了PMS中的createDataDirsLI方法,給installed發(fā)送消息,為應(yīng)用程序創(chuàng)建對應(yīng)的數(shù)據(jù)目錄,如果目錄已經(jīng)存在,也會重新創(chuàng)建一遍。

深入到PMS的createDataDirsLI方法中:

private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {int[] users = sUserManager.getUserIds();int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);//注釋1if (res < 0) {return res;}for (int user : users) {if (user != 0) {res = mInstaller.createUserData(volumeUuid, packageName,//注釋2UserHandle.getUid(user, uid), user, seinfo);if (res < 0) {return res;}}}return res; }

從上面可知調(diào)用mInstaller.install()函數(shù)完成APK安裝。

到此為止,系統(tǒng)應(yīng)用的安裝流程差不多就完成了。

6. 網(wǎng)絡(luò)下載應(yīng)用安裝

網(wǎng)絡(luò)應(yīng)用下載完成后,會自動調(diào)用PackageManagerService中的installPackage方法:

@Override public void installPackage(String originPath, IPackageInstallObserver2 observer,int installFlags, String installerPackageName, VerificationParams verificationParams,String packageAbiOverride) {installPackageAsUser(originPath, observer, installFlags, installerPackageName,verificationParams, packageAbiOverride, UserHandle.getCallingUserId()); }

可以看到主要是調(diào)用了PMS—>installPackageAsUser方法:

public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,int installFlags, String installerPackageName, VerificationParams verificationParams,String packageAbiOverride, int userId) {mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);......省略......final Message msg = mHandler.obtainMessage(INIT_COPY);msg.obj = new InstallParams(origin, null, observer, params.installFlags,installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride,params.grantedRuntimePermissions);mHandler.sendMessage(msg); }

主要是獲取用戶安裝位置,將InstallParams對象封裝在Message里,然后發(fā)一個Handler消息。

深入到處理INIT_COPY的地方:PMS—>doHandleMessage方法中:

void doHandleMessage(Message msg) {switch (msg.what) {case INIT_COPY: {......省略...... if (!mBound) {// If this is the only one pending we might// have to bind to the service again.if (!connectToService()) {Slog.e(TAG, "Failed to bind to media container service");params.serviceError();return;} else {// Once we bind to the service, the first// pending request will be processed.mPendingInstalls.add(idx, params);}} else {mPendingInstalls.add(idx, params);// Already bound to the service. Just make// sure we trigger off processing the first request.if (idx == 0) {mHandler.sendEmptyMessage(MCS_BOUND);}}break;}case MCS_BOUND: {if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");if (msg.obj != null) {mContainerService = (IMediaContainerService) msg.obj;}if (mContainerService == null) {......省略......} else if (mPendingInstalls.size() > 0) {HandlerParams params = mPendingInstalls.get(0);if (params != null) {if (params.startCopy()) {//注釋1// We are done... look for more work or to// go idle.if (DEBUG_SD_INSTALL) Log.i(TAG,"Checking for more work or unbind...");// Delete pending installif (mPendingInstalls.size() > 0) {mPendingInstalls.remove(0);}if (mPendingInstalls.size() == 0) {if (mBound) {if (DEBUG_SD_INSTALL) Log.i(TAG,"Posting delayed MCS_UNBIND");removeMessages(MCS_UNBIND);Message ubmsg = obtainMessage(MCS_UNBIND);// Unbind after a little delay, to avoid// continual thrashing.sendMessageDelayed(ubmsg, 10000);}} else {// There are more pending requests in queue.// Just post MCS_BOUND message to trigger processing// of next pending install.if (DEBUG_SD_INSTALL) Log.i(TAG,"Posting MCS_BOUND for next work");mHandler.sendEmptyMessage(MCS_BOUND);}}}} else {// Should never happen ideally.Slog.w(TAG, "Empty queue");}break;}

如果msg.what是INIT_COPY:

則連接DefaultContainerService服務(wù),將我們要安裝的信息方法HandlerParams的mPendingInstalls中,然后再發(fā)送MCS_BOUND消息。

如果msg.what是MCS_BOUND:

則通過HandlerParams params = mPendingInstalls.get(0)獲取要安裝包的信息,然后清除包信息,如果還有其他包,則繼續(xù)發(fā)MCS_BOUND消息,一直循環(huán),直到安裝包都安裝完。

然后再調(diào)用PackageManagerService.HandlerParams—>startCopy方法:

final boolean startCopy() {boolean res;try {if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);if (++mRetries > MAX_RETRIES) {Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");mHandler.sendEmptyMessage(MCS_GIVE_UP);handleServiceError();return false;} else {handleStartCopy();//注釋1res = true;}} catch (RemoteException e) {if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");mHandler.sendEmptyMessage(MCS_RECONNECT);res = false;}handleReturnCode();//注釋2return res;}

其中startCopy中有兩個重要的方法handleStartCopy和handleReturnCode。

handleStartCopy中會檢查應(yīng)用是否能安裝成功,如果不能安裝成功,則會返回failed的CODE;返回res標識,判斷是否安裝成功。

handleReturnCode方法有兩處重載了,一個是刪除時調(diào)用的,一個是安裝時調(diào)用的,下面列出安裝的地方:

@Overridevoid handleReturnCode() {// If mArgs is null, then MCS couldn't be reached. When it// reconnects, it will try again to install. At that point, this// will succeed.if (mArgs != null) {processPendingInstall(mArgs, mRet);}}

可以看到調(diào)用了processPendingInstall方法:

private void processPendingInstall(final InstallArgs args, final int currentStatus) {// Queue up an async operation since the package installation may take a little while.mHandler.post(new Runnable() {public void run() {mHandler.removeCallbacks(this);// Result object to be returnedPackageInstalledInfo res = new PackageInstalledInfo();res.returnCode = currentStatus;res.uid = -1;res.pkg = null;res.removedInfo = new PackageRemovedInfo();if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {args.doPreInstall(res.returnCode);synchronized (mInstallLock) {installPackageLI(args, res);//注釋1}args.doPostInstall(res.returnCode, res.uid);}......省略...... }

從注釋1處可以看到,調(diào)用的是installPackageLI方法:

private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {......省略......if (replace) {replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,installerPackageName, volumeUuid, res);} else {installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,args.user, installerPackageName, volumeUuid, res);}......省略...... }

如果是替換安裝,則走replacePackageLI的邏輯。追蹤replacePackageLI的邏輯流程:

  • replacePackageLI—>如果是系統(tǒng)應(yīng)用則調(diào)用replaceSystemPackageLI—>再調(diào)用PackageParser.Package的scanPackageLI方法。

  • replacePackageLI—>如果是非系統(tǒng)應(yīng)用則調(diào)用replaceNonSystemPackageLI—>再調(diào)用PackageParser.Package的scanPackageLI方法。

如果是第一次安裝,則走installNewPackageLI。追蹤installNewPackageLI的邏輯流程:

  • installNewPackageLI—>再調(diào)用PackageParser.Package的scanPackageLI方法。

到了調(diào)用PackageParser.Package的scanPackageLI方法就到了系統(tǒng)應(yīng)用安裝過程中的“繼續(xù)探究掃描安裝過程”邏輯,后面的安裝邏輯就與系統(tǒng)應(yīng)用安裝的邏輯一樣了。

7. 通過命令安裝應(yīng)用

命令安裝應(yīng)用的入口是:

framework/base/cmds/pm/src/com/android/commands/pm/Pm.java

應(yīng)用安裝的時候就會調(diào)用runInstall()方法:

private int runInstall() {......省略......try {VerificationParams verificationParams = new VerificationParams(verificationURI,originatingURI, referrerURI, VerificationParams.NO_UID, null);mPm.installPackageAsUser(apkFilePath, obs.getBinder(), installFlags,installerPackageName, verificationParams, abi, userId);//注釋1......省略...... } catch (RemoteException e) {System.err.println(e.toString());System.err.println(PM_NOT_RUNNING_ERR);return 1;} }

從注釋1處可以看到安裝邏輯調(diào)用的是PackageManagerService—>installPackageAsUser方法。后面的調(diào)用邏輯就與“網(wǎng)絡(luò)下載應(yīng)用安裝”的邏輯一樣了。

8. 通過外部設(shè)備安裝應(yīng)用

通過外部設(shè)備安裝應(yīng)用,調(diào)用的是Android內(nèi)部的PackageInstaller去完成的,其本身也是一個apk。代碼位置在

/packages/apps/PackageInstaller/

用于顯示安裝apk,但其最終的本質(zhì)還是調(diào)用PackageManagerService去完成安裝的。

當點擊文件管理器中的apk時,文件管理器就會啟動PackageInstaller中的PackageInstallerActivity,并將apk的信息通過intent傳遞給PackageInstallerActivity。

(1)深入到PackageInstallerActivity—>onCreate方法:

@Override protected void onCreate(Bundle icicle) {super.onCreate(icicle);mPm = getPackageManager();mInstaller = mPm.getPackageInstaller();//注釋1mUserManager = (UserManager) getSystemService(Context.USER_SERVICE);final Intent intent = getIntent();//注釋2if (PackageInstaller.ACTION_CONFIRM_PERMISSIONS.equals(intent.getAction())) {final int sessionId = intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1);final PackageInstaller.SessionInfo info = mInstaller.getSessionInfo(sessionId);if (info == null || !info.sealed || info.resolvedBaseCodePath == null) {Log.w(TAG, "Session " + mSessionId + " in funky state; ignoring");finish();return;}mSessionId = sessionId;mPackageURI = Uri.fromFile(new File(info.resolvedBaseCodePath));mOriginatingURI = null;mReferrerURI = null;} else {mSessionId = -1;mPackageURI = intent.getData();mOriginatingURI = intent.getParcelableExtra(Intent.EXTRA_ORIGINATING_URI);mReferrerURI = intent.getParcelableExtra(Intent.EXTRA_REFERRER);}final boolean unknownSourcesAllowedByAdmin = isUnknownSourcesAllowedByAdmin();final boolean unknownSourcesAllowedByUser = isUnknownSourcesEnabled();//注釋3boolean requestFromUnknownSource = isInstallRequestFromUnknownSource(intent);......省略.....// Block the install attempt on the Unknown Sources setting if necessary.if (!requestFromUnknownSource) {initiateInstall();//注釋4return;}......省略.....if (!unknownSourcesAllowedByAdmin|| (!unknownSourcesAllowedByUser && isManagedProfile)) {showDialogInner(DLG_ADMIN_RESTRICTS_UNKNOWN_SOURCES);mInstallFlowAnalytics.setFlowFinished(InstallFlowAnalytics.RESULT_BLOCKED_BY_UNKNOWN_SOURCES_SETTING);} else if (!unknownSourcesAllowedByUser) {// Ask user to enable setting firstshowDialogInner(DLG_UNKNOWN_SOURCES);mInstallFlowAnalytics.setFlowFinished(InstallFlowAnalytics.RESULT_BLOCKED_BY_UNKNOWN_SOURCES_SETTING);} else {initiateInstall();//注釋5} }

注釋1:獲取PackageInstaller對象

注釋2:PackageInstaller檢查權(quán)限

注釋3:PackageInstaller檢查是否開啟未知來源

注釋4、注釋5:調(diào)用initiateInstall方法

(2)深入到PackageInstallerActivity—>initiateInstall方法

private void initiateInstall() {String pkgName = mPkgInfo.packageName;// Check if there is already a package on the device with this name// but it has been renamed to something else.String[] oldName = mPm.canonicalToCurrentPackageNames(new String[] { pkgName });if (oldName != null && oldName.length > 0 && oldName[0] != null) {pkgName = oldName[0];mPkgInfo.packageName = pkgName;mPkgInfo.applicationInfo.packageName = pkgName;}// Check if package is already installed. display confirmation dialog if replacing pkgtry {// This is a little convoluted because we want to get all uninstalled// apps, but this may include apps with just data, and if it is just// data we still want to count it as "installed".mAppInfo = mPm.getApplicationInfo(pkgName,PackageManager.GET_UNINSTALLED_PACKAGES);if ((mAppInfo.flags&ApplicationInfo.FLAG_INSTALLED) == 0) {mAppInfo = null;}} catch (NameNotFoundException e) {mAppInfo = null;}mInstallFlowAnalytics.setReplace(mAppInfo != null);mInstallFlowAnalytics.setSystemApp((mAppInfo != null) && ((mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0));startInstallConfirm();//調(diào)用 }

initiateInstall方法主要負責檢查是否已經(jīng)安裝過,是否是系統(tǒng)應(yīng)用等。然后繼續(xù)調(diào)用了startInstallConfirm方法。

(3) 深入到PackageInstallerActivity—>startInstallConfirm方法

private void startInstallConfirm() {TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);tabHost.setup();ViewPager viewPager = (ViewPager)findViewById(R.id.pager);TabsAdapter adapter = new TabsAdapter(this, tabHost, viewPager);adapter.setOnTabChangedListener(new TabHost.OnTabChangeListener() {@Overridepublic void onTabChanged(String tabId) {if (TAB_ID_ALL.equals(tabId)) {mInstallFlowAnalytics.setAllPermissionsDisplayed(true);} else if (TAB_ID_NEW.equals(tabId)) {mInstallFlowAnalytics.setNewPermissionsDisplayed(true);}}});// If the app supports runtime permissions the new permissions will// be requested at runtime, hence we do not show them at install.boolean supportsRuntimePermissions = mPkgInfo.applicationInfo.targetSdkVersion>= Build.VERSION_CODES.M;boolean permVisible = false;mScrollView = null;mOkCanInstall = false;int msg = 0;AppSecurityPermissions perms = new AppSecurityPermissions(this, mPkgInfo);final int N = perms.getPermissionCount(AppSecurityPermissions.WHICH_ALL);if (mAppInfo != null) {msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0? R.string.install_confirm_question_update_system: R.string.install_confirm_question_update;mScrollView = new CaffeinatedScrollView(this);mScrollView.setFillViewport(true);boolean newPermissionsFound = false;if (!supportsRuntimePermissions) {newPermissionsFound =(perms.getPermissionCount(AppSecurityPermissions.WHICH_NEW) > 0);mInstallFlowAnalytics.setNewPermissionsFound(newPermissionsFound);if (newPermissionsFound) {permVisible = true;mScrollView.addView(perms.getPermissionsView(AppSecurityPermissions.WHICH_NEW));}}if (!supportsRuntimePermissions && !newPermissionsFound) {LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);TextView label = (TextView)inflater.inflate(R.layout.label, null);label.setText(R.string.no_new_perms);mScrollView.addView(label);}adapter.addTab(tabHost.newTabSpec(TAB_ID_NEW).setIndicator(getText(R.string.newPerms)), mScrollView);} else {findViewById(R.id.tabscontainer).setVisibility(View.GONE);findViewById(R.id.divider).setVisibility(View.VISIBLE);}if (!supportsRuntimePermissions && N > 0) {permVisible = true;LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);View root = inflater.inflate(R.layout.permissions_list, null);if (mScrollView == null) {mScrollView = (CaffeinatedScrollView)root.findViewById(R.id.scrollview);}((ViewGroup)root.findViewById(R.id.permission_list)).addView(perms.getPermissionsView(AppSecurityPermissions.WHICH_ALL));adapter.addTab(tabHost.newTabSpec(TAB_ID_ALL).setIndicator(getText(R.string.allPerms)), root);}mInstallFlowAnalytics.setPermissionsDisplayed(permVisible);if (!permVisible) {if (mAppInfo != null) {// This is an update to an application, but there are no// permissions at all.msg = (mAppInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0? R.string.install_confirm_question_update_system_no_perms: R.string.install_confirm_question_update_no_perms;} else {// This is a new application with no permissions.msg = R.string.install_confirm_question_no_perms;}tabHost.setVisibility(View.GONE);mInstallFlowAnalytics.setAllPermissionsDisplayed(false);mInstallFlowAnalytics.setNewPermissionsDisplayed(false);findViewById(R.id.filler).setVisibility(View.VISIBLE);findViewById(R.id.divider).setVisibility(View.GONE);mScrollView = null;}if (msg != 0) {((TextView)findViewById(R.id.install_confirm_question)).setText(msg);}mInstallConfirm.setVisibility(View.VISIBLE);mOk = (Button)findViewById(R.id.ok_button);mOk.requestFocus();mCancel = (Button)findViewById(R.id.cancel_button);mOk.setOnClickListener(this);mCancel.setOnClickListener(this); //add by wangqi begin{@TabWidget tabWidget = tabHost.getTabWidget();int childCount = tabWidget.getChildCount();if (childCount == 2) {final View left = tabWidget.getChildAt(0);final View right = tabWidget.getChildAt(1);left.setId(tabWidget.getId() + 1);right.setId(tabWidget.getId() + 2);right.setNextFocusLeftId(left.getId());right.setOnKeyListener(new View.OnKeyListener() {@Overridepublic boolean onKey(View v, int keyCode, KeyEvent event) {if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN) {left.requestFocus();}return true;}});} // end @}if (mScrollView == null) {// There is nothing to scroll view, so the ok button is immediately// set to install.//mOk.setText(R.string.install);mOkCanInstall = true;} else {mScrollView.setFullScrollAction(new Runnable() {@Overridepublic void run() {//mOk.setText(R.string.install);mOkCanInstall = true;}});} }

startInstallConfirm主要負責界面初始化,顯示權(quán)限信息等。

界面初始化完成后,安裝界面就會呈現(xiàn)在用戶面前,如果用戶想要安裝這個應(yīng)用程序,可以直接點擊確認按鈕,此時就會調(diào)用PackageInstallerActivity中的onClick方法:

public void onClick(View v) {if (v == mOk) {if (mOkCanInstall || mScrollView == null) {mInstallFlowAnalytics.setInstallButtonClicked();if (mSessionId != -1) {mInstaller.setPermissionsResult(mSessionId, true);// We're only confirming permissions, so we don't really know how the// story ends; assume success.mInstallFlowAnalytics.setFlowFinishedWithPackageManagerResult(PackageManager.INSTALL_SUCCEEDED);finish();} else {startInstall();//注釋1}} else {mScrollView.pageScroll(View.FOCUS_DOWN);}} else if(v == mCancel) {// Cancel and finishsetResult(RESULT_CANCELED);if (mSessionId != -1) {mInstaller.setPermissionsResult(mSessionId, false);}mInstallFlowAnalytics.setFlowFinished(InstallFlowAnalytics.RESULT_CANCELLED_BY_USER);finish();} }

onClick方法中分別會對取消和確定按鈕做處理,如果是確定按鈕,就會調(diào)用注釋1處的startInstall方法。

(4) 深入到PackageInstallerActivity—>startInstall方法

private void startInstall() {// Start subactivity to actually install the applicationIntent newIntent = new Intent();newIntent.putExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO,mPkgInfo.applicationInfo);newIntent.setData(mPackageURI);newIntent.setClass(this, InstallAppProgress.class);//跳轉(zhuǎn)的ActivitynewIntent.putExtra(InstallAppProgress.EXTRA_MANIFEST_DIGEST, mPkgDigest);newIntent.putExtra(InstallAppProgress.EXTRA_INSTALL_FLOW_ANALYTICS, mInstallFlowAnalytics);String installerPackageName = getIntent().getStringExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME);......省略.....if(localLOGV) Log.i(TAG, "downloaded app uri="+mPackageURI);startActivity(newIntent);//注釋1finish(); }

startInstall方法啟動后,將會跳轉(zhuǎn)到注釋1處的InstallAppProgress界面。并關(guān)掉當前的PackageInstallerActivity

(5) 深入到InstallAppProgress.java文件中

當InstallAppProgress.java啟動時,會先調(diào)用InstallAppProgress.java—>onCreate方法:

@Override public void onCreate(Bundle icicle) {......省略.....initView(); }

onCreate方法中會調(diào)用initView方法初始化界面:

public void initView() {......省略.....if ("package".equals(mPackageURI.getScheme())) {try {pm.installExistingPackage(mAppInfo.packageName);observer.packageInstalled(mAppInfo.packageName,PackageManager.INSTALL_SUCCEEDED);} catch (PackageManager.NameNotFoundException e) {observer.packageInstalled(mAppInfo.packageName,PackageManager.INSTALL_FAILED_INVALID_APK);}} else {pm.installPackageWithVerificationAndEncryption(mPackageURI, observer, installFlags,installerPackageName, verificationParams, null);} }

可以看到有兩條安裝邏輯,我這里只探索else中的邏輯。else中實際上是調(diào)用了ApplicationPackageManager的installPackageWithVerificationAndEncryption方法來安裝。

(6) 深入到ApplicationPackageManager—>installPackageWithVerificationAndEncryption方法:

@Override public void installPackageWithVerificationAndEncryption(Uri packageURI,PackageInstallObserver observer, int flags, String installerPackageName,VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {installCommon(packageURI, observer, flags, installerPackageName, verificationParams,encryptionParams);//注釋1 }

注意installPackageWithVerificationAndEncryption方法上有個Override,說明繼承于父類的PackageManager中。

從注釋1中可以看到調(diào)用的是installCommon方法:

private void installCommon(Uri packageURI,PackageInstallObserver observer, int flags, String installerPackageName,VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {......省略.....try {mPM.installPackage(originPath, observer.getBinder(), flags, installerPackageName,verificationParams, null);//注釋1} catch (RemoteException ignored) {} }

從注釋1中可以看到調(diào)用的是PMS中的installPackage方法。到這里后續(xù)的邏輯就與前面的“網(wǎng)絡(luò)下載應(yīng)用安裝”中的邏輯一樣了。

總結(jié)

以上是生活随笔為你收集整理的从源码角度解析Android中APK安装过程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。