先说问题
用最新的android studio 2.1预览版,新建android项目,然后照网上的例子添加jni目录、c文件、编译。。。出错了。
错误如下:Error:(12, 0) Error: NDK integration is deprecated in the current plugin.
Consider trying the new experimental plugin.
For details, see http://tools.android.com/tech-docs/new-build-system/gradle-experimental.
Set "android.useDeprecatedNdk=true" in gradle.properties to continue using the current NDK integration.
网上也有解决办法,按照提示设置android.useDeprecatedNdk=true即可。但我总觉得有些不靠谱呢,deprecated这个单词我还是有点熟悉的。所以有了下文
提示的那个连接http://tools.android.com/tech-docs/new-build-system/gradle-experimental,我比较好奇,说实话以前也看过,但一看是全英文的,知难而退了。。。。最近没什么事就想趁着这几个月把ndk这块花时间好好琢磨琢磨,所以今天终于下定决心进去看看。
看了介绍大概明白了什么意思:现在有新的gradle插件(注意是插件)正处于实验性阶段,架构相比之前的区别也较大,相当于重构了吧。(本人英文也是只过了四级而已,要是有解释错的地方,望大家见谅啊)所以这里我就按照说明使用测试插件自己尝试写了一个可编译的demo。
直接上代码吧,项目的build.gradle要改一处:classpath 'com.android.tools.build:gradle-experimental:0.7.0-alpha4' ,新建项目的时候插件默认是gradle:2.1.0-alpha4
app下面的build.gradle如下
<span style="font-size:18px;">apply plugin: 'com.android.model.application' //model
model {
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
ndk {
moduleName "JniUtils" //so模块名
ldLibs.addAll(["log", "android", "EGL", "GLESv1_CM"])
}
defaultConfig {
applicationId "com.example.wg.myapplication2"
minSdkVersion.apiLevel 16 //.apiLevel
targetSdkVersion.apiLevel 23
versionCode 1
versionName "1.0"
buildConfigFields { //这个没明白
create() {
type "int"
name "VALUE"
value "1"
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles.add(file("proguard-rules.pro"))
signingConfig = $("android.signingConfigs.myConfig") //引用的是后面的配置
debuggable true
}
debug {
ndk {
debuggable true
}
}
}
productFlavors {
create("flavor1") {
applicationId "com.example.wg.myapplication2"
}
create("arm") {//这里可以多写几个的,我图简单就几个架构的so写到一起了
ndk {
// You can customize the NDK configurations for each
// productFlavors and buildTypes.
abiFilters.add("armeabi-v7a")
abiFilters.add("armeabi")
abiFilters.add("x86")
abiFilters.add("mips")
}
}
create("fat") {
// If ndk.abiFilters is not configured, the application
// compile and package all suppported ABI.
}
}
// Configures source set directory.
sources {
main {
jni {
source {
include "someFile.txt" // This is ignored.
exclude "**/excludeThisFile.c"
}
}
java {
source {
srcDir "src"
}
}
}
}
}
//配置签名
android.signingConfigs {
create("myConfig") {
storeFile "/path/to/debug.keystore"
storePassword "android"
keyAlias "androiddebugkey"
keyPassword "android"
storeType "jks"
}
}
}
</span><span style="font-size:14px;">
</span><span style="font-size:18px;">dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.2.1'
// testCompile 'junit:junit:4.12' //单元测试有问题</span><span style="font-size:14px;">
}</span>
其实时候回想起来感觉也没什么难度,我就是把说明页面一些代码复制过来,替换一些字段即可。
但此次实验过程也有个问题是我没有解决的:
单元测试问题,android studio 默认生成了单元测试的类,但是我按照说明改写了build.gradle之后编译的时候就提示 org.junit 找不到。查了好久没找到原因,我按Ctrl在测试类里面可以正常跳转到源码,而且编译器没提示错误。只有编译的时候才报错。无奈之下只能将单元测试去掉了。
虽然这个插件只是测试版本,语法以后可能还会变,但既然官方推荐我们尝试,还是看看为妙