从 apk 文件中获取 minSdkVersion 和 targetSdkVersion
Posted
技术标签:
【中文标题】从 apk 文件中获取 minSdkVersion 和 targetSdkVersion【英文标题】:Get minSdkVersion and targetSdkVersion from apk file 【发布时间】:2013-12-20 18:03:12 【问题描述】:我正在尝试从设备上存储的 apk 中获取 minSdkVersion
和 targetSdkVersion
的值。讨论获取其他详细信息here,但仅讨论 targetSdkVersion
在ApplicationInfo
类中可用。 minSdkVersion
除了解压apk文件,读取androidManifest.xml之外,还能获取到吗?
【问题讨论】:
我想没有办法从清单文件中获取 minSDKVersion。 与实际用例相同的问题***.com/questions/30455858/… 【参考方案1】:使用 Android SDK 附带的apkanalyzer
:
apkanalyzer manifest target-sdk your.apk
apkanalyzer manifest min-sdk your.apk
【讨论】:
【参考方案2】:不需要任何工具,设备上有一个应用程序可以读取清单
https://play.google.com/store/apps/details?id=jp.susatthi.ManifestViewer&hl=en
缺点是,如果 minSdkVersion 没有在清单和 build.gradle 文件中声明,它就不会在这里显示。
【讨论】:
【参考方案3】:如果您只需要 minSdkVersion 和 targetSdkVersion 以及下载的 apk 文件的大量其他详细信息。您所需要的只是 aapt 工具,您可以在终端中运行以下命令。
aapt dump badging yourapk.apk
你可以 grep 为 minSdk 获取 sdkVersion
aapt dump badging yourapk.apk | grep sdkVersion
【讨论】:
这应该得到更多的支持。发现 OP 想知道什么的好方法,无需大量额外工具/乱七八糟。 对于任何试图找到aapt
的人——一旦安装了android开发工具,它就位于/[user home]Android/sdk/[sdk version]/build-tools
(对于mac)。由于某种原因,它不会像adb
那样自动添加到系统路径中【参考方案4】:
对于 Android API 24 (Android N - 7.0) 及更高版本,您确实拥有它:
https://developer.android.com/reference/android/content/pm/ApplicationInfo.html#minSdkVersion
对于早期版本,您可以使用我写的here 的解决方法,或者为此使用库。例如:
https://github.com/jaredrummler/APKParser
请注意,此库可能会占用大量堆内存和时间,因此需要进行一些更改以使其更适合此任务,正如我建议的 here。
【讨论】:
【参考方案5】:使用 aapt:
aapt list -a package.apk | grep SDK版本
您将看到十六进制的版本号。例如:
A: android:minSdkVersion(0x0101020c)=(type 0x10)0x3 A: android:targetSdkVersion(0x01010270)=(type 0x10)0xc
对于这个 apk,minSdkVersion 是 0x3 即 3,targetSdkVersion 是 0xc 即 12。
以下已编辑答案:-
然后您可以通过逆向工程来实现它,您可以通过以下步骤从 apk 中获取源代码 解码 .apk 文件的程序,分步方法: 第 1 步:
Make a new folder and copy over the .apk file that you want to decode.
Now rename the extension of this .apk file to .zip (e.g. rename from filename.apk to filename.zip) and save it. Now you can access the classes.dex files, etc. At this stage you are able to see drawables but not xml and java files, so continue.
第 2 步:
Now extract this .zip file in the same folder (or NEW FOLDER).
Download dex2jar and extract it to the same folder (or NEW FOLDER).
Move the classes.dex file into the dex2jar folder.
Now open command prompt and change directory to that folder (or NEW FOLDER). Then write d2j-dex2jar classes.dex (for mac terminal or ubuntu write ./d2j-dex2jar.sh classes.dex) and press enter. You now have the classes.dex.dex2jar file in the same folder.
Download java decompiler, double click on jd-gui, click on open file, and open classes.dex.dex2jar file from that folder: now you get class files.
Save all of these class files (In jd-gui, click File -> Save All Sources) by src name. At this stage you get the java source but the .xml files are still unreadable, so continue.
第 3 步:
现在打开另一个新文件夹
Put in the .apk file which you want to decode
Download the latest version of apktool AND apktool install window (both can be downloaded from the same link) and place them in the same folder
Download framework-res.apk and put it in the same folder (Not all apk file need this file, but it doesn't hurt)
Open a command window
Navigate to the root directory of APKtool and type the following command: apktool if framework-res.apk
apktool d myApp.apk (where myApp.apk denotes the filename that you want to decode)
现在您在该文件夹中获得了一个文件夹,并且可以轻松读取 apk 的 xml 文件。 第 4 步:
这不是任何步骤,只需将两个文件夹(在本例中为两个新文件夹)的内容复制到单个文件夹
并享受源代码...
【讨论】:
不满足要求“答案必须说明如何在 Android 应用中检索 APK 文件的 minSdkVersion” 然后你可以通过逆向工程来实现它,你可以从 apk 中获取源代码。编辑了我的答案 这应该被标记为接受的答案,tnx 很多,在 windows 中,使用 findstr 而不是 grep 你救了我的命。谢谢朋友~ 感谢您的积极反馈。我不是来接受答案的,我是来回馈社区的 :)【参考方案6】:我不相信你自己可以做到这一点,并且没有为此准备的 api。当前读取和解析 AndroidManifest 的方法根本不考虑 minSdkVersion。
为了在不使用现成功能的情况下检查您的 apk 文件,您最终需要手动将其添加到资产管理器中。并且该方法标有“不适用于应用程序”,根据我的经验,这通常意味着从应用程序调用它不是一个好主意。
http://androidxref.com/5.1.1_r6/xref/frameworks/base/core/java/android/content/res/AssetManager.java#612
如果你设法打电话:
public final int addAssetPath(String path)
从您的应用程序中,您应该能够通过解析 XML 文件来获取 minSdkVersion,请考虑以下代码:
private static final String ANDROID_MANIFEST_FILENAME = "AndroidManifest.xml";
....
method:
final int cookie = loadApkIntoAssetManager(assets, apkPath, flags);
Resources res = null;
XmlResourceParser parser = null;
try
res = new Resources(assets, mMetrics, null);
assets.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Build.VERSION.RESOURCES_SDK_INT);
parser = assets.openXmlResourceParser(cookie, ANDROID_MANIFEST_FILENAME);
final String[] outError = new String[1];
final Package pkg = parseBaseApk(res, parser, flags, outError);
if (pkg == null)
throw new PackageParserException(mParseError,
apkPath + " (at " + parser.getPositionDescription() + "): " + outError[0]);
代码: http://androidxref.com/5.1.1_r6/xref/frameworks/base/core/java/android/content/pm/PackageParser.java#863
您应该能够使用 XmlResourceParser 解析您的 AndroidManifest 文件并找到 minSdkVersion 的元素。
如果您想自己尝试,只需复制以下静态方法并调用getMinSdkVersion(yourApkFile)
:
/**
* Parses AndroidManifest of the given apkFile and returns the value of
* minSdkVersion using undocumented API which is marked as
* "not to be used by applications"
*
* @param apkFile
* @return minSdkVersion or -1 if not found in Manifest
* @throws IOException
* @throws XmlPullParserException
*/
public static int getMinSdkVersion(File apkFile) throws IOException,
XmlPullParserException
XmlResourceParser parser = getParserForManifest(apkFile);
while (parser.next() != XmlPullParser.END_DOCUMENT)
if (parser.getEventType() == XmlPullParser.START_TAG
&& parser.getName().equals("uses-sdk"))
for (int i = 0; i < parser.getAttributeCount(); i++)
if (parser.getAttributeName(i).equals("minSdkVersion"))
return parser.getAttributeIntValue(i, -1);
return -1;
/**
* Tries to get the parser for the given apkFile from @link AssetManager
* using undocumented API which is marked as
* "not to be used by applications"
*
* @param apkFile
* @return
* @throws IOException
*/
private static XmlResourceParser getParserForManifest(final File apkFile)
throws IOException
final Object assetManagerInstance = getAssetManager();
final int cookie = addAssets(apkFile, assetManagerInstance);
return ((AssetManager) assetManagerInstance).openXmlResourceParser(
cookie, "AndroidManifest.xml");
/**
* Get the cookie of an asset using an undocumented API call that is marked
* as "no to be used by applications" in its source code
*
* @see <a
* href="http://androidxref.com/5.1.1_r6/xref/frameworks/base/core/java/android/content/res/AssetManager.java#612">AssetManager.java#612</a>
* @return the cookie
*/
private static int addAssets(final File apkFile,
final Object assetManagerInstance)
try
Method addAssetPath = assetManagerInstance.getClass().getMethod(
"addAssetPath", new Class[] String.class );
return (Integer) addAssetPath.invoke(assetManagerInstance,
apkFile.getAbsolutePath());
catch (NoSuchMethodException e)
e.printStackTrace();
catch (InvocationTargetException e)
e.printStackTrace();
catch (IllegalAccessException e)
e.printStackTrace();
return -1;
/**
* Get @link AssetManager using reflection
*
* @return
*/
private static Object getAssetManager()
Class assetManagerClass = null;
try
assetManagerClass = Class
.forName("android.content.res.AssetManager");
Object assetManagerInstance = assetManagerClass.newInstance();
return assetManagerInstance;
catch (ClassNotFoundException e)
e.printStackTrace();
catch (InstantiationException e)
e.printStackTrace();
catch (IllegalAccessException e)
e.printStackTrace();
return null;
您可能也需要一个反射调用来设置它:
assets.setConfiguration(0, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Build.VERSION.RESOURCES_SDK_INT);
不保证它会起作用(也不保证它不会对您的手机有害)操作应该是安全的,因为您正在创建一个新的 AssetManager 并且不依赖于您的应用程序的 AssetManager。快速浏览一下 C++ 代码,它似乎没有被添加到任何全局列表中。
代码: http://androidxref.com/5.1.1_r6/xref/frameworks/base/libs/androidfw/AssetManager.cpp#173
【讨论】:
我成功测试了解决方案,并将静态方法getMinSdkVersion
添加到代码示例中,使其立即可用。我为这个解决方案提供了赏金,因为使用了相同的解析器,Android 使用它自己。但是,在其 cmets 中使用标记为“不被应用程序使用”的未记录 API 调用是一个问题。
这个函数很少失败,因为 getAttributeName 可以返回一个空字符串(为已安装的应用程序“TitaniumBackup”找到这个:play.google.com/store/apps/…)。我找到了一种通过使用 getAttributeNameResource 来解决这个问题的方法,并在这里写了:***.com/a/43603448/878126
如何获得 apkPath ?是ApplicationInfo.sourceDir
吗?【参考方案7】:
这很容易做到。你需要关注
-
Apk Extractor 或输入命令 adb pull /data/app/package_name.apk
Apk Tooljar文件
现在输入命令
apktool d package_name.apk
apk 将被提取到当前目录,您将拥有一个可读的 AndroidManfiest 文件
【讨论】:
不满足要求“答案必须说明如何在 Android 应用中检索 APK 文件的 minSdkVersion”【参考方案8】:将 apk 复制到新目录中:
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List pkgAppsList = getPackageManager().queryIntentActivities(mainIntent, 0);
for (Object object : pkgAppsList)
ResolveInfo info = (ResolveInfo) object;
File file = new File(info.activityInfo.applicationInfo.publicSourceDir);
// Copy the .apk file to wherever
以下方法将AndroidManifest读入byte[]进行处理:
public void getIntents(String path_to_apk)
try
JarFile jf = new JarFile(path_to_apk);
InputStream is = jf.getInputStream(jf.getEntry("AndroidManifest.xml"));
byte[] xml = new byte[is.available()];
int br = is.read(xml);
//Tree tr = TrunkFactory.newTree();
decompressXML(xml);
//prt("XML\n"+tr.list());
catch (Exception ex)
console.log("getIntents, ex: "+ex); ex.printStackTrace();
最后解压android manifest的xml:
// decompressXML -- Parse the 'compressed' binary form of Android XML docs
// such as for AndroidManifest.xml in .apk files
public static int endDocTag = 0x00100101;
public static int startTag = 0x00100102;
public static int endTag = 0x00100103;
public void decompressXML(byte[] xml)
// Compressed XML file/bytes starts with 24x bytes of data,
// 9 32 bit words in little endian order (LSB first):
// 0th word is 03 00 08 00
// 3rd word SEEMS TO BE: Offset at then of StringTable
// 4th word is: Number of strings in string table
// WARNING: Sometime I indiscriminently display or refer to word in
// little endian storage format, or in integer format (ie MSB first).
int numbStrings = LEW(xml, 4*4);
// StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
// of the length/string data in the StringTable.
int sitOff = 0x24; // Offset of start of StringIndexTable
// StringTable, each string is represented with a 16 bit little endian
// character count, followed by that number of 16 bit (LE) (Unicode) chars.
int stOff = sitOff + numbStrings*4; // StringTable follows StrIndexTable
// XMLTags, The XML tag tree starts after some unknown content after the
// StringTable. There is some unknown data after the StringTable, scan
// forward from this point to the flag for the start of an XML start tag.
int xmlTagOff = LEW(xml, 3*4); // Start from the offset in the 3rd word.
// Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
for (int ii=xmlTagOff; ii<xml.length-4; ii+=4)
if (LEW(xml, ii) == startTag)
xmlTagOff = ii; break;
// end of hack, scanning for start of first start tag
// XML tags and attributes:
// Every XML start and end tag consists of 6 32 bit words:
// 0th word: 02011000 for startTag and 03011000 for endTag
// 1st word: a flag?, like 38000000
// 2nd word: Line of where this tag appeared in the original source file
// 3rd word: FFFFFFFF ??
// 4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
// 5th word: StringIndex of Element Name
// (Note: 01011000 in 0th word means end of XML document, endDocTag)
// Start tags (not end tags) contain 3 more words:
// 6th word: 14001400 meaning??
// 7th word: Number of Attributes that follow this tag(follow word 8th)
// 8th word: 00000000 meaning??
// Attributes consist of 5 words:
// 0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
// 1st word: StringIndex of Attribute Name
// 2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
// 3rd word: Flags?
// 4th word: str ind of attr value again, or ResourceId of value
// TMP, dump string table to tr for debugging
//tr.addSelect("strings", null);
//for (int ii=0; ii<numbStrings; ii++)
// // Length of string starts at StringTable plus offset in StrIndTable
// String str = compXmlString(xml, sitOff, stOff, ii);
// tr.add(String.valueOf(ii), str);
//
//tr.parent();
// Step through the XML tree element tags and attributes
int off = xmlTagOff;
int indent = 0;
int startTagLineNo = -2;
while (off < xml.length)
int tag0 = LEW(xml, off);
//int tag1 = LEW(xml, off+1*4);
int lineNo = LEW(xml, off+2*4);
//int tag3 = LEW(xml, off+3*4);
int nameNsSi = LEW(xml, off+4*4);
int nameSi = LEW(xml, off+5*4);
if (tag0 == startTag) // XML START TAG
int tag6 = LEW(xml, off+6*4); // Expected to be 14001400
int numbAttrs = LEW(xml, off+7*4); // Number of Attributes to follow
//int tag8 = LEW(xml, off+8*4); // Expected to be 00000000
off += 9*4; // Skip over 6+3 words of startTag data
String name = compXmlString(xml, sitOff, stOff, nameSi);
//tr.addSelect(name, null);
startTagLineNo = lineNo;
// Look for the Attributes
StringBuffer sb = new StringBuffer();
for (int ii=0; ii<numbAttrs; ii++)
int attrNameNsSi = LEW(xml, off); // AttrName Namespace Str Ind, or FFFFFFFF
int attrNameSi = LEW(xml, off+1*4); // AttrName String Index
int attrValueSi = LEW(xml, off+2*4); // AttrValue Str Ind, or FFFFFFFF
int attrFlags = LEW(xml, off+3*4);
int attrResId = LEW(xml, off+4*4); // AttrValue ResourceId or dup AttrValue StrInd
off += 5*4; // Skip over the 5 words of an attribute
String attrName = compXmlString(xml, sitOff, stOff, attrNameSi);
String attrValue = attrValueSi!=-1
? compXmlString(xml, sitOff, stOff, attrValueSi)
: "resourceID 0x"+Integer.toHexString(attrResId);
sb.append(" "+attrName+"=\""+attrValue+"\"");
//tr.add(attrName, attrValue);
prtIndent(indent, "<"+name+sb+">");
indent++;
else if (tag0 == endTag) // XML END TAG
indent--;
off += 6*4; // Skip over 6 words of endTag data
String name = compXmlString(xml, sitOff, stOff, nameSi);
prtIndent(indent, "</"+name+"> (line "+startTagLineNo+"-"+lineNo+")");
//tr.parent(); // Step back up the NobTree
else if (tag0 == endDocTag) // END OF XML DOC TAG
break;
else
prt(" Unrecognized tag code '"+Integer.toHexString(tag0)
+"' at offset "+off);
break;
// end of while loop scanning tags and attributes of XML tree
prt(" end at offset "+off);
// end of decompressXML
public String compXmlString(byte[] xml, int sitOff, int stOff, int strInd)
if (strInd < 0) return null;
int strOff = stOff + LEW(xml, sitOff+strInd*4);
return compXmlStringAt(xml, strOff);
public static String spaces = " ";
public void prtIndent(int indent, String str)
prt(spaces.substring(0, Math.min(indent*2, spaces.length()))+str);
// compXmlStringAt -- Return the string stored in StringTable format at
// offset strOff. This offset points to the 16 bit string length, which
// is followed by that number of 16 bit (Unicode) chars.
public String compXmlStringAt(byte[] arr, int strOff)
int strLen = arr[strOff+1]<<8&0xff00 | arr[strOff]&0xff;
byte[] chars = new byte[strLen];
for (int ii=0; ii<strLen; ii++)
chars[ii] = arr[strOff+2+ii*2];
return new String(chars); // Hack, just use 8 byte chars
// end of compXmlStringAt
// LEW -- Return value of a Little Endian 32 bit word from the byte array
// at offset off.
public int LEW(byte[] arr, int off)
return arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000
| arr[off+1]<<8&0xff00 | arr[off]&0xFF;
// end of LEW
附:我从这里检索了这些方法:
How to get the .apk file of an application programmatically
这里:
How to parse the AndroidManifest.xml file inside an .apk package
【讨论】:
我成功测试了解决方案。它解析了整个 AndroidManifest,令人印象深刻。感谢您提供其他 SO 问题的链接。这导致了以某种方式解析 AndroidManifest 的真正问题。与 JohanShogun 的答案相比,它使用自己的解析器,而没有使用未记录的 API 调用。但是,解析器可能会在未来某个时间在较新的 APK 版本中失败。没有像 JohanShogun 的回答那样获得最合适和最新的解析器的机制。以上是关于从 apk 文件中获取 minSdkVersion 和 targetSdkVersion的主要内容,如果未能解决你的问题,请参考以下文章
如何从 Android 中的 apk 文件中获取源代码? [复制]
如何以编程方式从 sdcard/storage .apk 文件中获取 appicon?