NDK

Android Studio之NDK开发

Posted by Mio4kon on 2015-09-28

Android Studio 1.3 版本开始支持了NDK开发.试用了一下发现的确方便了许多,不再需要mk文件.

准备工作

1.在SDK-Tools中安装Android-Ndk

2.修改工程目录下的build,gradle(不是Model下的文件)

1
2
3
4
dependencies {
//classpath 'com.android.tools.build:gradle:1.3.0'
classpath 'com.android.tools.build:gradle-experimental:0.2.0'
}

3.修改gradle->wrapper目录下的gradle-wrapper.properties,修改为2.5版本

1
distributionUrl=https\://services.gradle.org/distributions/gradle-2.5-all.zip

4.修改Model下的build.gradle文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
apply plugin: 'com.android.model.application'
model {
android {
compileSdkVersion = 23
buildToolsVersion = "23.0.1"
defaultConfig.with {
applicationId = "mio.kon.yyb.ndk_test"
minSdkVersion.apiLevel = 14
targetSdkVersion.apiLevel = 22
versionCode = 1
versionName = "1.0"
}
compileOptions.with {
sourceCompatibility=JavaVersion.VERSION_1_7
targetCompatibility=JavaVersion.VERSION_1_7
}
}
android.ndk {
moduleName = "jni-test"
/*
* Other ndk flags configurable here are
* cppFlags += "-fno-rtti"
* cppFlags += "-fno-exceptions"
* ldLibs = ["android", "log"]
* stl = "system"
*/
}
android.productFlavors {
// for detailed abiFilter descriptions, refer to "Supported ABIs" @
// https://developer.android.com/ndk/guides/abis.html#sa
create("arm") {
ndk.abiFilters += "armeabi"
}
create("arm7") {
ndk.abiFilters += "armeabi-v7a"
}
create("arm8") {
ndk.abiFilters += "arm64-v8a"
}
create("x86") {
ndk.abiFilters += "x86"
}
create("x86-64") {
ndk.abiFilters += "x86_64"
}
create("mips") {
ndk.abiFilters += "mips"
}
create("mips-64") {
ndk.abiFilters += "mips64"
}
// To include all cpu architectures, leaves abiFilters empty
create("all")
}
android.buildTypes {
release {
minifyEnabled = false
proguardFiles += file('proguard-rules.pro')
}
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:appcompat-v7:23.0.1'
}

JNI开发

main目录下新建jni目录

编写JNI代码

1
2
3
public native String stringFromJNI();
public native int intFromJNI();

生成c文件

编写.c文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string.h>
#include <jni.h>
JNIEXPORT jstring JNICALL
Java_mio_kon_yyb_ndk_1test_MainActivity_stringFromJNI(JNIEnv *env, jobject instance) {
return (*env)->NewStringUTF(env, "I come from jni string");
}
JNIEXPORT jint JNICALL
Java_mio_kon_yyb_ndk_1test_MainActivity_intFromJNI(JNIEnv *env, jobject instance) {
return 24;
}

导入库(应该与之前gradle配置的android.ndk下的moduleName保持一致)

1
2
3
4
static {
System.loadLibrary ("jni-test");
}
1
2
3
4
5
TextView tv = (TextView) findViewById (R.id.tv);
TextView tv2 = (TextView) findViewById (R.id.tv2);
tv.setText (stringFromJNI ());
tv2.setText ("int from jni:"+intFromJNI ());

运行结果:

最后,如果需要so文件可以在build-binaries-debug-all-obj文件下找到.

demo

参考链接