- 配置Android Studio;
File -> Settings -> Tools -> External Tools点击加号框如下图:
配置javah 、ndk-build、ndk-build clean这三个命令
Program: $JDKPath$/bin/javah
Parameters: -classpath $Classpath$ -v -jni $FileClass$
Working directory: $SourcepathEntry$\..\jni
Program: D:\java\androidstudio\sdk\ndk-bundle\ndk-build.cmd
Parameters:
Working directory: $ProjectFileDir$\app\src\main
Program: D:\java\androidstudio\sdk\ndk-bundle\ndk-build.cmd
Parameters: clean
Working directory: $ProjectFileDir$\app\src\main
- 使用javah 、ndk-build、ndk-build clean这三个命令位置
- 配置完成,我们开始新建工程JNI,然后新建jni目录
- 修改app下的build.gradle文件, 如下图
android {
...
defaultConfig {
...
ndk{
moduleName "test"
}
sourceSets {
main {
jni.srcDirs = []
jniLibs.srcDirs = ['libs']
}
}
}
buildTypes {
...
}
}
- 修改JNI下的gradle.properties文件(如果没有此文件,自己新建一个),如下图
android.useDeprecatedNdk=true
- 新建Test.java
public class Test {
static {
System.loadLibrary("Test");
}
public native String getString();
}
注:先build下整个工程,然后执行第7步
- 开始创建头文件,操作如下图(注意在Test.java文件上点击右键)
- 执行完成后jni目录下就创建了com_mazaiting_jni_Test.h文件,然后我们在jni目录下编写 Test.cpp、Android.mk、Application.mk这三个文件,代码如下:
com_mazaiting_jni_Test.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_mazaiting_jni_Test */
#ifndef _Included_com_mazaiting_jni_Test
#define _Included_com_mazaiting_jni_Test
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_mazaiting_jni_Test
* Method: getString
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_mazaiting_jni_Test_getString
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
Test.cpp
//
// Created by Administrator on 2017/10/30.
//
#include "com_mazaiting_jni_Test.h"
JNIEXPORT jstring JNICALL Java_com_mazaiting_jni_Test_getString
(JNIEnv *env, jobject){
return (*env).NewStringUTF("This is test jni!");
}
Applicaition.mk
APP_MODULES := Test
APP_ABI := all
Android.mk
具体解释请查看Android .mk文件语法规范
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := Test
LOCAL_SRC_FILES := Test.cpp
include $(BUILD_SHARED_LIBRARY)
- 执行ndk-build,请看下图:(注意在jni目录上点击右键)
- 得到.so文件
- 在程序中应用
public class MainActivity extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) this.findViewById(R.id.textView);
textView.setText(new Test().getString());
}
}
-
程序运行结果