下面列出了android.content.pm.PackageParser#Package() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates oat dir for the specified package if needed and supported.
* In certain cases oat directory
* <strong>cannot</strong> be created:
* <ul>
* <li>{@code pkg} is a system app, which is not updated.</li>
* <li>Package location is not a directory, i.e. monolithic install.</li>
* </ul>
*
* @return Absolute path to the oat directory or null, if oat directory
* cannot be created.
*/
@Nullable
private String createOatDirIfSupported(PackageParser.Package pkg, String dexInstructionSet) {
if (!pkg.canHaveOatDir()) {
return null;
}
File codePath = new File(pkg.codePath);
if (codePath.isDirectory()) {
// TODO(calin): why do we create this only if the codePath is a directory? (i.e for
// cluster packages). It seems that the logic for the folder creation is
// split between installd and here.
File oatDir = getOatDir(codePath);
try {
mInstaller.createOatDir(oatDir.getAbsolutePath(), dexInstructionSet);
} catch (InstallerException e) {
Slog.w(TAG, "Failed to create oat dir", e);
return null;
}
return oatDir.getAbsolutePath();
}
return null;
}
@Override
public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
synchronized (mPackages) {
PackageParser.Package pkg = mPackages.get(packageName);
if (pkg != null) {
AppSetting setting = (AppSetting) pkg.mExtras;
if ((flags & PackageManager.GET_SIGNATURES) != 0 && pkg.mSignatures == null) {
if (pkg.mAppMetaData != null && pkg.mAppMetaData.containsKey(Constants.FEATURE_FAKE_SIGNATURE)) {
String sig = pkg.mAppMetaData.getString("fake-signature");
if (sig != null) {
pkg.mSignatures = new Signature[] {new Signature(sig)};
}
} else {
PackageParserCompat.collectCertificates(setting.parser, pkg, PackageParser.PARSE_IS_SYSTEM);
}
}
PackageInfo packageInfo = PackageParserCompat.generatePackageInfo(pkg, flags,
getFirstInstallTime(pkg), getLastInstallTime(pkg));
if (packageInfo != null) {
ComponentFixer.fixApplicationInfo(setting, packageInfo.applicationInfo, userId);
return packageInfo;
}
}
}
return null;
}
@GuardedBy("mLock")
private void addServicesLocked(PackageParser.Package pkg, boolean chatty) {
final int servicesSize = pkg.services.size();
StringBuilder r = null;
for (int i = 0; i < servicesSize; i++) {
PackageParser.Service s = pkg.services.get(i);
s.info.processName = fixProcessName(pkg.applicationInfo.processName,
s.info.processName);
mServices.addService(s);
if (DEBUG_PACKAGE_SCANNING && chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(s.info.name);
}
}
if (DEBUG_PACKAGE_SCANNING && chatty) {
Log.d(TAG, " Services: " + (r == null ? "<NONE>" : r));
}
}
private void grantPermissionsToSysComponentsAndPrivApps(int userId) {
Log.i(TAG, "Granting permissions to platform components for user " + userId);
final PackageList packageList = mServiceInternal.getPackageList();
for (String packageName : packageList.getPackageNames()) {
final PackageParser.Package pkg = mServiceInternal.getPackage(packageName);
if (pkg == null) {
continue;
}
if (!isSysComponentOrPersistentPlatformSignedPrivApp(pkg)
|| !doesPackageSupportRuntimePermissions(pkg)
|| pkg.requestedPermissions.isEmpty()) {
continue;
}
grantRuntimePermissionsForPackage(userId, pkg);
}
}
@Override
public List<String> querySharedPackages(String packageName) {
synchronized (mPackages) {
PackageParser.Package p = mPackages.get(packageName);
if (p == null || p.mSharedUserId == null) {
// noinspection unchecked
return Collections.EMPTY_LIST;
}
ArrayList<String> list = new ArrayList<>();
for (PackageParser.Package one : mPackages.values()) {
if (TextUtils.equals(one.mSharedUserId, p.mSharedUserId)) {
list.add(one.packageName);
}
}
return list;
}
}
public void onPackageUninstalledLPw(@NonNull PackageParser.Package pkg,
@NonNull int[] userIds) {
PackageSetting ps = (PackageSetting) pkg.mExtras;
if (ps == null) {
return;
}
for (int userId : userIds) {
if (mService.mPackages.get(pkg.packageName) != null && ps.getInstalled(userId)) {
continue;
}
if (ps.getInstantApp(userId)) {
// Add a record for an uninstalled instant app
addUninstalledInstantAppLPw(pkg, userId);
removeInstantAppLPw(userId, ps.appId);
} else {
// Deleting an app prunes all instant state such as cookie
deleteDir(getInstantApplicationDir(pkg.packageName, userId));
mCookiePersistence.cancelPendingPersistLPw(pkg, userId);
removeAppLPw(userId, ps.appId);
}
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public List<ResolveInfo> queryIntentContentProviders(Intent intent, String resolvedType, int flags, int userId) {
checkUserId(userId);
ComponentName comp = intent.getComponent();
if (comp == null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
if (intent.getSelector() != null) {
intent = intent.getSelector();
comp = intent.getComponent();
}
}
}
if (comp != null) {
final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
final ProviderInfo pi = getProviderInfo(comp, flags, userId);
if (pi != null) {
final ResolveInfo ri = new ResolveInfo();
ri.providerInfo = pi;
list.add(ri);
}
return list;
}
// reader
synchronized (mPackages) {
String pkgName = intent.getPackage();
if (pkgName == null) {
return mProviders.queryIntent(intent, resolvedType, flags);
}
final PackageParser.Package pkg = mPackages.get(pkgName);
if (pkg != null) {
return mProviders.queryIntentForPackage(intent, resolvedType, flags, pkg.providers);
}
return null;
}
}
/**
* generateActivityInfo
*
* @param p PackageParser.Package
* @param pi PackageInfo
* @param flags flags
*/
private void generateActivityInfo(PackageParser.Package p, PackageInfo pi, int flags) {
PackageUserState state = new PackageUserState();
if ((flags & PackageManager.GET_ACTIVITIES) != 0) {
int N = p.activities.size();
if (N > 0) {
if ((flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
pi.activities = new ActivityInfo[N];
} else {
int num = 0;
for (int i = 0; i < N; i++) {
if (p.activities.get(i).info.enabled) num++;
}
pi.activities = new ActivityInfo[num];
}
for (int i = 0, j = 0; i < N; i++) {
final Activity activity = p.activities.get(i);
if (activity.info.enabled
|| (flags & PackageManager.GET_DISABLED_COMPONENTS) != 0) {
pi.activities[j++] = PackageParser.generateActivityInfo(activity, flags, state, 0);
// try {
// pi.activities[j++] = JavaCalls.callStaticMethodOrThrow(PackageParser.class, "generateActivityInfo",
// activity, flags, state, 0);
// } catch (Exception e) {
// e.printStackTrace();
// }
}
}
}
}
}
public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
Log.i(TAG, "Granting permissions to default Use Open WiFi app for user:" + userId);
if (packageName == null) {
return;
}
PackageParser.Package useOpenWifiPackage = getPackage(packageName);
if (useOpenWifiPackage != null
&& doesPackageSupportRuntimePermissions(useOpenWifiPackage)) {
grantRuntimePermissions(
useOpenWifiPackage, COARSE_LOCATION_PERMISSIONS, false, true, userId);
}
}
public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) {
Log.i(TAG, "Granting permissions to enabled carrier apps for user:" + userId);
if (packageNames == null) {
return;
}
for (String packageName : packageNames) {
PackageParser.Package carrierPackage = getSystemPackage(packageName);
if (carrierPackage != null
&& doesPackageSupportRuntimePermissions(carrierPackage)) {
grantRuntimePermissions(carrierPackage, PHONE_PERMISSIONS, userId);
grantRuntimePermissions(carrierPackage, LOCATION_PERMISSIONS, userId);
grantRuntimePermissions(carrierPackage, SMS_PERMISSIONS, userId);
}
}
}
@GuardedBy("mLock")
private void grantRuntimePermissionsGrantedToDisabledPackageLocked(
PackageParser.Package pkg, int callingUid, PermissionCallback callback) {
if (pkg.parentPackage == null) {
return;
}
if (pkg.requestedPermissions == null) {
return;
}
final PackageParser.Package disabledPkg =
mPackageManagerInt.getDisabledPackage(pkg.parentPackage.packageName);
if (disabledPkg == null || disabledPkg.mExtras == null) {
return;
}
final PackageSetting disabledPs = (PackageSetting) disabledPkg.mExtras;
if (!disabledPs.isPrivileged() || disabledPs.hasChildPackages()) {
return;
}
final int permCount = pkg.requestedPermissions.size();
for (int i = 0; i < permCount; i++) {
String permission = pkg.requestedPermissions.get(i);
BasePermission bp = mSettings.getPermissionLocked(permission);
if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) {
continue;
}
for (int userId : mUserManagerInt.getUserIds()) {
if (disabledPs.getPermissionsState().hasRuntimePermission(permission, userId)) {
grantRuntimePermission(
permission, pkg.packageName, false, callingUid, userId, callback);
}
}
}
}
@Override
public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
checkUserId(userId);
synchronized (mPackages) {
PackageParser.Service s = mServices.mServices.get(component);
if (s != null) {
ServiceInfo serviceInfo = PackageParserCompat.generateServiceInfo(s, flags);
PackageParser.Package p = mPackages.get(serviceInfo.packageName);
AppSetting settings = (AppSetting) p.mExtras;
ComponentFixer.fixComponentInfo(settings, serviceInfo, userId);
return serviceInfo;
}
}
return null;
}
static final PackageParser.Package parsePackage(Context context, File apk, int flags) throws Throwable {
PackageParser parser = new PackageParser();
PackageParser.Package pkg = parser.parsePackage(apk, flags);
Reflector.with(parser)
.method("collectCertificates", PackageParser.Package.class, boolean.class)
.call(pkg, false);
return pkg;
}
/**
* addScannedPackageLPw directly modifies the package metadata in pm.Settings
* at a point of no-return. We need to make sure that the scanned package does
* not contain bad keyset meta-data that could generate an incorrect
* PackageSetting. Verify that there is a signing keyset, there are no issues
* with null objects, and the upgrade and defined keysets match.
*
* Returns true if the package can safely be added to the keyset metadata.
*/
public void assertScannedPackageValid(PackageParser.Package pkg)
throws PackageManagerException {
if (pkg == null || pkg.packageName == null) {
throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
"Passed invalid package to keyset validation.");
}
ArraySet<PublicKey> signingKeys = pkg.mSigningDetails.publicKeys;
if (signingKeys == null || !(signingKeys.size() > 0) || signingKeys.contains(null)) {
throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
"Package has invalid signing-key-set.");
}
ArrayMap<String, ArraySet<PublicKey>> definedMapping = pkg.mKeySetMapping;
if (definedMapping != null) {
if (definedMapping.containsKey(null) || definedMapping.containsValue(null)) {
throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
"Package has null defined key set.");
}
int defMapSize = definedMapping.size();
for (int i = 0; i < defMapSize; i++) {
if (!(definedMapping.valueAt(i).size() > 0)
|| definedMapping.valueAt(i).contains(null)) {
throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
"Package has null/no public keys for defined key-sets.");
}
}
}
ArraySet<String> upgradeAliases = pkg.mUpgradeKeySets;
if (upgradeAliases != null) {
if (definedMapping == null || !(definedMapping.keySet().containsAll(upgradeAliases))) {
throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
"Package has upgrade-key-sets without corresponding definitions.");
}
}
}
/** Removes all components defined in the given package from the internal structures. */
void removeAllComponents(PackageParser.Package pkg, boolean chatty) {
synchronized (mLock) {
removeAllComponentsLocked(pkg, chatty);
}
}
@DexReplace
private static boolean getGlobalEnable(PackageInfo pi, Context context, PackageParser.Package p, int flags, int userId) {
return Settings.Secure.getInt(context.getContentResolver(), SECURE_SETTING_KEY, 0) != 0;
}
@DexReplace
private static boolean getGlobalEnable(PackageInfo pi, Context context, PackageParser.Package p, int flags, int userId) {
return Settings.Secure.getInt(context.getContentResolver(), SECURE_SETTING_KEY, 0) != 0;
}
@DexReplace
private static boolean getGlobalEnable(PackageInfo pi, Context context, PackageParser.Package p, int flags, int userId) {
return Settings.Secure.getInt(context.getContentResolver(), SECURE_SETTING_KEY, 0) != 0;
}
@Override
public int checkUidPermission(String permName, PackageParser.Package pkg, int uid,
int callingUid) {
return PermissionManagerService.this.checkUidPermission(permName, pkg, uid, callingUid);
}
/**
* Updates the flags for all applications by replacing the flags in the specified mask
* with the provided flag values.
*/
public abstract boolean updatePermissionFlagsForAllApps(int flagMask, int flagValues,
int callingUid, int userId, @NonNull Collection<PackageParser.Package> packages,
@Nullable PermissionCallback callback);