下面列出了android.content.pm.PackageParser#Activity() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** Add all components defined in the given package to the internal structures. */
void addAllComponents(PackageParser.Package pkg, boolean chatty) {
final ArrayList<PackageParser.ActivityIntentInfo> newIntents = new ArrayList<>();
synchronized (mLock) {
addActivitiesLocked(pkg, newIntents, chatty);
addReceiversLocked(pkg, chatty);
addProvidersLocked(pkg, chatty);
addServicesLocked(pkg, chatty);
}
final String setupWizardPackage = sPackageManagerInternal.getKnownPackageName(
PACKAGE_SETUP_WIZARD, UserHandle.USER_SYSTEM);
for (int i = newIntents.size() - 1; i >= 0; --i) {
final PackageParser.ActivityIntentInfo intentInfo = newIntents.get(i);
final PackageParser.Package disabledPkg = sPackageManagerInternal
.getDisabledSystemPackage(intentInfo.activity.info.packageName);
final List<PackageParser.Activity> systemActivities =
disabledPkg != null ? disabledPkg.activities : null;
adjustPriority(systemActivities, intentInfo, setupWizardPackage);
}
}
@GuardedBy("mLock")
private void addActivitiesLocked(PackageParser.Package pkg,
List<PackageParser.ActivityIntentInfo> newIntents, boolean chatty) {
final int activitiesSize = pkg.activities.size();
StringBuilder r = null;
for (int i = 0; i < activitiesSize; i++) {
PackageParser.Activity a = pkg.activities.get(i);
a.info.processName =
fixProcessName(pkg.applicationInfo.processName, a.info.processName);
mActivities.addActivity(a, "activity", newIntents);
if (DEBUG_PACKAGE_SCANNING && chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (DEBUG_PACKAGE_SCANNING && chatty) {
Log.d(TAG, " Activities: " + (r == null ? "<NONE>" : r));
}
}
@GuardedBy("mLock")
private void addReceiversLocked(PackageParser.Package pkg, boolean chatty) {
final int receiversSize = pkg.receivers.size();
StringBuilder r = null;
for (int i = 0; i < receiversSize; i++) {
PackageParser.Activity a = pkg.receivers.get(i);
a.info.processName = fixProcessName(pkg.applicationInfo.processName,
a.info.processName);
mReceivers.addActivity(a, "receiver", null);
if (DEBUG_PACKAGE_SCANNING && chatty) {
if (r == null) {
r = new StringBuilder(256);
} else {
r.append(' ');
}
r.append(a.info.name);
}
}
if (DEBUG_PACKAGE_SCANNING && chatty) {
Log.d(TAG, " Receivers: " + (r == null ? "<NONE>" : r));
}
}
/**
* Finds a privileged activity that matches the specified activity names.
*/
private static PackageParser.Activity findMatchingActivity(
List<PackageParser.Activity> activityList, ActivityInfo activityInfo) {
for (PackageParser.Activity sysActivity : activityList) {
if (sysActivity.info.name.equals(activityInfo.name)) {
return sysActivity;
}
if (sysActivity.info.name.equals(activityInfo.targetActivity)) {
return sysActivity;
}
if (sysActivity.info.targetActivity != null) {
if (sysActivity.info.targetActivity.equals(activityInfo.name)) {
return sysActivity;
}
if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) {
return sysActivity;
}
}
}
return null;
}
public List queryIntentForPackage(Intent intent, String resolvedType,
int flags, ArrayList<PackageParser.Activity> packageActivities) {
if (packageActivities == null) {
return null;
}
mFlags = flags;
final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
int N = packageActivities.size();
ArrayList<ArrayList<PackageParser.ActivityIntentInfo>> listCut = new ArrayList<ArrayList<PackageParser.ActivityIntentInfo>>(
N);
ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
for (int i = 0; i < N; ++i) {
intentFilters = packageActivities.get(i).intents;
if (intentFilters != null && intentFilters.size() > 0) {
listCut.add(intentFilters);
}
}
return super.queryIntentFromList(intent, resolvedType, defaultOnly,
listCut);
}
/**
* 启动插件
*
* @param info
* 插件信息
*/
void startPlugin(PluginInfo info) {
if (info == null) {
return;
}
if (!mPlugins.containsKey(info.packageName)) {
Log.e(TAG, "no plugin or not install");
return;
}
Intent intent = new Intent(Intent.ACTION_MAIN);
List res = mActivitys.queryIntentForPackage(intent, null, 0, info.mPackageObj.activities);
if (res != null && res.size() > 0) {
PackageParser.Activity activity = (android.content.pm.PackageParser.Activity) res.get(0);
String className = activity.className;
Intent newIntent = new Intent(mContext, PluginBlankActivity.class);
newIntent.putExtra(PluginBlankActivity.ACTIVITY_NAME, className);
newIntent.putExtra(PluginBlankActivity.PLUGIN_NAME, info.packageName);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(newIntent);
} else {
showToast(mContext, "this plugin no enter class", Toast.LENGTH_LONG);
}
}
@Override
protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, int match) {
final PackageParser.Activity activity = info.activity;
ActivityInfo ai = PackageParserCompat.generateActivityInfo(activity, mFlags);
if (ai == null) {
return null;
}
final ResolveInfo res = new ResolveInfo();
res.activityInfo = ai;
if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
res.filter = info;
}
res.priority = info.getPriority();
res.preferredOrder = activity.owner.mPreferredOrder;
// System.out.println("Result: " + res.activityInfo.className +
// " = " + res.priority);
res.match = match;
res.isDefault = info.hasDefault;
res.labelRes = info.labelRes;
res.nonLocalizedLabel = info.nonLocalizedLabel;
res.icon = info.icon;
return res;
}
public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, int flags,
ArrayList<PackageParser.Activity> packageActivities) {
if (packageActivities == null) {
return null;
}
mFlags = flags;
final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
final int N = packageActivities.size();
ArrayList<PackageParser.ActivityIntentInfo[]> listCut = new ArrayList<PackageParser.ActivityIntentInfo[]>(
N);
ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
for (int i = 0; i < N; ++i) {
intentFilters = packageActivities.get(i).intents;
if (intentFilters != null && intentFilters.size() > 0) {
PackageParser.ActivityIntentInfo[] array = new PackageParser.ActivityIntentInfo[intentFilters
.size()];
intentFilters.toArray(array);
listCut.add(array);
}
}
return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut);
}
List<ResolveInfo> queryActivities(Intent intent, String resolvedType, int flags,
List<PackageParser.Activity> activities, int userId) {
synchronized (mLock) {
return mActivities.queryIntentForPackage(
intent, resolvedType, flags, activities, userId);
}
}
@Override
protected boolean allowFilterResult(
PackageParser.ActivityIntentInfo filter, List<PackageParser.Activity> dest) {
for (int i = dest.size() - 1; i >= 0; i--) {
PackageParser.Activity destAi = dest.get(i);
if (destAi == filter.activity) {
return false;
}
}
return true;
}
private void addActivity(PackageParser.Activity a, String type,
List<PackageParser.ActivityIntentInfo> newIntents) {
mActivities.put(a.getComponentName(), a);
if (DEBUG_SHOW_INFO) {
final CharSequence label = a.info.nonLocalizedLabel != null
? a.info.nonLocalizedLabel
: a.info.name;
Log.v(TAG, " " + type + " " + label + ":");
}
if (DEBUG_SHOW_INFO) {
Log.v(TAG, " Class=" + a.info.name);
}
final int intentsSize = a.intents.size();
for (int j = 0; j < intentsSize; j++) {
PackageParser.ActivityIntentInfo intent = a.intents.get(j);
if (newIntents != null && "activity".equals(type)) {
newIntents.add(intent);
}
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);
}
}
protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
PackageParser.Activity activity = (PackageParser.Activity) label;
out.print(prefix);
out.print(Integer.toHexString(System.identityHashCode(activity)));
out.print(' ');
activity.printComponentShortName(out);
if (count > 1) {
out.print(" ("); out.print(count); out.print(" filters)");
}
out.println();
}
public final void removeActivity(PackageParser.Activity a) {
mActivities.remove(a.getComponentName());
int NI = a.intents.size();
for (int j = 0; j < NI; j++) {
PackageParser.ActivityIntentInfo intent = a.intents.get(j);
removeFilter(intent);
}
}
@Override
public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
checkUserId(userId);
synchronized (mPackages) {
PackageParser.Activity a = mReceivers.mActivities.get(component);
if (a != null) {
ActivityInfo receiverInfo = PackageParserCompat.generateActivityInfo(a, flags);
PackageParser.Package p = mPackages.get(receiverInfo.packageName);
AppSetting settings = (AppSetting) p.mExtras;
ComponentFixer.fixComponentInfo(settings, receiverInfo, userId);
return receiverInfo;
}
}
return null;
}
/** Returns the given activity */
PackageParser.Activity getActivity(ComponentName component) {
synchronized (mLock) {
return mActivities.mActivities.get(component);
}
}
/** Returns the given receiver */
PackageParser.Activity getReceiver(ComponentName component) {
synchronized (mLock) {
return mReceivers.mActivities.get(component);
}
}
List<ResolveInfo> queryReceivers(Intent intent, String resolvedType, int flags,
List<PackageParser.Activity> receivers, int userId) {
synchronized (mLock) {
return mReceivers.queryIntentForPackage(intent, resolvedType, flags, receivers, userId);
}
}
public LoadedPlugin(PluginManager pluginManager, Context context, File apk) throws Exception {
this.mPluginManager = pluginManager;
this.mHostContext = context;
this.mLocation = apk.getAbsolutePath();
this.mPackage = PackageParserCompat.parsePackage(context, apk, PackageParser.PARSE_MUST_BE_APK);
this.mPackage.applicationInfo.metaData = this.mPackage.mAppMetaData;
this.mPackageInfo = new PackageInfo();
this.mPackageInfo.applicationInfo = this.mPackage.applicationInfo;
this.mPackageInfo.applicationInfo.sourceDir = apk.getAbsolutePath();
if (Build.VERSION.SDK_INT >= 28
|| (Build.VERSION.SDK_INT == 27 && Build.VERSION.PREVIEW_SDK_INT != 0)) { // Android P Preview
try {
this.mPackageInfo.signatures = this.mPackage.mSigningDetails.signatures;
} catch (Throwable e) {
PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), PackageManager.GET_SIGNATURES);
this.mPackageInfo.signatures = info.signatures;
}
} else {
this.mPackageInfo.signatures = this.mPackage.mSignatures;
}
this.mPackageInfo.packageName = this.mPackage.packageName;
if (pluginManager.getLoadedPlugin(mPackageInfo.packageName) != null) {
throw new RuntimeException("plugin has already been loaded : " + mPackageInfo.packageName);
}
this.mPackageInfo.versionCode = this.mPackage.mVersionCode;
this.mPackageInfo.versionName = this.mPackage.mVersionName;
this.mPackageInfo.permissions = new PermissionInfo[0];
this.mPackageManager = createPluginPackageManager();
this.mPluginContext = createPluginContext(null);
this.mNativeLibDir = getDir(context, Constants.NATIVE_DIR);
this.mPackage.applicationInfo.nativeLibraryDir = this.mNativeLibDir.getAbsolutePath();
this.mResources = createResources(context, getPackageName(), apk);
this.mClassLoader = createClassLoader(context, apk, this.mNativeLibDir, context.getClassLoader());
tryToCopyNativeLib(apk);
// Cache instrumentations
Map<ComponentName, InstrumentationInfo> instrumentations = new HashMap<ComponentName, InstrumentationInfo>();
for (PackageParser.Instrumentation instrumentation : this.mPackage.instrumentation) {
instrumentations.put(instrumentation.getComponentName(), instrumentation.info);
}
this.mInstrumentationInfos = Collections.unmodifiableMap(instrumentations);
this.mPackageInfo.instrumentation = instrumentations.values().toArray(new InstrumentationInfo[instrumentations.size()]);
// Cache activities
Map<ComponentName, ActivityInfo> activityInfos = new HashMap<ComponentName, ActivityInfo>();
for (PackageParser.Activity activity : this.mPackage.activities) {
activity.info.metaData = activity.metaData;
activityInfos.put(activity.getComponentName(), activity.info);
}
this.mActivityInfos = Collections.unmodifiableMap(activityInfos);
this.mPackageInfo.activities = activityInfos.values().toArray(new ActivityInfo[activityInfos.size()]);
// Cache services
Map<ComponentName, ServiceInfo> serviceInfos = new HashMap<ComponentName, ServiceInfo>();
for (PackageParser.Service service : this.mPackage.services) {
serviceInfos.put(service.getComponentName(), service.info);
}
this.mServiceInfos = Collections.unmodifiableMap(serviceInfos);
this.mPackageInfo.services = serviceInfos.values().toArray(new ServiceInfo[serviceInfos.size()]);
// Cache providers
Map<String, ProviderInfo> providers = new HashMap<String, ProviderInfo>();
Map<ComponentName, ProviderInfo> providerInfos = new HashMap<ComponentName, ProviderInfo>();
for (PackageParser.Provider provider : this.mPackage.providers) {
providers.put(provider.info.authority, provider.info);
providerInfos.put(provider.getComponentName(), provider.info);
}
this.mProviders = Collections.unmodifiableMap(providers);
this.mProviderInfos = Collections.unmodifiableMap(providerInfos);
this.mPackageInfo.providers = providerInfos.values().toArray(new ProviderInfo[providerInfos.size()]);
// Register broadcast receivers dynamically
Map<ComponentName, ActivityInfo> receivers = new HashMap<ComponentName, ActivityInfo>();
for (PackageParser.Activity receiver : this.mPackage.receivers) {
receivers.put(receiver.getComponentName(), receiver.info);
BroadcastReceiver br = BroadcastReceiver.class.cast(getClassLoader().loadClass(receiver.getComponentName().getClassName()).newInstance());
for (PackageParser.ActivityIntentInfo aii : receiver.intents) {
this.mHostContext.registerReceiver(br, aii);
}
}
this.mReceiverInfos = Collections.unmodifiableMap(receivers);
this.mPackageInfo.receivers = receivers.values().toArray(new ActivityInfo[receivers.size()]);
// try to invoke plugin's application
invokeApplication();
}
/**
* 解析APK的manifest
*
* @param info
* 插件信息
*/
private void getPackageInfo(PluginInfo info) {
int flags = PackageManager.GET_ACTIVITIES | PackageManager.GET_CONFIGURATIONS
| PackageManager.GET_INSTRUMENTATION | PackageManager.GET_PERMISSIONS | PackageManager.GET_PROVIDERS
| PackageManager.GET_RECEIVERS | PackageManager.GET_SERVICES | PackageManager.GET_SIGNATURES;
// 需要获取Package对象,主要是处理隐式启动插件中的activity
PackageParser parser = new PackageParser(info.apkPath);
DisplayMetrics metrics = new DisplayMetrics();
metrics.setToDefaults();
File sourceFile = new File(info.apkPath);
PackageParser.Package pack = parser.parsePackage(sourceFile, info.apkPath, metrics, 0);
// 因为PackagePaser的generatePackageInfo方法不同版本参数相差太多,所以还是用packagemanager的api
// 但这样导致APK被解析了两次,上面获取Package是一次
PackageInfo packageInfo = mContext.getPackageManager().getPackageArchiveInfo(info.apkPath, flags);
info.packageName = packageInfo.packageName;
info.mPackageObj = pack;
info.mPackageInfo = packageInfo;
ArrayList<PackageParser.Activity> activitys = pack.activities;
int size = activitys.size();
for (int i = 0; i < size; i++) {
mActivitys.addActivity(activitys.get(i));
}
ArrayList<PackageParser.Service> services = pack.services;
size = services.size();
for (int i = 0; i < size; i++) {
mServices.addService(services.get(i));
}
ArrayList<PackageParser.Provider> providers = pack.providers;
size = providers.size();
for (int i = 0; i < size; i++) {
Provider p = providers.get(i);
String names[] = PATTERN_SEMICOLON.split(p.info.authority);
for (int j = 0; j < names.length; j++) {
mProviderInfoMap.put(names[i], p);
}
}
}
@Override
protected PackageParser.Activity newResult(PackageParser.ActivityIntentInfo info,
int match) {
return info.activity;
}