Search code examples
androidgradlegroovy

Android Gradle/Groovy, how to copy files to APK


I have a bunch of files on my applications source folder that I need to package in my app's bundle. Unfortunately, I'm a Gradle/Groovy noob. My idea would be to modify the apps build.gradle to run an extra gradle file that will hook into the compilation process and add this files before the apk is signed.

For example how Sentry does it:

Ideally I would like to replicate that with something like (pseudo-code):

task copyFolder(path) {
  // copy the files from a `src` folder into the apps apk
}

preBuild.depends(copyFolder)

Edit: A more detailed explanation

This is a React Native app, so things might vary to a regular Android app but here is a more detailed explanation. My app's folder looks like this:

android // the Android app folder
src // contains JS source files
migrations
  migration1.sql
  migration2.sql

I need to package this migration sqls into the final APK so I can later access then on runtime, when the application starts.

As a reference point for iOS I automated this process by adding a build script that just calls a bash script that looks like this:

#!/bin/sh

echo "Copying prisma migration files..."

MIGRATIONS_TARGET=${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}

mkdir "$MIGRATIONS_TARGET/migrations"
cp -r ${SRCROOT}/../migrations ${MIGRATIONS_TARGET}

echo "migration files copied ✅"

So I'm basically looking for the equivalent of that. Moving the files to the resource folder is a no-go for me. This needs to be automated in a single script that hooks into some step of the build process.


Solution

  • APK is basically a zip archive, and it is possible to add any file inside it. But you will not be able to read them from your application. In order to access them, you must use res or assests directories. You can use this task to copy:

    tasks.register('copyFolder', Copy) {
        from "${SRCROOT}/../migrations"
        into "src/main/assets/migrations"
    }
    
    preBuild.dependsOn(copyFolder)
    

    And then access them as assets

    Note that relative path root is Gradle project's module's root directory, NOT React project's root.