Bootstrap

Android 11.0 PackageManagerService(三)APK的安装过程

一. APK的安装步骤

安装步骤一:把APK的信息通过IO流的形式写入到PackageInstaller.Session中

安装步骤二:调用PackageInstaller.Session的commit方法,把APK的信息交给PackageManagerService处理

安装步骤三:进行Apk的Copy操作,进行安装

二. 点击安装后到完成APK的拷贝流程如下:

点击一个未安装的apk后,会弹出安装界面,点击确定按钮后,会进入PacakageInstallerActivity.java的bindUI()中的mAlert点击事件,点击apk后,弹出的安装界面底部显示的是一个Dialog,主要由bindUi构成,上面有取消和安装两个按钮,点击安装之后调用startInstall()进行安装。bingUi方法的代码如下:

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存在,执行setPermissionResult()完成取消安装
                        mInstaller.setPermissionsResult(mSessionId, false);
                    }
                    finish();
                }, null);
        setupAlert();

        mOk = mAlert.getButton(DialogInterface.BUTTON_POSITIVE);
        mOk.setEnabled(false);

        if (!mOk.isInTouchMode()) {
            mAlert.getButton(DialogInterface.BUTTON_NEGATIVE).requestFocus();
        }
}

startInstall方法组装了一个Intent,并跳转到 InstallInstalling 这个Activity,并关闭掉当前的PackageInstallerActivity。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);
        // 设置Intent中的class为InstallInstalling,用来进行Activity跳转
        newIntent.setClass(this, InstallInstalling.class);
        String installerPackageName = getIntent().getStringExtra(
                Intent.EXTRA_INSTALLER_PACKAGE_NAME);
        if (mOriginatingURI != null) {
            newIntent.putExtra(Intent.EXTRA_ORIGINATING_URI, mOriginatingURI);
        }
        if (mReferrerURI != null) {
            newIntent.putExtra(Intent.EXTRA_REFERRER, mReferrerURI);
        }
        if (mOriginatingUid != PackageInstaller.SessionParams.UID_UNKNOWN) {
            newIntent.putExtra(Intent.EXTRA_ORIGINATING_UID, mOriginatingUid);
        }
        if (installerPackageName != null) {
            newIntent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME,
                    installerPackageName);
        }
        if (getIntent().getBooleanExtra(Intent.EXTRA_RETURN_RESULT, false)) {
            newIntent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
        }
        newIntent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
        if(localLOGV) Log.i(TAG, "downloaded app uri="+mPackageURI);
        startActivity(newIntent);
        finish();
    }

InstallInstalling 的Activity启动后,进入onCreate方法

主要分为6步:

1. 如果savedInstanceState不为null,获取此前保存的mSessionId和mInstallId,其中mSessionId是安装包的会话Id,mInstallId是等待的安装事件Id

2. 根据mInstallId向InstallEventReceiver注册一个观察者,launchFinishBasedOnResult会接收到安装事件的回调,无论安装成功或者是安装失败都会关闭当前的Activity(InstallInstalling)。如果saveInstanceState为null,代码的逻辑也是类似的。

3.  创建SessionParams,它用来代表安装会话的参数,组装Params

4. 根据mPackageUri对包(APK)进行轻量级的解析,并将解析的参数赋值给SessionParams

5. 向InstallEventReceiver注册一个观察者返回一个新的mInstallId

6. PackageInstaller的createSession方法内部会通过IPackageInstallerService进行进程间通信,最终调用的是PackageInstallerService的createSession方法来创建并返回mSessionId

@Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ApplicationInfo appInfo = getIntent()
                .getParcelableExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO);
        mPackageURI = getIntent().getData();

        if ("package".equals(mPackageURI.getScheme())) {
            try {
                getPackageManager().installExistingPackage(appInfo.packageName);
                launchSuccess();
            } catch (PackageManager.NameNotFoundException e) {
                launchFailure(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, null);
            }
        } else {
            // 根据mPackageURI创建一个对应的File
            final File sourceFile = new File(mPackageURI.getPath());
            PackageUtil.AppSnippet as = PackageUtil.getAppSnippet(this, appInfo, sourceFile);

            mAlert.setIcon(as.icon);
            mAlert.setTitle(as.label);
            mAlert.setView(R.layout.install_content_view);
            mAlert.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.cancel),
                    (ignored, ignored2) -> {
                        if (mInstallingTask != null) {
                            mInstallingTask.cancel(true);
                        }

                        if (mSessionId > 0) {
                            getPackageManager().getPackageInstaller().abandonSession(mSessionId);
                            mSessionId = 0;
                        }

                        setResult(RESULT_CANCELED);
                        finish();
                    }, null);
            setupAlert();
            requireViewById(R.id.installing).setVisibility(View.VISIBLE);
            // 1. 如果savedInstanceState不为null,获取此前保存的mSessionId和mInstallId,
            // 其中mSessionId是安装包的会话Id,mInstallId是等待安装的事件Id
            if (savedInstanceState != null) {
                mSessionId = savedInstanceState.getInt(SESSION_ID);
                mInstallId = savedInstanceState.getInt(INSTALL_ID);

                // Reregister for result; might instantly call back if result was delivered while
                // activity was destroyed
                try {
                    // 2. 根据mInstallId向InstallEventReceiver注册一个观察者,           
                    // launchFinishBasedOnResult会接收到安装事件的回调,无论安装成功还是失败
                    // 都会关闭当前的Activity(InstallInstalling)。如果savedInstanceState为          
                    // null,代码的逻辑也是类似的
                    InstallEventReceiver.addObserver(this, mInstallId,
                            this::launchFinishBasedOnResult);
                } catch (EventResultPersister.OutOfIdsException e) {
                    // Does not happen
                }
            } else {
                //3. 创建SessionParams,它用来代表安装会话的参数,组装params
                PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
                        PackageInstaller.SessionParams.MODE_FULL_INSTALL);
                params.setInstallAsInstantApp(false);
                params.setReferrerUri(getIntent().getParcelableExtra(Intent.EXTRA_REFERRER));
                params.setOriginatingUri(getIntent()
                        .getParcelableExtra(Intent.EXTRA_ORIGINATING_URI));
                params.setOriginatingUid(getIntent().getIntExtra(Intent.EXTRA_ORIGINATING_UID,
                        UID_UNKNOWN));
                params.setInstallerPackageName(getIntent().getStringExtra(
                        Intent.EXTRA_INSTALLER_PACKAGE_NAME));
                params.setInstallReason(PackageManager.INSTALL_REASON_USER);
                // 4. 根据mPackageUri对包进行轻量级的解析,并将解析的参数赋值给SessionParams
                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 {
                    // 5. 向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 {
                    // 6. 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();
        }
    }

这里 PackageInstaller 的createSession()内部会通过 IPackageInstaller与 PackageInstallerService进行进程间通信,最终调用的是PackageInstallerService的createSession方法来创建并返回mSessionId。

接着在InstallInstalling的onResume方法中,调用onPostExecute()方法,将APK的信息通过IO流的形式写入到PackageInstaller.session中。onResume方法代码如下:

@Override
    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);
            }
        }
    }

InstallingAsyncTask 的DoInBackground()会根据包(APK)的Uri,将APK的信息通过IO流的形式写入到PackageInstaller.Session中最后在onPostExecute()中调用PackageInstaller.Session的commit方法,进行安装。InstallingAsyncTask代码如下:

private final class InstallingAsyncTask extends AsyncTask<Void, Void,
            PackageInstaller.Session> {
        volatile boolean isDone;

        @Override
        protected PackageInstaller.Session doInBackground(Void... params) {
            
            .........

            try {
                File file = new File(mPackageURI.getPath());

                try (InputStream in = new FileInputStream(file)) {
                    long sizeBytes = file.length();
                    try (OutputStream out = session
                            .openWrite("PackageInstaller", 0, sizeBytes)) {
                        byte[] buffer = new byte[1024 * 1024];
                        while (true) {
                            int numRead = in.read(buffer);

                            if (numRead == -1) {
                                session.fsync(out);
                                break;
                            }

                            if (isCancelled()) {
                                session.close();
                                break;
                            }
                            // 将APK的信息通过IO流的形式写入到PackageInstaller.Session中
                            out.write(buffer, 0, numRead);
                            if (sizeBytes > 0) {
                                float fraction = ((float) numRead / (float) sizeBytes);
                                session.addProgress(fraction);
                            }
                        }
                    }
                }

                return session;
            } catch (IOException | SecurityException e) {
                Log.e(LOG_TAG, "Could not write package", e);

                session.close();

                return null;
            } finally {
                synchronized (this) {
                    isDone = true;
                    notifyAll();
                }
            }
        }

        @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);
                // 调用PackageInstaller.Session的commit方法,进行安装
                session.commit(pendingIntent.getIntentSender());
                mCancelButton.setEnabled(false);
                setFinishOnTouchOutside(false);
            } else {
                ........
            }
        }
    }

接着看一下PackageInstaller.Session的commit方法

@Override
    public void commit(@NonNull IntentSender statusReceiver, boolean forTransfer) {
        
        ......

        if (!markAsSealed(statusReceiver, forTransfer)) {
            return;
        }
        if (isMultiPackage()) {
            
            .....

        }

        dispatchStreamValidateAndCommit();
    }

private void dispatchStreamValidateAndCommit() {
    // 向Handler中发送了一个类型为MSG_STREAM_VALIDATE_AND_COMMIT的消息
    mHandler.obtainMessage(MSG_STREAM_VALIDATE_AND_COMMIT).sendToTarget();
}

MSG_STREAM_VALIDATE_AND_COMMIT在Handler(mHandlerCallback)中进行处理,进入到handleStreamValidateAndCommit()方法

private final Handler.Callback mHandlerCallback = new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_STREAM_VALIDATE_AND_COMMIT:
                    // 处理MSG_STREAM_VALIDATE_AND_COMMIT消息
                    handleStreamValidateAndCommit();
                    break;
                case MSG_INSTALL:
                    handleInstall();
                    break;
                
                .....

            }

            return true;
        }
    };

handleStreamValidateAndCommit方法的代码如下:

private void handleStreamValidateAndCommit() {
        
        // 最终发送了一条MSG_INSTALL的消息给Handler

        mHandler.obtainMessage(MSG_INSTALL).sendToTarget();
    }

MSG_INSTALL在Handler(mHandlerCallback)中进行处理,进入到handleInstall方法。

private void handleInstall() {
        
        //.......

        // For a multiPackage session, read the child sessions
        // outside of the lock, because reading the child
        // sessions with the lock held could lead to deadlock
        // (b/123391593).
        List<PackageInstallerSession> childSessions = getChildSessionsNotLocked();

        try {
            synchronized (mLock) {
                // 调用了installNonStagedLocked方法
                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);
        }
    }

在handlerInstall方法中调用了installNonStageLocked方法。

private void installNonStagedLocked(List<PackageInstallerSession> childSessions)
            throws PackageManagerException {
        
        //。。。。。

         if (isMultiPackage()) {
            List<PackageManagerService.ActiveInstallSession> installingChildSessions =
                    new ArrayList<>(childSessions.size());
            boolean success = true;
            PackageManagerException failure = null;
            for (int i = 0; i < childSessions.size(); ++i) {
                final PackageInstallerSession session = childSessions.get(i);
                try {
                    final PackageManagerService.ActiveInstallSession installingChildSession =
                            session.makeSessionActiveLocked();
                    if (installingChildSession != null) {
                        installingChildSessions.add(installingChildSession);
                    }
                } catch (PackageManagerException e) {
                    failure = e;
                    success = false;
                }
            }
            if (!success) {
                sendOnPackageInstalled(mContext, mRemoteStatusReceiver, sessionId,
                        isInstallerDeviceOwnerOrAffiliatedProfileOwnerLocked(), userId, null,
                        failure.error, failure.getLocalizedMessage(), null);
                return;
            }
            // 调用了PackageManagerService的installStage方法
            mPm.installStage(installingChildSessions);
        } else {
            // 调用了PackageManagerService的installStage方法
            mPm.installStage(installingSession);
        }
    }

在最后调用了PackageManagerService的installStage方法,在此代码逻辑就回到了PackageManagerService。

void installStage(ActiveInstallSession activeInstallSession) {
        if (DEBUG_INSTANT) {
            if ((activeInstallSession.getSessionParams().installFlags
                    & PackageManager.INSTALL_INSTANT_APP) != 0) {
                Slog.d(TAG, "Ephemeral install of " + activeInstallSession.getPackageName());
            }
        }
        // 1. 创建了类型为INIT_COPY的消息
        final Message msg = mHandler.obtainMessage(INIT_COPY);
        // 2. 创建InstallParams,它对应于包的安装数据
        final InstallParams params = new InstallParams(activeInstallSession);
        params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params));
        msg.obj = params;

        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage",
                System.identityHashCode(msg.obj));
        Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall",
                System.identityHashCode(msg.obj));
        // 3. 将InstallParams通过消息发送出去
        mHandler.sendMessage(msg);
    }


        // 对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;
                }
            }
        }

在Handler中对INIT_COPY消息的处理中,调用了HandlerParams.startCopy方法。

final void startCopy() {
    if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
        handleStartCopy();
        handleReturnCode();
}

handleStartCopy()需要执行下面几步:

1. 首先检查文件和cid是否已经生成,如果生成则设置installFlags

2. 检查空间大小,如果空间不够就会释放无用的控件

3. 覆盖原有安装位置的文件,并根据返回结果来确定函数的返回值,并设置installFlags

4. 确定是否有任何已安装的包安装器,如果有,则延迟检测。主要分三步:

        1)首先新建一个验证Intent,然后设置相关的信息,

        2)之后获取验证器列表

        3)最后向每个验证器发送验证Intent。

public void handleStartCopy() {
            int ret = PackageManager.INSTALL_SUCCEEDED;

            // 1. 首先检查文件和cid是否已经生成,如生成则设置installFlags
            if (origin.staged) {
                if (origin.file != null) {
                    installFlags |= PackageManager.INSTALL_INTERNAL;
                } else {
                    throw new IllegalStateException("Invalid stage location");
                }
            }

            。。。。

            // 2. 检查空间大小,如果空间不够则释放无用空间
            if (!origin.staged && pkgLite.recommendedInstallLocation
                    == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
                // TODO: focus freeing disk space on the target device
                final StorageManager storage = StorageManager.from(mContext);
                final long lowThreshold = storage.getStorageLowBytes(
                        Environment.getDataDirectory());

                final long sizeBytes = PackageManagerServiceUtils.calculateInstalledSize(
                        origin.resolvedPath, packageAbiOverride);
                if (sizeBytes >= 0) {
                    try {
                        mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0);
                        pkgLite = PackageManagerServiceUtils.getMinimalPackageInfo(mContext,
                                origin.resolvedPath, installFlags, packageAbiOverride);
                    } catch (InstallerException e) {
                        Slog.w(TAG, "Failed to free cache", e);
                    }
                }

                if (pkgLite.recommendedInstallLocation
                        == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
                    pkgLite.recommendedInstallLocation
                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
                }
            }


            if (ret == PackageManager.INSTALL_SUCCEEDED) {

                .....
                
                    {
                    // 3. 覆盖原有安装位置的文件,并根据范湖结果来确定函数的返回值,
                    // 并设置installFlags
                    loc = installLocationPolicy(pkgLite);
                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
                    } else if (loc == PackageHelper.RECOMMEND_FAILED_WRONG_INSTALLED_VERSION) {
                        ret = PackageManager.INSTALL_FAILED_WRONG_INSTALLED_VERSION;
                    } else if (!onInt) {
                        // Override install location with flags
                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
                            // Set the flag to install on external media.
                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
                        } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) {
                            if (DEBUG_INSTANT) {
                                Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag");
                            }
                            installFlags |= PackageManager.INSTALL_INSTANT_APP;
                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
                        } else {
                            // Make sure the flag for installing on external
                            // media is unset
                            installFlags |= PackageManager.INSTALL_INTERNAL;
                        }
                    }
                }
            }

            final InstallArgs args = createInstallArgs(this);
            mVerificationCompleted = true;
            mIntegrityVerificationCompleted = true;
            mEnableRollbackCompleted = true;
            mArgs = args;

            if (ret == PackageManager.INSTALL_SUCCEEDED) {
                final int verificationId = mPendingVerificationToken++;

                // Perform package verification (unless we are simply moving the package).
                if (!origin.existing) {
                    PackageVerificationState verificationState =
                            new PackageVerificationState(this);
                    mPendingVerification.append(verificationId, verificationState);
                    // 发送一个请求来检查包的完整性
                    sendIntegrityVerificationRequest(verificationId, pkgLite, verificationState);
                    // 向验证者发送验证包的请求
                    ret = sendPackageVerificationRequest(
                            verificationId, pkgLite, verificationState);

                   
                }


                .....

            mRet = ret;
        }

在Android 11.0 中是通过sendPackageVerificationRequest来验证包的。

int sendPackageVerificationRequest(
                int verificationId,
                PackageInfoLite pkgLite,
                PackageVerificationState verificationState) {
            int ret = INSTALL_SUCCEEDED;

            .....            

            if (!origin.existing
                    && isVerificationEnabled
                    && (!isIncrementalInstall || !isV4Signed)) {
                // 4. 确定是否有任何已安装的包验证器,如有,则延迟检测。主要分三步:
                // 首先新建一个验证Intent,然后设置相关的信息,之后获取验证器列表
                // 最后向每个验证器发送验证Intent
                // 4.1 构造验证Intent
                final Intent verification = new Intent(
                        Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
                verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
                verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
                        PACKAGE_MIME_TYPE);
                verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

                ....

                populateInstallerExtras(verification);
                
                // 4.2 获取验证器列表
                final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
                        receivers, verificationState);

                DeviceIdleInternal idleController =
                        mInjector.getLocalDeviceIdleController();
                final long idleDuration = getVerificationTimeout();
                final BroadcastOptions options = BroadcastOptions.makeBasic();
                options.setTemporaryAppWhitelistDuration(idleDuration);

                /*
                 * If any sufficient verifiers were listed in the package
                 * manifest, attempt to ask them.
                 */
                if (sufficientVerifiers != null) {
                    final int n = sufficientVerifiers.size();
                    if (n == 0) {
                        Slog.i(TAG, "Additional verifiers required, but none installed.");
                        ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
                    } else {
                        for (int i = 0; i < n; i++) {
                            final ComponentName verifierComponent = sufficientVerifiers.get(i);
                            idleController.addPowerSaveTempWhitelistApp(Process.myUid(),
                                    verifierComponent.getPackageName(), idleDuration,
                                    verifierUser.getIdentifier(), false, "package verifier");
                            
                            // 4.3 向每个验证器发送验证Intent
                            // 向验证器客户端发送Intent,只有当验证成功之后才开启copy工作
                            // 如果没有任何验证器则直接拷贝
                            final Intent sufficientIntent = new Intent(verification);
                            sufficientIntent.setComponent(verifierComponent);
                            mContext.sendBroadcastAsUser(sufficientIntent, verifierUser,
                                    /* receiverPermission= */ null,
                                    options.toBundle());
                        }
                    }
                }

            .....                

            return ret;
        }

向验证器客户端发送Intent,只有当验证成功之后才会开启copy工作。如果没有任何验证器则直接拷贝。

在handleReturnCode中调用copyApk()进行APK的拷贝工作。

void handleReturnCode() {
            if (mVerificationCompleted
                    && mIntegrityVerificationCompleted && mEnableRollbackCompleted) {
                if ((installFlags & PackageManager.INSTALL_DRY_RUN) != 0) {
                    String packageName = "";
                    ParseResult<PackageLite> result = ApkLiteParseUtils.parsePackageLite(
                            new ParseTypeImpl(
                                    (changeId, packageName1, targetSdkVersion) -> {
                                        ApplicationInfo appInfo = new ApplicationInfo();
                                        appInfo.packageName = packageName1;
                                        appInfo.targetSdkVersion = targetSdkVersion;
                                        return mPackageParserCallback.isChangeEnabled(changeId,
                                                appInfo);
                                    }).reset(),
                            origin.file, 0);
                    if (result.isError()) {
                        Slog.e(TAG, "Can't parse package at " + origin.file.getAbsolutePath(),
                                result.getException());
                    } else {
                        packageName = result.getResult().packageName;
                    }
                    try {
                        observer.onPackageInstalled(packageName, mRet, "Dry run", new Bundle());
                    } catch (RemoteException e) {
                        Slog.i(TAG, "Observer no longer exists.");
                    }
                    return;
                }
                if (mRet == PackageManager.INSTALL_SUCCEEDED) {
                    // 调用copyApk方法
                    mRet = mArgs.copyApk();
                }
                processPendingInstall(mArgs, mRet);
            }
        }

调用了InstallArgs.copyApk方法,最终会调用到FileInstallArgs.copyApk方法。

        int copyApk() {
            Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk");
            try {
                // 调用doCopyApk方法
                return doCopyApk();
            } finally {
                Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER);
            }
        }

        private int doCopyApk() {
            
            .....

            // 调用PackageManagerServiceUtils.copyPackage方法
            int ret = PackageManagerServiceUtils.copyPackage(
                    origin.file.getAbsolutePath(), codeFile);
            if (ret != PackageManager.INSTALL_SUCCEEDED) {
                Slog.e(TAG, "Failed to copy package");
                return ret;
            }

            .....

            return ret;
        }

在doCopyApk方法中调用了PackageManagerServiceUtils.copyPackage方法,其代码如下:

public static int copyPackage(String packagePath, File targetDir) {
        if (packagePath == null) {
            return PackageManager.INSTALL_FAILED_INVALID_URI;
        }

        try {
            final File packageFile = new File(packagePath);
            final PackageParser.PackageLite pkg = PackageParser.parsePackageLite(packageFile, 0);
            copyFile(pkg.baseCodePath, targetDir, "base.apk");
            if (!ArrayUtils.isEmpty(pkg.splitNames)) {
                for (int i = 0; i < pkg.splitNames.length; i++) {
                    // 调用了copyFile方法
                    copyFile(pkg.splitCodePaths[i], targetDir,
                            "split_" + pkg.splitNames[i] + ".apk");
                }
            }
            return PackageManager.INSTALL_SUCCEEDED;
        } catch (PackageParserException | IOException | ErrnoException e) {
            Slog.w(TAG, "Failed to copy package at " + packagePath + ": " + e);
            return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
        }
    }

在copyFile方法中,通过文件流的操作,把APK拷贝到/data/app等目录

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的安装过程

APK拷贝完成后,进入真正的安装,流程如下:

在上述handleReturnCode方法中,执行了copyApk方法后,最后又执行了processPendingInstall方法。

private void processPendingInstall(final InstallArgs args, final int currentStatus) {
        if (args.mMultiPackageInstallParams != null) {
            args.mMultiPackageInstallParams.tryProcessInstallRequest(args, currentStatus);
        } else {
            // 1. 设置安装参数
            PackageInstalledInfo res = createPackageInstalledInfo(currentStatus);
            // 2. 创建一个新线程,处理安装参数,进行安装
            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) {
                    // 1. 如果之前安装失败,清除无用信息
                    request.args.doPreInstall(request.installResult.returnCode);
                }
                synchronized (mInstallLock) {
                    // 2. installPackagesTracedLI是安装过程的核心方法
                    // 然后调用installPackagesLI进行安装
                    installPackagesTracedLI(installRequests);
                }
                for (InstallRequest request : installRequests) {
                    // 3. 如果之前安装失败,清除无用信息
                    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));
            }
        });
    }

int doPreInstall(int status) {
            if (status != PackageManager.INSTALL_SUCCEEDED) {
                // 清除无用信息
                cleanUp();
            }
            return status;
        }

int doPostInstall(int status, int uid) {
            if (status != PackageManager.INSTALL_SUCCEEDED) {
                // 调用cleanUp清除无用信息
                cleanUp();
            }
            return status;
        }

在installPackagesLI方法中,以原子的方式安装一个或多个包。此操作分为四个阶段:

1)Prepare准备:分析任何当前安装状态,分析包并对其进行初始验证。

2)Scan 扫描:扫描分析准备阶段拿到的包

3) Reconcile 协调:包的扫描结果,用于协调可能向系统中添加的一个或多个包

4) Commit 提交:提交所有扫描的包并更新系统状态,这是安装流程中唯一可以修改系统状态的地方放,必须在此阶段之前确定所有的可预测的错误

5)完成APK的安装

private void installPackagesLI(List<InstallRequest> requests) {

    .....

    // 1. Prepare 准备:分析任何当前安装状态,分析包并对其进行初始验证
    prepareResult = preparePackageLI(request.args, request.installResult);
                
    .....               

    // 2. Scan 扫描:扫描分析准备阶段拿到的包
    final ScanResult result = scanPackageTracedLI(
                            prepareResult.packageToScan, prepareResult.parseFlags,
                            prepareResult.scanFlags, System.currentTimeMillis(),
                            request.args.user, request.args.abiOverride);
    ....    

    // 3. Reconcile 协调:包的扫描结果,用于协调可能向系统中添加的一个或多个包
    ReconcileRequest reconcileRequest = new ReconcileRequest(preparedScans, installArgs,
                    installResults,
                    prepareResults,
                    mSharedLibraries,
                    Collections.unmodifiableMap(mPackages), versionInfos,
                    lastStaticSharedLibSettings);
    
    ......

    // 4. Commit 提交:提交所有扫描的包并更新系统状态。这是安装流程中唯一可以修改系统状态的地方,
    // 必须在此阶段之前确定所有的可预测的错误
    commitPackagesLocked(commitRequest);
    
    .....

    // 5. 完成APK的安装
    executePostCommitSteps(commitRequest);
       
}

executePostCommitSteps 安装APK,并为新的代码路径准备应用程序配置文件,并在此检查是否需要dex优化。

如果是直接安装新包,会为新的代码路径准备应用程序配置文件;如果是替换安装,其主要过程为更新设置,清除原有的某些APP数据,重新生成相关的app数据目录等步骤,同时要区分系统应用替换和非系统应用替换。而安装新包,则直接更新设置,生成APP数据即可。

[PackageManagerService.java] executePostCommitSteps()

private void executePostCommitSteps(CommitRequest commitRequest) {
       
    for (ReconciledPackage reconciledPkg : commitRequest.reconciledPackages.values()) {
            
        ......

        1) 进行安装
        prepareAppDataAfterInstallLIF(pkg);
        2) 如果需要替换安装,则需要清除原有的App数据
        if (reconciledPkg.prepareResult.clearCodeCache) {
            clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE | FLAG_STORAGE_CE
                | FLAG_STORAGE_EXTERNAL | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
        }
        
        ...
            
        3) 为新的代码路径准备应用程序配置文件。这需要在调用dexopt之前完成,
           以便任何安装时配置文件都可以用于优化
        mArtManagerService.prepareAppProfiles(
                    pkg,
                    resolveUserIds(reconciledPkg.installArgs.user.getIdentifier()),
                    /* updateReferenceProfileContent= */ true);

        4) 检查是否需要优化dex文件
        final boolean performDexopt =
                    (!instantApp || Global.getInt(mContext.getContentResolver(),
                    Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0)
                    && !pkg.isDebuggable()
                    && (!onIncremental);

        if (performDexopt) {               


            5) 执行dex优化
            mPackageDexOptimizer.performDexOpt(pkg, realPkgSetting,
                        null /* instructionSets */,
                        getOrCreateCompilerPackageStats(pkg),
                        mDexManager.getPackageUseInfoOrDefault(packageName),
                        dexoptOptions);
                
        }

            
        BackgroundDexOptService.notifyPackageChanged(packageName);

        notifyPackageChangeObserversOnUpdate(reconciledPkg);
    }
}

PackageManagerService.prepareAppDataAfterInstallLIF()

通过一系列的调用,最终会调用到Installer.java的createAppData()方法进行安装,交给installed进程进行APK的安装。

调用过程如下:

prepareAppDataAfterInstallLIF()
    |
prepareAppDataLIF()
    |
prepareAppDataLeafLIF()
    |
[Installer.java]
createAppData()

private void prepareAppDataAfterInstallLIF(AndroidPackage pkg) {
        
    ..... 

    for (UserInfo user : mUserManager.getUsers(false /*excludeDying*/)) {
           
        ......

        if (ps.getInstalled(user.id)) {
            // TODO: when user data is locked, mark that we're still dirty
            prepareAppDataLIF(pkg, user.id, flags);
                
        }
    }
}


private void prepareAppDataLIF(AndroidPackage pkg, int userId, int flags) {
    if (pkg == null) {
        Slog.wtf(TAG, "Package was null!", new Throwable());
        return;
    }
    // 调用prepareAppDataLeafLIF方法
    prepareAppDataLeafLIF(pkg, userId, flags);
}


private void prepareAppDataLeafLIF(AndroidPackage pkg, int userId, int flags) {
        
    ......

    try {
        // 调用Install守护进程的入口
        ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags,
                    appId, seInfo, pkg.getTargetSdkVersion());
    } catch (InstallerException e) {
        if (pkg.isSystem()) {
             destroyAppDataLeafLIF(pkg, userId, flags);
             try {
                 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId,                 
                     flags,appId, seInfo, pkg.getTargetSdkVersion());
                    
             } catch (InstallerException e2) {
                 ......
             }
         }
    }
}
Installer.java 

public long createAppData(String uuid, String packageName, int userId, int flags, int     
        appId,String seInfo, int targetSdkVersion) throws InstallerException {
    if (!checkBeforeRemote()) return -1;
    try {
        // mInstalld为IInstall的对象,即通过Binder调用到进程installd,
        // 最终调用installd的createAppData()
        return mInstalld.createAppData(uuid, packageName, userId, flags, appId, seInfo,
                    targetSdkVersion);
    } catch (Exception e) {
        throw InstallerException.from(e);
    }
}

总结:

APK的安装主要分为以下四步:

1)将APK的信息通过IO流的形式写入到 PackageInstaller.Session中

2)调用PackageInstaller.Session的commit方法,将APK的信息交由PKMS处理。

3)拷贝APK

4)最后进行安装

最终是交给IInstalld守护进程进行真正的安装操作。

;