我在构建时编译了spirv着色器,并且在使用CMake构建后我需要将它们复制到APK中。我尝试使用
${CMAKE_CURRENT_BINARY_DIR}/assets
但它们最终没有出现在 apk 中。唯一有效的方法是手动复制到构建/中间体,这看起来很糟糕。有更好的办法吗?
这就是你如何在 gradle 构建系统中做到这一点。
将以下内容添加到 gradle 文件中。
运行“buildApk”任务将构建着色器,复制到资产目录,构建 apk 并检查 apk 内部着色器是否位于生成的 apk 的资产目录中。
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.util.zip.ZipFile
// Build your shader and copy it to assets folder.
tasks.register("buildShader") {
dependsOn("configureCMakeDebug")
dependsOn("buildCMakeDebug")
doLast {
val shaderName = "libhello.so"
val shader = project.fileTree("${project.buildDir}/intermediates/cxx/Debug/") {
include("**/$shaderName")
}.files.firstOrNull()
if (shader != null) {
val assetsShader = File("${project.projectDir}/src/main/assets/$shaderName")
Files.move(shader.toPath(), assetsShader.toPath(), StandardCopyOption.REPLACE_EXISTING)
}
}
}
// Once shader is copied build apk.
tasks.register("buildApk") {
dependsOn("buildShader")
dependsOn("assembleDebug")
doLast {
printAssetsDirContents()
}
}
// Once apk is built, unzip and print contents of apk's assets folder.
fun printAssetsDirContents() {
val apkFile = File("${project.buildDir}/outputs/apk/debug/app-debug.apk")
val destinationDir = File("${project.buildDir}/outputs/apk/debug/unzipped_assets")
destinationDir.mkdirs()
ZipFile(apkFile).use { zip ->
zip.entries().asSequence().forEach { entry ->
if (entry.name.startsWith("assets/")) {
zip.getInputStream(entry).use { input ->
File(destinationDir, entry.name.substringAfter("assets/")).outputStream().use { output ->
input.copyTo(output)
}
}
}
}
}
println("Files in assets folder:")
destinationDir.listFiles()?.forEach {
println(it.name)
}
}