Android Studio编译NDK工程
由于现在的开发都是基于AS的,但是当前AS对NDK的支持还不是特别完善,再切换ADT略显别扭,简单根据NDK文档写了一个Gradle脚本,来调用NDK ENV来编译。
目前的脚本仅能实现对*.c的编译,对NativeActivity的支持还不是特别完善。
主要分为3个步骤:
1)NDK编译链环境检查
2)编译
3)迁移编译后so文件、清理文件夹
//新建NDK compile任务
task compileNDK << {
// TAG
String TAG = ":" + project.getProject().name + ":ndk:"
// Check NDK environment
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
def ndkDir = properties.getProperty('ndk.dir')
if (ndkDir == null) {
System.err.println("ndk not found,please set (ndk dir) in local.properties")
System.exit(-1)
} else {
println TAG + ndkDir
// NDK build command
String NDK_CMD = ndkDir + "/ndk-build"
// NDK target project path
def env = ["NDK_PROJECT_PATH=${project.getProject().getProjectDir().getAbsolutePath()}" + "/src/main/"]
def moduleSrcPath = project.getProject().getProjectDir().getAbsolutePath() + "/src/main"
println TAG + "start compiling"
Process p = NDK_CMD.execute(env, null)
println TAG + "${p.text}"
if (p.exitValue() != 0) {
System.err.println TAG + "interrupted"
System.exit(-1)
} else {
// delete obj folder
def obj = new File(moduleSrcPath + "/obj/")
if (obj.deleteDir()) {
println TAG + "delete obj folder"
} else {
println TAG + "can't delete obj folder,please manual delete it"
}
File soFolder = new File(moduleSrcPath + "/libs")
//clear jniLibs
File jniLibFolder = new File(moduleSrcPath + "/jniLibs")
deleteFile(jniLibFolder)
jniLibFolder.mkdir()
//move path
def otherFiles = false
soFolder.eachFile {
if (!it.name.toUpperCase().endsWith(".JAR")) {
println TAG + "move so file " + it.name + " " + it.renameTo(new File(moduleSrcPath + "/jniLibs", it.name))
deleteFile(it)
} else {
otherFiles = true;
}
}
//if libs folder is null and delete it
if (!otherFiles) {
deleteFile(soFolder)
}
//
println TAG + "SUCCESS"
}
}
}
将脚本放入build.gradle的android标记内。
然后将这个任务添加到编译过程中
tasks.whenTaskAdded {
task ->
if (task.name == 'generateDebugBuildConfig') {
task.dependsOn compileNDK
}
}