編輯:關於 Android 程式設計
前幾篇我們把 AMS 啟動 Activity 的主幹流程大致理清了。這一篇專門看一個關鍵細節:AMS 是怎麼透過 PKMS(PackageManagerService)拿到 ActivityInfo 的,以及這個物件裡的 processName 與 uid 究竟從哪裡來。
回顧 startActivity 的路徑:AMS 的 startActivity() 之後進入 startActivityMayWait(),在這個函式裡呼叫 resolveActivity() 解析 ActivityInfo;再往後會走到 startActivityLocked(),並在其中建立 ActivityRecord。
ActivityRecord 的 processName 與 info.applicationInfo.uid 這兩個值,在後續「是否已有對應進程」的判斷中起著決定性作用(前面已分析過)。而它們分別來源於 ActivityInfo 的 processName 與其中的 ApplicationInfo。
final int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage,
Intent intent, String resolvedType, IVoiceInteractionSession voiceSession,
IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, WaitResult outResult, Configuration config,
Bundle options, boolean ignoreTargetSecurity, int userId,
IActivityContainer iContainer, TaskRecord inTask) {
// 拒絕可能洩漏的檔案描述符
if (intent != null && intent.hasFileDescriptors()) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
boolean componentSpecified = intent.getComponent() != null;
// 不要修改呼叫端的物件
intent = new Intent(intent);
// 收集目標 Intent 的相關資訊
ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId);
............
接著看 resolveActivity(),它最終是透過 PKMS 的 resolveIntent() 取得 ResolveInfo,而 ActivityInfo 是其中的一個成員:
ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
ProfilerInfo profilerInfo, int userId) {
// 收集目標 Intent 的相關資訊
ActivityInfo aInfo;
try {
ResolveInfo rInfo = AppGlobals.getPackageManager().resolveIntent(
intent, resolvedType,
PackageManager.MATCH_DEFAULT_ONLY | ActivityManagerService.STOCK_PM_FLAGS,
userId);
aInfo = rInfo != null ? rInfo.activityInfo : null;
} catch (RemoteException e) {
aInfo = null;
}
if (aInfo != null) {
// 把找到的目標寫回 intent,之後就不必再解析一次
// 例如使用者從歷史記錄回到這一頁時,應永遠啟動同一個 Activity
intent.setComponent(new ComponentName(
aInfo.applicationInfo.packageName, aInfo.name));
// 不要對 system 進程做除錯設定
if ((startFlags & ActivityManager.START_FLAG_DEBUG) != 0) {
if (!aInfo.processName.equals("system")) {
mService.setDebugApp(aInfo.processName, true, false);
}
}
if ((startFlags & ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
if (!aInfo.processName.equals("system")) {
mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
}
}
if (profilerInfo != null) {
if (!aInfo.processName.equals("system")) {
mService.setProfileApp(aInfo.applicationInfo, aInfo.processName, profilerInfo);
}
}
}
return aInfo;
}
把解析結果寫回 Intent 的 Component 是一個值得注意的設計:一旦解析過,後續(包括使用者回退再進入)都不必重複查找。
PKMS 的 resolveIntent() 先驗證使用者與跨使用者權限,接著呼叫 queryIntentActivities() 取得候選集合,最後交給 chooseBestActivity() 挑出最合適的一項。
@Override
public ResolveInfo resolveIntent(Intent intent, String resolvedType, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
return chooseBestActivity(intent, resolvedType, flags, query, userId);
}
重點在 queryIntentActivities()。它會依 Intent 攜帶資訊的多寡,走三條不同成本的路徑:
public List<ResolveInfo> queryIntentActivities(Intent intent, String resolvedType,
int flags, int userId) {
if (!sUserManager.exists(userId)) return Collections.emptyList();
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
"query intent activities");
ComponentName comp = intent.getComponent();
if (comp == null) {
if (intent.getSelector() != null) {
intent = intent.getSelector();
comp = intent.getComponent();
}
}
if (comp != null) {
// Intent 指定了元件,只會有一個匹配項
final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
final ActivityInfo ai = getActivityInfo(comp, flags, userId);
if (ai != null) {
final ResolveInfo ri = new ResolveInfo();
ri.activityInfo = ai;
list.add(ri);
}
return list;
}
// 讀者鎖
synchronized (mPackages) {
final String pkgName = intent.getPackage();
if (pkgName == null) {
// Intent 未指定套件名,需在系統所有套件中查找
List<CrossProfileIntentFilter> matchingFilters =
getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
// 先檢查需要跳過目前 profile 的結果
ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(
matchingFilters, intent, resolvedType, flags, userId);
if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
result.add(xpResolveInfo);
return filterIfNotPrimaryUser(result, userId);
}
// 再檢查目前 profile 中的結果
List<ResolveInfo> result = mActivities.queryIntent(
intent, resolvedType, flags, userId);
// 檢查跨 profile 的結果
xpResolveInfo = queryCrossProfileIntents(
matchingFilters, intent, resolvedType, flags, userId);
if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) {
result.add(xpResolveInfo);
Collections.sort(result, mResolvePrioritySorter);
}
result = filterIfNotPrimaryUser(result, userId);
if (hasWebURI(intent)) {
CrossProfileDomainInfo xpDomainInfo = null;
final UserInfo parent = getProfileParent(userId);
if (parent != null) {
xpDomainInfo = getCrossProfileDomainPreferredLpr(
intent, resolvedType, flags, userId, parent.id);
}
if (xpDomainInfo != null) {
if (xpResolveInfo != null) {
// 若尚未移除,跨 profile 的 ResolveInfo 會重複出現兩次
result.remove(xpResolveInfo);
}
if (result.size() == 0) {
result.add(xpDomainInfo.resolveInfo);
return result;
}
} else if (result.size() <= 1) {
return result;
}
result = filterCandidatesWithDomainPreferredActivitiesLPr(
intent, flags, result, xpDomainInfo, userId);
Collections.sort(result, mResolvePrioritySorter);
}
return result;
}
final PackageParser.Package pkg = mPackages.get(pkgName);
if (pkg != null) {
// Intent 帶有套件名,就在指定套件中查找
return filterIfNotPrimaryUser(
mActivities.queryIntentForPackage(
intent, resolvedType, flags, pkg.activities, userId),
userId);
}
return new ArrayList<ResolveInfo>();
}
}
三條路徑的成本差異明顯:有 Component 最快(直接查表),只有套件名次之(在該套件的 activities 中比對),兩者皆無最慢(要掃過系統所有已安裝套件)。這也解釋了為什麼显式指定 Component 的啟動方式效能最好。
我們聚焦最直接的那條路——getActivityInfo():從 mActivities.mActivities 依 ComponentName 取出 Activity,再由 PackageParser.generateActivityInfo() 生成 ActivityInfo。
public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
if (!sUserManager.exists(userId)) return null;
enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
"get activity info"); // 檢查權限
synchronized (mPackages) {
PackageParser.Activity a = mActivities.mActivities.get(component);
if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
if (ps == null) return null;
return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), userId);
}
if (mResolveComponentName.equals(component)) {
return PackageParser.generateActivityInfo(
mResolveActivity, flags, new PackageUserState(), userId);
}
}
return null;
}
generateActivityInfo() 做的事其實很樸素:以 Activity 內部的 info 為基礎複製一份新的 ActivityInfo,再補上 ApplicationInfo 等欄位。
public static final ActivityInfo generateActivityInfo(Activity a, int flags,
PackageUserState state, int userId) {
if (a == null) return null;
if (!checkUseInstalledOrHidden(flags, state)) {
return null;
}
if (!copyNeeded(flags, a.owner, state, a.metaData, userId)) {
return a.info;
}
// 做淺複製,以便安全地保存 metadata
ActivityInfo ai = new ActivityInfo(a.info);
ai.metaData = a.metaData;
ai.applicationInfo = generateApplicationInfo(a.owner, flags, state, userId);
return ai;
}
這裡最關鍵的就是 mActivities 這個成員——它是一個 ActivityIntentResolver:
final ActivityIntentResolver mActivities = new ActivityIntentResolver();
而 ActivityIntentResolver 內部又維護了一份以 ComponentName 為鍵的映射:
// Keys are String (activity class name), values are Activity.
private final ArrayMap<ComponentName, PackageParser.Activity> mActivities =
new ArrayMap<>();
之前分析 PKMS 時已經確認:無論是開機時掃描各目錄下的 APK,還是安裝新 APK,最終都會彙集到 scanPackageDirtyLI()。
開機掃描路徑:scanDirLI() → scanPackageLI(File, ...)(建立 PackageParser 解析檔案)→ scanPackageLI(Package, ...) → scanPackageDirtyLI()。
安裝路徑:先把 APK 複製到目標目錄 → installPackageLI()(同樣建立 PackageParser 解析)→ installNewPackageLI()(結束前發送廣播通知 Launcher 等應用更新圖標)→ scanPackageLI(Package, ...) → scanPackageDirtyLI()。
換言之,兩條路的分岔只在「APK 從哪來」,彙集點是同一個。
在 scanPackageDirtyLI() 裡,系統遍歷 PackageParser.Package 的所有 Activity,依規則確定各自的 processName,然後放入 mActivities:
final int N = pkg.activities.size();
r = null;
for (int i = 0; i < N; i++) {
PackageParser.Activity a = pkg.activities.get(i);
a.info.processName = fixProcessName(pkg.applicationInfo.processName,
a.info.processName, a.info.applicationInfo.uid);
mActivities.addActivity(a, "activity");
............
}
fixProcessName() 的規則很簡單:Activity 自己宣告了就用自己那個,沒宣告才回退到應用的預設值。
private static String fixProcessName(String defProcessName, String processName, int uid) {
if (processName == null) {
return defProcessName;
}
return processName;
}
而 ActivityIntentResolver 的 addActivity() 主要就是把它塞進 mActivities(鍵為 ComponentName),同時把它的各個 IntentFilter 註冊進解析器:
public final void addActivity(PackageParser.Activity a, String type) {
final boolean systemApp = a.info.applicationInfo.isSystemApp();
mActivities.put(a.getComponentName(), a);
final int NI = a.intents.size();
for (int j = 0; j < NI; j++) {
PackageParser.ActivityIntentInfo intent = a.intents.get(j);
if (systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
intent.setPriority(0);
Log.w(TAG, "Package " + a.info.applicationInfo.packageName
+ " has activity " + a.className + " with priority > 0, forcing to 0");
}
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " IntentFilter:");
intent.dump(new LogPrinter(Log.VERBOSE, TAG), " ");
}
if (!intent.debugCheck()) {
Log.w(TAG, "==> For Activity " + a.info.name);
}
addFilter(intent);
}
}
順帶一提,系統應用宣告高優先級 IntentFilter 的企圖會被強制歸零——這是為了避免平台應用壟斷隱式 Intent 的解析結果。
無論開機掃描還是安裝,PackageParser.Package 都是新建 PackageParser 解析檔案得到的。開機掃描在 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();
pp.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);
} catch (PackageParserException e) {
throw PackageManagerException.from(e);
}
......
安裝則在 installPackageLI() 中呼叫:
private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
final int installFlags = args.installFlags;
final String installerPackageName = args.installerPackageName;
final String volumeUuid = args.volumeUuid;
final File tmpPackageFile = new File(args.getCodePath());
final boolean forwardLocked =
((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
|| (args.volumeUuid != null));
boolean replace = false;
int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE;
if (args.move != null) {
// 搬移完整應用時,先對新的安裝位置做一次初始掃描
scanFlags |= SCAN_INITIAL;
}
res.returnCode = PackageManager.INSTALL_SUCCEEDED;
// 取得 PackageSettings 並解析套件
final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
| (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
| (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
PackageParser pp = new PackageParser();
pp.setSeparateProcesses(mSeparateProcesses);
pp.setDisplayMetrics(mMetrics);
final PackageParser.Package pkg;
try {
pkg = pp.parsePackage(tmpPackageFile, parseFlags);
} catch (PackageParserException e) {
res.setError("Failed parse during installPackageLI", e);
return;
}
......
parsePackage() 會依「是否為目錄」分流:
public Package parsePackage(File packageFile, int flags) throws PackageParserException {
if (packageFile.isDirectory()) {
return parseClusterPackage(packageFile, flags);
} else {
return parseMonolithicPackage(packageFile, flags);
}
}
目錄形態(含 split APK)走 parseClusterPackage():先解析 base APK,再逐一解析各個 split。
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 {
// 把 base 與所有 split 載入 AssetManager,
// 以便解析 manifest 時資源能被正確覆寫
loadApkIntoAssetManager(assets, lite.baseCodePath, flags);
if (!ArrayUtils.isEmpty(lite.splitCodePaths)) {
for (String path : lite.splitCodePaths) {
loadApkIntoAssetManager(assets, path, flags);
}
}
final File baseApk = new File(lite.baseCodePath);
final Package pkg = parseBaseApk(baseApk, assets, flags);
if (pkg == null) {
throw new PackageParserException(INSTALL_PARSE_FAILED_NOT_APK,
"Failed to parse base APK: " + baseApk);
}
if (!ArrayUtils.isEmpty(lite.splitNames)) {
final int num = lite.splitNames.length;
pkg.splitNames = lite.splitNames;
pkg.splitCodePaths = lite.splitCodePaths;
pkg.splitRevisionCodes = lite.splitRevisionCodes;
pkg.splitFlags = new int[num];
pkg.splitPrivateFlags = new int[num];
for (int i = 0; i < num; i++) {
parseSplitApk(pkg, i, assets, flags);
}
}
pkg.codePath = packageDir.getAbsolutePath();
return pkg;
} finally {
IoUtils.closeQuietly(assets);
}
}
單檔形態則直接解析 base APK:
public Package parseMonolithicPackage(File apkFile, int flags) throws PackageParserException {
if (mOnlyCoreApps) {
final PackageLite lite = parseMonolithicPackageLite(apkFile, flags);
if (!lite.coreApp) {
throw new PackageParserException(INSTALL_PARSE_FAILED_MANIFEST_MALFORMED,
"Not a coreApp: " + apkFile);
}
}
final AssetManager assets = new AssetManager();
try {
final Package pkg = parseBaseApk(apkFile, assets, flags);
pkg.codePath = apkFile.getAbsolutePath();
return pkg;
} finally {
IoUtils.closeQuietly(assets);
}
}
再往下的 parseBaseApk() 建立 Package 物件,並遍歷 manifest 的 XML 節點;我們只關心 application,它交給 parseBaseApplication() 處理:
private Package parseBaseApk(Resources res, XmlResourceParser parser, int flags,
String[] outError) throws XmlPullParserException, IOException {
...... final Package pkg = new Package(pkgName);
boolean foundApp = false;
TypedArray sa = res.obtainAttributes(attrs, com.android.internal.R.styleable.AndroidManifest);
pkg.mVersionCode = pkg.applicationInfo.versionCode = sa.getInteger(
com.android.internal.R.styleable.AndroidManifest_versionCode, 0);
pkg.baseRevisionCode = sa.getInteger(
com.android.internal.R.styleable.AndroidManifest_revisionCode, 0);
pkg.mVersionName = sa.getNonConfigurationString(
com.android.internal.R.styleable.AndroidManifest_versionName, 0);
if (pkg.mVersionName != null) {
pkg.mVersionName = pkg.mVersionName.intern();
}
...... int outerDepth = parser.getDepth();
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
continue;
}
String tagName = parser.getName();
if (tagName.equals("application")) {
if (foundApp) {
if (RIGID_PARSER) {
outError[0] = "<manifest> has more than one <application>";
mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
return null;
} else {
Slog.w(TAG, "<manifest> has more than one <application>");
XmlUtils.skipCurrentTag(parser);
continue;
}
}
foundApp = true;
if (!parseBaseApplication(pkg, res, parser, attrs, flags, outError)) {
return null;
}
}
......
parseBaseApplication() 先取得 ApplicationInfo 並處理 processName,然後遍歷 application 下的各節點。我們關注的是 Activity:
private boolean parseBaseApplication(Package owner, Resources res, XmlPullParser parser,
AttributeSet attrs, int flags, String[] outError)
throws XmlPullParserException, IOException {
final ApplicationInfo ai = owner.applicationInfo;
final String pkgName = owner.applicationInfo.packageName;
...... ai.processName = buildProcessName(ai.packageName, null, pname, flags,
mSeparateProcesses, outError);
...... while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& (type != XmlPullParser.END_TAG || parser.getDepth() > innerDepth)) {
if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
continue;
}
String tagName = parser.getName();
if (tagName.equals("activity")) {
Activity a = parseActivity(owner, res, parser, attrs, flags, outError, false,
owner.baseHardwareAccelerated);
if (a == null) {
mParseError = PackageManager.INSTALL_PARSE_FAILED_MANIFEST_MALFORMED;
return false;
}
owner.activities.add(a);
}
......
而 parseActivity() 只建立 Activity 物件並解析各項屬性到 info 等變量中——仔細看會發現,這裡既沒有 Activity 的 info.processName,也沒有 ComponentName。它們其實是在父類建構過程中生成的:
private Activity parseActivity(Package owner, Resources res, XmlPullParser parser,
AttributeSet attrs, int flags, String[] outError, boolean receiver,
boolean hardwareAccelerated) throws XmlPullParserException, IOException {
TypedArray sa = res.obtainAttributes(attrs, R.styleable.AndroidManifestActivity);
if (mParseActivityArgs == null) {
mParseActivityArgs = new ParseComponentArgs(owner, outError,
R.styleable.AndroidManifestActivity_name,
R.styleable.AndroidManifestActivity_label,
R.styleable.AndroidManifestActivity_icon,
R.styleable.AndroidManifestActivity_logo,
R.styleable.AndroidManifestActivity_banner,
mSeparateProcesses,
R.styleable.AndroidManifestActivity_process,
R.styleable.AndroidManifestActivity_description,
R.styleable.AndroidManifestActivity_enabled);
}
mParseActivityArgs.tag = receiver ? "<receiver>" : "<activity>";
mParseActivityArgs.sa = sa;
mParseActivityArgs.flags = flags;
Activity a = new Activity(mParseActivityArgs, new ActivityInfo());
......
Activity 的建構子(父類是 Component):
public Activity(final ParseComponentArgs args, final ActivityInfo _info) {
super(args, _info);
info = _info;
info.applicationInfo = args.owner.applicationInfo;
}
父類 Component 的建構子裡,正是 processName 被設定的地方:
public Component(final ParseComponentArgs args, final ComponentInfo outInfo) {
this(args, (PackageItemInfo) outInfo);
if (args.outError[0] != null) {
return;
}
if (args.processRes != 0) {
CharSequence pname;
if (owner.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.FROYO) {
pname = args.sa.getNonConfigurationString(
args.processRes, Configuration.NATIVE_CONFIG_VERSION);
} else {
// 部分舊應用會在這裡使用資源引用,舊版本上僅給警告後忽略;
// 為避免它們失效,這裡維持相同行為
pname = args.sa.getNonResourceString(args.processRes);
}
outInfo.processName = buildProcessName(owner.applicationInfo.packageName,
owner.applicationInfo.processName, pname, args.flags,
args.sepProcesses, args.outError);
}
if (args.descriptionRes != 0) {
outInfo.descriptionRes = args.sa.getResourceId(args.descriptionRes, 0);
}
outInfo.enabled = args.sa.getBoolean(args.enabledRes, true);
}
這裡就解答了第一個疑問:info.processName 在解析 Activity 節點時,由 Component 建構子依 android:process 屬性算出。注意它有一個 targetSdkVersion 的分支——Froyo 之前的部分應用會誤用資源引用,為了相容仍走 getNonResourceString()。
而 ComponentName 則來自下一層建構子,它同時決定了 className:
public Component(final ParsePackageItemArgs args, final PackageItemInfo outInfo) {
owner = args.owner;
intents = new ArrayList<ComponentIntentInfo>(0);
String name = args.sa.getNonConfigurationString(args.nameRes, 0);
if (name == null) {
className = null;
args.outError[0] = args.tag + " does not specify android:name";
return;
}
outInfo.name = buildClassName(owner.applicationInfo.packageName, name, args.outError);
if (outInfo.name == null) {
className = null;
args.outError[0] = args.tag + " does not have valid android:name";
return;
}
className = outInfo.name;
......
取得 ComponentName 時,只要有 className 就會建立:
public ComponentName getComponentName() {
if (componentName != null) {
return componentName;
}
if (className != null) {
componentName = new ComponentName(owner.applicationInfo.packageName, className);
}
return componentName;
}
ComponentName 的建構子只是保存兩個變量並做非空校驗:
public ComponentName(String pkg, String cls) {
if (pkg == null) throw new NullPointerException("package name is null");
if (cls == null) throw new NullPointerException("class name is null");
mPackage = pkg;
mClass = cls;
}
至此,ComponentName 與 processName 的來源都清楚了:前者由「套件名 + android:name」組裝,後者由 android:process 經 buildProcessName 推導,未宣告時回退到應用的 processName。
ActivityInfo 裡另一個關鍵資訊是 uid(位於 ApplicationInfo 中)。賦值發生在 scanPackageDirtyLI():
pkg.applicationInfo.uid = pkgSetting.appId;
而 Activity 的建構子中 info.applicationInfo 就是 Package 的 applicationInfo,因此這一行的效果等於替 ActivityInfo 的 applicationInfo.uid 賦值。
接著追 pkgSetting.appId。同一個函式裡透過下列程式碼建立 pkgSetting:
pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi,
pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, false);
這個多參數版本最終轉調字串參數版本:
PackageSetting getPackageLPw(PackageParser.Package pkg, PackageSetting origPackage,
String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
String legacyNativeLibraryPathString, String primaryCpuAbi, String secondaryCpuAbi,
int pkgFlags, int pkgPrivateFlags, UserHandle user, boolean add) {
final String name = pkg.packageName;
PackageSetting p = getPackageLPw(name, origPackage, realName, sharedUser, codePath,
resourcePath, legacyNativeLibraryPathString, primaryCpuAbi, secondaryCpuAbi,
pkg.mVersionCode, pkgFlags, pkgPrivateFlags, user, add, true /* allowInstall */);
return p;
}
首次安裝時,mPackages 中沒有對應 PackageSetting,也沒有 origPackage 與 sharedUser,於是走 newUserIdLPw() 配置新 uid 的分支:
private PackageSetting getPackageLPw(String name, PackageSetting origPackage,
String realName, SharedUserSetting sharedUser, File codePath, File resourcePath,
String legacyNativeLibraryPathString, String primaryCpuAbiString,
String secondaryCpuAbiString, int vc, int pkgFlags, int pkgPrivateFlags,
UserHandle installUser, boolean add, boolean allowInstall) {
PackageSetting p = mPackages.get(name);
UserManagerService userManager = UserManagerService.getInstance();
if (p != null) {
...... } else {
if (origPackage != null) {
...... } else {
p = new PackageSetting(name, realName, codePath, resourcePath,
legacyNativeLibraryPathString, primaryCpuAbiString,
secondaryCpuAbiString, null /* cpuAbiOverrideString */,
vc, pkgFlags, pkgPrivateFlags);
p.setTimeStamp(codePath.lastModified());
p.sharedUser = sharedUser;
// 非系統應用預設為 stopped 狀態
if ((pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
...... // 逐使用者設定 installed / stopped 等狀態
}
if (sharedUser != null) {
// 有 sharedUser 時共用同一個 uid
p.appId = sharedUser.userId;
} else {
// 為「被停用的系統套件」複製設定
PackageSetting dis = mDisabledSysPackages.get(name);
if (dis != null) {
if (dis.signatures.mSignatures != null) {
p.signatures.mSignatures = dis.signatures.mSignatures.clone();
}
p.appId = dis.appId;
p.getPermissionsState().copyFrom(dis.getPermissionsState());
...... // 複製元件啟停狀態
addUserIdLPw(p.appId, p, name);
} else {
// 配置新的 uid
p.appId = newUserIdLPw(p);
}
}
}
}
if (p.appId < 0) {
PackageManagerService.reportSettingsProblem(Log.WARN,
"Package " + name + " could not be assigned a valid uid");
return null;
}
if (add) {
addPackageSettingLPw(p, name, sharedUser);
}
...... return p;
}
newUserIdLPw() 的策略是「先撿空位,再遞增」:遍歷現有 uid 表,遇到空位就重用;若無空位且未超過上限,則取目前最大值 +1。
private int newUserIdLPw(Object obj) {
// 先看看有沒有被釋放的位置可以重用
final int N = mUserIds.size();
for (int i = mFirstAvailableUid; i < N; i++) {
if (mUserIds.get(i) == null) {
mUserIds.set(i, obj);
return Process.FIRST_APPLICATION_UID + i;
}
}
// 沒有空位了
if (N > (Process.LAST_APPLICATION_UID - Process.FIRST_APPLICATION_UID)) {
return -1;
}
mUserIds.add(obj);
return Process.FIRST_APPLICATION_UID + N;
}
uid 重用的機制也解釋了為什麼卸載再安裝後 uid 常常會變小——它填回了空位。
scanPackageDirtyLI() 的尾段會把結果落地保存:PackageSetting 進 mSettings,Package 進 mPackages。
synchronized (mPackages) {
// 越過這一點之後不預期安裝會失敗
// 把新的 setting 加入 mSettings
mSettings.insertPackageSettingLPw(pkgSetting, pkg);
// 把新的 package 加入 mPackages
mPackages.put(pkg.applicationInfo.packageName, pkg);
......
mPackages 只是直接 put,不必多說。mSettings 則透過 insertPackageSettingLPw() 先把 pkg 掛到 PackageSetting 上,同步 volume、codePath、resourcePath、CPU ABI、版本號、簽名與 flags 等欄位,最後交給 addPackageSettingLPw() 保存。
void insertPackageSettingLPw(PackageSetting p, PackageParser.Package pkg) {
p.pkg = pkg;
final String volumeUuid = pkg.applicationInfo.volumeUuid;
final String codePath = pkg.applicationInfo.getCodePath();
final String resourcePath = pkg.applicationInfo.getResourcePath();
final String legacyNativeLibraryPath = pkg.applicationInfo.nativeLibraryRootDir;
// 視需要更新 volume
if (!Objects.equals(volumeUuid, p.volumeUuid)) {
Slog.w(PackageManagerService.TAG, "Volume for " + p.pkg.packageName
+ " changing from " + p.volumeUuid + " to " + volumeUuid);
p.volumeUuid = volumeUuid;
}
// 視需要更新 code path
if (!Objects.equals(codePath, p.codePathString)) {
p.codePath = new File(codePath);
p.codePathString = codePath;
}
// 視需要更新 resource path
if (!Objects.equals(resourcePath, p.resourcePathString)) {
p.resourcePath = new File(resourcePath);
p.resourcePathString = resourcePath;
}
// 更新 so 庫路徑
if (!Objects.equals(legacyNativeLibraryPath, p.legacyNativeLibraryPathString)) {
p.legacyNativeLibraryPathString = legacyNativeLibraryPath;
}
p.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
p.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
p.cpuAbiOverrideString = pkg.cpuAbiOverride;
// 視需要更新 versionCode
if (pkg.mVersionCode != p.versionCode) {
p.versionCode = pkg.mVersionCode;
}
// 視需要更新簽名
if (p.signatures.mSignatures == null) {
p.signatures.assignSignatures(pkg.mSignatures);
}
// 視需要更新 flags
if (pkg.applicationInfo.flags != p.pkgFlags) {
p.pkgFlags = pkg.applicationInfo.flags;
}
// 若定義了 shared user id,同步初始化其簽名
if (p.sharedUser != null && p.sharedUser.signatures.mSignatures == null) {
p.sharedUser.signatures.assignSignatures(pkg.mSignatures);
}
addPackageSettingLPw(p, pkg.packageName, p.sharedUser);
}
private void addPackageSettingLPw(PackageSetting p, String name, SharedUserSetting sharedUser) {
mPackages.put(name, p);
......
每次開機都會重新掃描各目錄下的 APK,重建 mSettings 中的資料,最後再把 mSettings 寫入 packages.xml,以便下次開機快速還原。
AMS 透過 Intent 向 PKMS 換取 ActivityInfo,而其中的 processName 與 uid 會在後續啟動進程時被反覆使用。PKMS 的查詢效率與 Intent 攜帶的資訊量直接相關:
· 帶 ComponentName → 直接查表,最快;
· 只帶套件名 → 在該套件內比對 IntentFilter;
· 兩者皆無 → 全域掃描,最慢。
而這一切能成立,靠的是開機掃描與安裝流程共同彙集到 scanPackageDirtyLI(),由它把 PackageParser 解析出的 Activity 註冊進 ActivityIntentResolver,並在 PackageSetting 中配置 uid。
後續可以沿著這條線去看「安裝兩個應用(例如微信)」的完整過程;不過 uid 的分配與 processName 的推導,建議還是多打 log 實測驗證一次,比對源碼更直觀。
UI 碎片化控件详解:Fragment 基本概念与用法入门
(一)概述 前面我們把 Android 四大組件——Activity、Service、BroadcastReceiver、ContentProvider,以及它們之間的紐
PullToRefresh 下拉刷新控件實戰:從導入到自訂樣式
PullToRefresh 是什麼?在 Android 開發中,下拉刷新幾乎是列表頁面的標配。系統雖然提供了 SwipeRefreshLayout,但如果需要更豐富的上下
Android Drawable 九種常見子類:從 XML 到視覺效果
Drawable 的概念 在 Android 中,Drawable 代表可繪製的圖像資源。它不只是圖片,也可以是顏色、形狀、漸層、狀態清單或多層組合。善用 Drawabl
NavigationView + DrawerLayout 實現側拉抽屜效果
先上效果圖: NavigationView 是 android-support-design 包下的控件,使用前需引入 design 依賴: dependencies