Search code examples
androidbuildapkassets

How to automatically put the APK into the asset after the build by android gradle script


I'm using DexClassLoader for dynamic loading class, and now, I need to copy APK file into the asset folder every time. is there any way to add automatically to android gradle script Thanks


Solution

  • You can do that using a python, also make sure you already installed the python before doing this.

    Create a python file in your root project.

    build.py

    import subprocess
    import shutil
    import os
    import sys
    
    # Call this function to build the apk via gradle.
    def build_cmd():
    
        # This will build your debug apk.
        buildProject = "gradlew.bat clean --profile --recompile-scripts --offline --rerun-tasks assembleDebug";
    
        # If you want to build a release apk use this instead.
        # buildProject = "gradlew.bat clean --profile --recompile-scripts --offline --rerun-tasks assembleRelease -Pandroid.injected.signing.store.file=" + os.path.abspath("store_key.jks") + " -Pandroid.injected.signing.store.password=pass123 -Pandroid.injected.signing.key.alias=key_alias -Pandroid.injected.signing.key.password=pass123"
    
        # As of Python 3 use run() instead of call() function
        # https://docs.python.org/3/library/subprocess.html#older-high-level-api
        subprocess.run(buildProject, shell=True)
    
    # Call this function to move the builded apk to your desire directory.
    def moveDir():
        # Get the generated apk
        apk_path = "./app/build/outputs/apk/debug/app-debug.apk"
    
        # apk will rename and move to asset directory
        shutil.move(apk_path, "./app/src/main/assets/app-debug.apk")
    
    
    if __name__ == '__main__':
    
        build_cmd()
        moveDir()
    

    Then run the build.py in the terminal

    python build.py

    and wait until the gradle task finish.

    EDIT:

    Because some members don't have python environment on this project instead of using a script in python try to add some task in your app/build.gradle

    android {
    
        // Some stuffs of yours....
    
        task copyAPKtoAsset(type: Copy) {
            from "/build/outputs/apk/debug/app-debug.apk", "/build/outputs/apk/release/app-release.apk"
            into "/src/main/assets/"
        }
    
        afterEvaluate {
            packageDebug.finalizedBy(copyAPKtoAsset)
        }
    }
    

    Build your project and check your assets directory after.