Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run compiled Java code before APK packaging

My app shows a list of items created from a static XML file contained in the APK. To speed things up, my app caches a binary version of the data on the first load. The app starts around 300ms faster when it reads the cached binary data rather than the XML.

You can guess where this is going: I want to precompute the binary version when the app is built and stick that into the assets directory. I'd like to keep the XML loader because users can select other XML files and show those in the app. So I don't want to move my loader into buildSrc, or go through the effort of building a separate project for both the build scripts and app to depend on.

I've gotten gradle to run my caching code as a separate target, but I don't know which Android build task to declare a doLast on for it to happen during a normal build.

Which task should I declare the dependency on, so it's generated whenever a build runs? I've tried preBuild, packageDebug, and packageRelease.

task writeBinary() {
    doFirst {
        print("Writing binary file")
        javaexec {
            classpath += files("build/intermediates/classes/debug")
            classpath += files("build_libs/xpp3-1.1.4c.jar")
            main = "ehues.tome.loader.BinaryReaderWriter"
            args = ['src/main/assets/standard/my.xml', 'src/main/assets/standard/my.bin']
        }
    }
}
like image 295
Erigami Avatar asked Jul 13 '19 19:07

Erigami


1 Answers

This is in general a questionable approach; just don't use assets or res/raw and have your resources automatically processed by AAPT2 - instead of attempting to re-invent the wheel.

The point is, that assets and res/raw are not being processed, but only copied.

And if you really would like to create binary format, this can be done by running aapt2 or aapt2.exe. A Gradle Exec task can run a terminal command - and such task then can be added to the graph:

aapt2 compile path-to-input-files [options] -o output-directory/

However, providing proper resource XML format would cause it to handle this all by itself.

like image 63
Martin Zeitler Avatar answered Nov 08 '22 21:11

Martin Zeitler