I need to instrument the dalvik bytecode of any given .apk file as part of my research and to obtain working, modified .apk with the instrumented bytecode.
I am programming in Java 1.6 under Windows 7.
Input
- The original .apk file with the original, unchanged
classes.dexdalvik bytecode. - the instrumented
classes.dexbytecode of the .apk (yes, we assume we already instrumented the bytecode).
Desired output
- The .apk file with the instrumented
classes.dexbytecode instead of the original.
Problem statement
What is the most straightforward way to obtain the desired output from Java source code?
Update Apr 12 ’16
Regarding step 2 of original answer:
The sources of current version of
ApkBuildercan be found in the official repo here and comment explaining why it should be used can be found also in the official repo.In your local Android SDK installation, the classes seem to live in
android-sdk/tools/lib/sdklib.jarOriginal answer Nov 30 ’12
Step 1: remove the original classes.dex
To rebuild the .apk with custom
classes.dexfile first we need to delete the originalclasses.dexfile from it. This can be easily done using the theaapt.exetool from Android SDK install dir, e.g. located here:c:\Program Files (x86)\Android\android-sdk\platform-tools\aapt.exeThe command:
will remove the file.
Step 2: rebuild the .apk
There is a lot of confusion about building .apks as the
(...)\android-sdk\tools\apkbuilder.batscript is deprecated. See this discussion for details.Behind the scenes the script calls
ApkBuilderMainwhich calls non-deprecatedApkBuilder.Based on no longer available unofficial sources, I came up with the following code snippet: