Use mergeAssets to modify Android's assets files during construction

demand background

  • Recently, there is a demand. When building APK in AS, you can decide whether to encrypt a file under the assets folder according to the configuration. However, this file is often modified, so it must be kept in plain text and can be edited at any time. Encryption is only required when the build generates the apk

How to achieve

  • The best way we can solve this problem is to write a gradle script to achieve
    /**
     * 在每次构建apk时,对assets下的文件进行加密或其他处理
     */
    android.applicationVariants.all { variant ->
        //def mergeAssetsDir = variant.mergeAssets.outputDir //gradle 4.x版本以下
        def mergeAssetsDir = variant.mergeAssetsProvider.get().outputDir.get() //gradle 5.x版本以上
        def file = new File([mergeAssetsDir, "my_assets_config.txt"].join(File.separator))
        if (file.exists()) file.delete() //每次构建的时候都将需要处理的问题件删除,这样下面的mergeAssets每次才会触发
    
        variant.mergeAssets.doLast {
            if (file.exists()) {
                println("encrpty json")
                //这里可以编写自己的加密脚本,然后将内容重新写入文件
                file.write("我是加密后的内容哦")
            }
        }
    }
  • The script is actually very simple. It uses the build variant of gradle and adds its own logic processing when the mergeAssets task is executed. If processing is required for each build, you can delete the files to be processed each time, so that you can start mergeAssets task execution

  • The mergeAssets task is different under different gradle versions. Gradle5.X and above have changed, so you need to determine where the merged assets directory is based on your gradle version. This is the build directory below gradle4.x , the way to obtain the relative directory of assets is: variant.mergeAssets.outputDir

     The build directory above gradle5.X is like this, the relative directory of assets is obtained by: variant.mergeAssetsProvider.get().outputDir.get()

Guess you like

Origin blog.csdn.net/qq_19942717/article/details/125698279