Android:将标准XML转换为Android二进制XML格式(AXML)



我想将一个纯文本的AndroidManifest.xml文件转换为Android用来将其封装在最终APK中的二进制格式。

我想在Java中做到这一点,因为我需要在android设备上做这件事(这就是为什么这个问题是NOT的重复:如何将XML转换为android二进制XML。我知道你可以使用AAPT,但我需要一个Java方法)

有很多工具可以将二进制xml解码为可读文件,但没有关于如何做相反的事情,这正是我想要的。

任何关于如何实现这一目标的信息或提示都将不胜感激。

您可能会发现许多命令行工具可用于编译和反编译Android的xml文件。这些工具由几个构建工具组合而成,包括aapt(Android资产打包工具),用于查看、创建和更新Zip兼容的归档文件(Zip、jar、apk)。由于该工具是Android SDK的一部分,因此在Java中没有它的本机实现。

幸运的是,自编译Android存储库在Java Native Interface(JNI)中拥有所有必要的文件。它们可以在安卓应用程序中使用,并且能够自我编译、变异和病毒传播。

以下是应用程序中可用的本地模块列表:

aapt -> Platform_Framework_Basetoolsaapt aidl -> Platform_Framework_Basetoolsaidl androidfw -> Platform_Framework_Baseincludeandroidfw
zipalign -> Platform_Buildtoolszipalign host -> Platform_Buildlibhost
libpng -> Platform_External_Libpng expat -> Platform_External_Expat zlib -> Platform_External_Zlib
libcutils -> Platform_System_Corelibcutils cutils -> Platform_System_Coreincludecutils
liblog -> Platform_System_Coreliblog log -> Platform_System_Coreincludelog
libutils -> Platform_System_Corelibutils utils -> Platform_System_Coreincludeutils
log.h -> Platform_System_Coreincludeandroid
asset_manager.h -> Platform_Framework_Nativeincludeandroid looper.h -> Platform_Framework_Nativeincludeandroid
zopfli -> zopflisrc
ld -> Tool_Chain_Utilsbinutils-2.25ld

如果你仔细查看源代码,你会发现该应用程序使用本机jni文件执行aapt命令:

private void runAapt() throws Exception {
Util.deleteRecursive(new File(S.dirRes, "drawable-xxhdpi"));
Aapt aapt = new Aapt();
int exitCode = aapt.fnExecute("aapt p -f -v -M " + S.xmlMan.getPath() + " -F " + S.ap_Resources.getPath()
+ " -I " + S.jarAndroid.getPath() + " -A " + S.dirAssets.getPath() + " -S " + S.dirRes.getPath()
+ " -J " + S.dirGen.getPath());
if (exitCode != 0) {
throw new Exception("AAPT exit(" + exitCode + ")");
}
}

现在,通过示例代码来了解这些功能是如何实现的。例如,更改清单文件中的值,

private void modifyManifest() throws Exception {
Document dom = Util.readXml(S.xmlMan);
dom.getDocumentElement().getAttributes().getNamedItem("package").setNodeValue(userInput.appPackage);
Transformer t = tf.newTransformer();
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.setOutputProperty(OutputKeys.METHOD, "xml");
t.setOutputProperty(OutputKeys.VERSION, "1.0");
t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
t.transform(new DOMSource(dom), new StreamResult(new FileOutputStream(xmlFile)));
} 

从github发布页面下载xml2axml.jar工具,然后可以使用以下命令解码axml和编码xml文件:

将xml文件编码到axml:

java -jar xml2axml e [AndroidManifest-readable-in.xml] [AndroidManifest-bin-out.xml]

将axml文件解码为xml:

java -jar xml2axml d [AndroidManifest-bin-in.xml] [AndroidManifest-readable-out.xml]

您的问题归结为如何在Android设备上运行aapt。

既然aapt是开源的,最好的解决方案就是自己构建它!

很多人已经这样做了——事实上,Play Store中也有这样的例子。看见http://talc1.loria.fr/users/cerisara/posts/buildandroid/有关如何使用从AIDE应用程序获得的aapt的说明。在Play Store上搜索会发现许多其他Android IDE,它们也提供aapt功能。

最新更新