[Android]教你如何获取未安装应用的ResolveInfo
原理:
public PackageInfo getPackageArchiveInfo(String archiveFilePath, int flags) { PackageParser packageParser = new PackageParser(archiveFilePath); DisplayMetrics metrics = new DisplayMetrics(); metrics.setToDefaults(); final File sourceFile = new File(archiveFilePath); PackageParser.Package pkg = packageParser.parsePackage( sourceFile, archiveFilePath, metrics, 0); if (pkg == null) { return null; } if ((flags & GET_SIGNATURES) != 0) { packageParser.collectCertificates(pkg, 0); } return PackageParser.generatePackageInfo(pkg, null, flags, 0, 0); }
这里是源码,首先通过PackageParser解析,然后通过PackageParser.generatePackageInfo返回PackageInfo,但是PackageInfo里却把intent-filter给去掉了,不知道为啥,不过既然知道了这段代码那么就好好办了。那就是通过反射把PackageParser.Package得到,然后再封装成intentfilter。
解决方案:
try { // 先得到解析类PackageParser并实例化 Class packageParserClass = Class.forName("android.content.pm.PackageParser"); Object packageParser = packageParserClass.getConstructor(String.class).newInstance(dexPath); // 构建参数 DisplayMetrics metrics = new DisplayMetrics(); metrics.setToDefaults(); File sourceFile = new File(dexPath); // 调用PackageParser的parsePackage解析数据 Method method = packageParserClass.getDeclaredMethod("parsePackage", File.class, String.class, DisplayMetrics.class, int.class); method.setAccessible(true); Object Package = method.invoke(packageParser, sourceFile, dexPath, metrics, 0); // 反射得到结果 Field activities = Package.getClass().getDeclaredField("activities"); activities.setAccessible(true); ArrayList filters = (ArrayList) activities.get(Package); for (int i = 0; i < filters.size(); i++) { Object activity = filters.get(i); Field intentsField = activity.getClass().getField("intents"); intentsField.setAccessible(true); ArrayList<IntentFilter> intents = (ArrayList<IntentFilter>) intentsField.get(activity); for (int j = 0; j < intents.size(); j++) { if (intents.iterator().hasNext()) { String actionString = intents.get(0).getAction(0); String categoryString = intents.get(0).getCategory(0); System.out.println(actionString + " " + categoryString); } } } } catch (Exception e) { }dexPath就是你要解析的APK的路径。intentfilter里有action和category。这样就实现了得到一个activity的ResolveInfo,至于为什么要类型转来转去,那就具体看安卓源码吧。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。