开篇
PackageManagerService 系列文章如下(基于 Android 9.0 源码)
? Framework 核心服务之 PackageManagerService 钻研(1)- 启动流程
? Framework 核心服务之 PackageManagerService 钻研(2)- 构造函数
? Framework 核心服务之 PackageManagerService 钻研(3)- PackageManager
? Framework 核心服务之 PackageManagerService 钻研(4)- PackageInstaller
? Framework 核心服务之 PackageManagerService 钻研(5)- APK 安装流程(PackageInstaller)
? Framework 核心服务之 PackageManagerService 钻研(6)- APK 安装流程(PMS)
? Framework 核心服务之 PackageManagerService 钻研(7)- PackageParser
核心源码
关键类 | 路径 |
---|---|
PackageInstaller.java | frameworks/base/core/java/android/content/pm/PackageInstaller.java |
PackageInstallerActivity.java | packages/apps/PackageInstaller/src/com/android/packageinstaller/PackageInstallerActivity.java |
InstallInstalling.java | packages/apps/PackageInstaller/src/com/android/packageinstaller/InstallInstalling.java |
PackageInstallerSession.java | frameworks/base/services/core/java/com/android/server/pm/PackageInstallerSession.java |
前言
在本系列上一篇文章【深入研究 PackageManagerService 系列(4)之 PackageInstaller 初始化】中,我们学习了 PackageInstaller 是如何初始化的,这一篇文章我们继续学习 PackageInstaller 是如何安装 APK 的。
PackageInstallerActivity
在上一篇文章的末尾阶段,我们知道 PackageInstallerActivity 调用startInstallConfirm 方法初始化安装确认界面后,这个安装确认界面就会呈现给用户,用户如果想要安装这个应用程序就会点击确定按钮,就会调用 PackageInstallerActivity 的 onClick 方法。
onClick
public void onClick(View v) {
if (v == mOk) {
if (mOk.isEnabled()) {
if (mOkCanInstall || mScrollView == null) {
if (mSessionId != -1) {
mInstaller.setPermissionsResult(mSessionId, true);
finish();
} else {
startInstall(); // ? ? ? ? ? ?
}
} else {
mScrollView.pageScroll(View.FOCUS_DOWN);
}
}
} else if (v == mCancel) {
// Cancel and finish
setResult(RESULT_CANCELED);
if (mSessionId != -1) {
mInstaller.setPermissionsResult(mSessionId, false);
}
finish();
}
}
onClick 方法中分别对"确定"和"取消"按钮做了处理,主要查看对"确定"按钮的处理,我们发现调用了 startInstall 方法。
startInstall
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 (mOriginatingURI != null) {
newIntent.putExtra(Intent.EXTRA_ORIGINATING_URI, mOriginatingURI);
}
... ...
if(localLOGV) Log.i(TAG, "downloaded app uri="+mPackageURI);
/**
* startInstall 方法用于跳转到 InstallInstalling 这个 Activity
*/
startActivity(newIntent);
finish(); // 关闭当前的 PackageInstallerActivity
}
InstallInstalling
InstallInstalling 主要用于向包管理器发送包的信息并处理包管理的回调。
onCreate
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.install_installing);
ApplicationInfo appInfo = getIntent()
.getParcelableExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO);
mPackageURI = getIntent().getData();
// 分别对 package 和 content 协议的 Uri 进行处理
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.initSnippetForNewApp(this, PackageUtil.getAppSnippet(this, appInfo,
sourceFile), R.id.app_snippet);
// 如果 savedInstanceState 不为 null,获取此前保存的 mSessionId 和 mInstallId
if (savedInstanceState != null) {
mSessionId = savedInstanceState.getInt(SESSION_ID); // mSessionId 是安装包的会话 id
mInstallId = savedInstanceState.getInt(INSTALL_ID); // mInstallId 是等待的安装事件 id
/**
* 根据 mInstallId 向 InstallEventReceiver 注册一个观察者
* launchFinishBasedOnResult 会接收到安装事件的回调,无论安装成功或者失败都会关闭当前的 Activity(InstallInstalling)
*/
try {
InstallEventReceiver.addObserver(this, mInstallId,
this::launchFinishBasedOnResult);
} catch (EventResultPersister.OutOfIdsException e) {
// Does not happen
}
} else {
// savedInstanceState 为 null
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
PackageInstaller.SessionParams.MODE_FULL_INSTALL);
params.referrerUri = getIntent().getParcelableExtra(Intent.EXTRA_REFERRER);
params.originatingUri = getIntent()
.getParcelableExtra(Intent.EXTRA_ORIGINATING_URI);
params.originatingUid = getIntent().getIntExtra(Intent.EXTRA_ORIGINATING_UID,
UID_UNKNOWN);
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 {
mInstallId = InstallEventReceiver
.addObserver(this, EventResultPersister.GENERATE_NEW_ID,
this::launchFinishBasedOnResult);
} catch (EventResultPersister.OutOfIdsException e) {
launchFailure(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, null);
}
try {
mSessionId = getPackageManager().getPackageInstaller().createSession(params);
} catch (IOException e) {
launchFailure(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, null);
}
}
... ...
mSessionCallback = new InstallSessionCallback();
}
}
onResume
我们查看 InstallInstalling 的 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();
// 根据 mSessionId 得到 SessionInfo,SessionInfo 代表安装会话的详细信息
PackageInstaller.SessionInfo sessionInfo = installer.getSessionInfo(mSessionId);
// 如果 sessionInfo 不为 Null 并且不是活动的,就创建并执行 InstallingAsyncTask
if (sessionInfo != null && !sessionInfo.isActive()) {
mInstallingTask = new InstallingAsyncTask(); // ? ? ? ? ? ?
mInstallingTask.execute();
} else {
// we will receive a broadcast when the install is finished
mCancelButton.setEnabled(false);
setFinishOnTouchOutside(false);
}
}
}
InstallingAsyncTask
既然启动了 InstallingAsyncTask,那我们就来看看 相关的 doInBackground 和 onPostExecute 方法:
/**
* Send the package to the package installer and then register a event result observer that
* will call {@link #launchFinishBasedOnResult(int, int, String)}
*/
private final class InstallingAsyncTask extends AsyncTask<Void, Void,
PackageInstaller.Session> {
volatile boolean isDone;
// 根据包(APK)的 Uri,将 APK 的信息通过 IO 流的形式写入到 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();
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;
}
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(
getPackageManager().getPermissionControllerPackageName());
broadcastIntent.putExtra(EventResultPersister.EXTRA_ID, mInstallId);
// 创建了一个 PendingIntent
PendingIntent pendingIntent = PendingIntent.getBroadcast(
InstallInstalling.this,
mInstallId,
broadcastIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
/**
* 将该 PendingIntent 的 IntentSender 通过
* PackageInstaller.Session 的 commit 方法发送出去
*/
session.commit(pendingIntent.getIntentSender()); // ? ? ? ? ? ?
mCancelButton.setEnabled(false);
setFinishOnTouchOutside(false);
} else {
getPackageManager().getPackageInstaller().abandonSession(mSessionId);
if (!isCancelled()) {
launchFailure(PackageManager.INSTALL_FAILED_INVALID_APK, null);
}
}
}
}
Ok,问题来了,commit 到哪去了?我们不妨来看一下 PackageInstaller.Session 的 commit 方法:
commit
public void commit(@NonNull IntentSender statusReceiver) {
try {
mSession.commit(statusReceiver, false);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
mSession
public static class Session implements Closeable {
private IPackageInstallerSession mSession;
我们发现,mSession 的类型为 IPackageInstallerSession ,这说明要通过 IPackageInstallerSession 来进行进程间的通信,最终会调用 PackageInstallerSession 的 commit 方法,又回到框架层处理了。
PackageInstallerSession
commit
@Override
public void commit(@NonNull IntentSender statusReceiver, boolean forTransfer) {
Preconditions.checkNotNull(statusReceiver);
final boolean wasSealed;
synchronized (mLock) {
assertCallerIsOwnerOrRootLocked();
assertPreparedAndNotDestroyedLocked("commit");
// 将包的信息封装为 PackageInstallObserverAdapter
final PackageInstallObserverAdapter adapter = new PackageInstallObserverAdapter(
mContext, statusReceiver, sessionId, isInstallerDeviceOwnerLocked(), userId);
mRemoteObserver = adapter.getBinder();
... ...
mHandler.obtainMessage(MSG_COMMIT).sendToTarget(); // ? ? ? ? ? ?
}
... ...
}
Handler.Callback
private final Handler.Callback mHandlerCallback = new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MSG_COMMIT:
synchronized (mLock) {
try {
commitLocked(); // ? ? ? ? ? ?
} catch (PackageManagerException e) {
final String completeMsg = ExceptionUtils.getCompleteMessage(e);
Slog.e(TAG,
"Commit of session " + sessionId + " failed: " + completeMsg);
destroyInternal();
dispatchSessionFinished(e.error, completeMsg, null); // ? ? ? ? ? ?
}
}
break;
case MSG_SESSION_FINISHED_WITH_EXCEPTION:
PackageManagerException e = (PackageManagerException) msg.obj;
dispatchSessionFinished(e.error, ExceptionUtils.getCompleteMessage(e),
null);
break;
}
return true;
}
};
commitLocked
private final PackageManagerService mPm;
private void commitLocked()
throws PackageManagerException {
... ...
/**
* commitLocked 方法很长,我们主要关注这一行代码
* 调用 PackageManagerService 的 installStage 方法
* 这样安装 APK 的代码逻辑就进入了 PackageManagerService 中
*/
mPm.installStage(mPackageName, stageDir, stageCid, localObserver, params,
mInstallerPackageName, mInstallerUid, user, mCertificates);
}
dispatchSessionFinished
我们这边再看一下,如果 commitLocked 出现了异常后的流程处理:
private void dispatchSessionFinished(int returnCode, String msg, Bundle extras) {
final IPackageInstallObserver2 observer;
final String packageName;
... ...
if (observer != null) {
try {
// 调用 IPackageInstallObserver2 的 onPackageInstalled 方法
observer.onPackageInstalled(packageName, returnCode, msg, extras); // ? ? ? ? ? ?
} catch (RemoteException ignored) {
}
}
... ...
mCallback.onSessionFinished(this, success);
}
它的实现方法在 PackageInstallObserver 类中:
public class PackageInstallObserver {
private final IPackageInstallObserver2.Stub mBinder = new IPackageInstallObserver2.Stub() {
@Override
public void onUserActionRequired(Intent intent) {
PackageInstallObserver.this.onUserActionRequired(intent);
}
@Override
public void onPackageInstalled(String basePackageName, int returnCode,
String msg, Bundle extras) {
/**
* 调用了 PackageInstallObserver 的 onPackageInstalled 方法
* 实现这个方法的类为 PackageInstallObserver 的子类:PackageInstallObserverAdapter
*/
PackageInstallObserver.this.onPackageInstalled(basePackageName, returnCode, msg,
extras);
}
};
... ...
}
也就是说:dispatchSessionFinished 方法会通过 Observer 的 onPackageInstalled 方法,将出现的 PackageManagerException 异常信息回调给 PackageInstallObserverAdapter。
总结
本篇文章讲解了 PackageInstaller 安装 APK 的过程,简单来说就两步:
✨ 1. 将 APK 的信息通过 IO流 的形式写入到 PackageInstaller.Session中。
✨ 2. 调用 PackageInstaller.Session 的 commit 方法,将 APK 的信息交由 PMS 处理。