—- 1. NDK的下载与环境配置. 首先进入as的设置,下载NDK 然后进入project structure设置路径 在local.properties里设置1
ndk.dir=/Users/wangchangqin/develop/android/sdk/ndk-bundle sdk.dir=/Users/wangchangqin/develop/android/sdk
在gradle.properties里设置1
org.gradle.jvmargs=-Xmx1536m android.useDeprecatedNdk=true
2. 新建一个实体类 1
2
3
4
5
6
public class JniTest {
static {
System.loadLibrary("wcqtest");
}
public static native String getJniString();
}
这个wcqtest需要在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
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
applicationId "com.example.wangchangqin.ndkdemo2"
minSdkVersion 23
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
ndk {
moduleName "wcqtest"
abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
//输出指定三种abi体系结构下的so库。
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12' }
3. 头文件的生成 进入java目录,make project 执行 在java目录下会生成.h头文件1
2
3
4
5
6
7
/* DO NOT EDIT THIS FILE - it is machine generated */ #include <jni.h> /* Header for class com_example_wangchangqin_ndkdemo2_JniTest */ #ifndef _Included_com_example_wangchangqin_ndkdemo2_JniTest #define _Included_com_example_wangchangqin_ndkdemo2_JniTest #ifdef __cplusplus
extern "C" {
#endif /*
* Class: com_example_wangchangqin_ndkdemo2_JniTest * Method: getJniString * Signature: ()Ljava/lang/String; */ JNIEXPORT jstring JNICALL Java_com_example_wangchangqin_ndkdemo2_JniTest_getJniString
(JNIEnv *, jclass); #ifdef __cplusplus
}
#endif #endif
4. 新建jni目录,创建c或c++文件 把生成的头文件放到jni目录,创建tmp.c文件(名字随便)1
2
3
4
#include "com_example_wangchangqin_ndkdemo2_JniTest.h" JNIEXPORT jstring JNICALL Java_com_example_wangchangqin_ndkdemo2_JniTest_getJniString
(JNIEnv *env, jclass obj){
return (*env) -> NewStringUTF(env,"hello jni");
}
5. 运行 1
2
3
4
5
6
7
8
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); Log.e("qqq",JniTest.getJniString());
}
}
成功!