Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android/Gradle: Add an asset after the compile phase

Tags:

android

gradle

I have a task that generates a metadata file based off the compiled classes in an Android Gradle build. I can get it to run by executing it after the compile task:

android.applicationVariants.all { variant ->
    def variantName = variant.name.capitalize()
    def compileSourcesTaskName = "compile${variantName}Sources"
    def compileSourcesTask = project.tasks.findByName(compileSourcesTaskName)
    compileSourcesTask.finalizedBy "myTaskThatGeneratesAssets"
}

Unfortunately, Android has already processed the assets at this point. The new file won't get included in the assembled APK.

An answer to a similar question suggests calling aapt add to add the file to the APK before alignment/signing. This seems like it could work, but the post doesn't go into implementation details. The code to call aapt in the Android Gradle plugin looks fairly complicated for a build script, and I'm not sure how to get access to the IAndroidTarget it references.

I'd appreciate suggestions on how to implement this, or any other solutions!

like image 433
kvance Avatar asked Oct 29 '25 09:10

kvance


1 Answers

Okay, here's what I ended up with. It makes two assumptions that may break on later versions of the android gradle plugin (I'm using 1.3.0):

  1. The path to the platform tools is ${android.getSdkDirectory().getAbsolutePath()}/build-tools/${android.buildToolsVersion}/
  2. The path to the intermediate (resources) APK is ${buildDir}/intermediates/res/resources-${variant.baseName}.ap_

So long as those are true, this should generate a task to add the new asset file using aapt after the resources APK has already been built:

def overlayDir = ... // path to a resources overlay directory that contains "assets/my.json"
def addMyAssetTaskName = "add${variantName}MyAsset"
task "${addMyAssetTaskName}" (type: Exec) {
    dependsOn myTaskThatGeneratesAssets
    workingDir overlayDir
    def aaptCommand = "${android.getSdkDirectory().getAbsolutePath()}/build-tools/${android.buildToolsVersion}/aapt"
    def apkPath = "${buildDir}/intermediates/res/resources-${variant.baseName}.ap_"
    commandLine aaptCommand, 'add', apkPath, "assets/my.json"
}

Then I use finalizedBy like in the question above to addMyAssetTaskName.

like image 68
kvance Avatar answered Oct 31 '25 09:10

kvance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!