开发环境
SDK:
android 7.1.1
Tool:
Android studio 2.1.1
NDK
配置开发环境
设置系统NDK系统环境变量
NDK_ROOT = E:\android_sdk\ndk-bundle
PATH = %NDK_ROOT%
PATH = C:\Program Files\Java\jdk1.8.0_111\bin (如果不配置,Javah、java、javac不可用)
代码
步骤一,建立工程,声明要调用的模块libhellojni.so,用native 声明要调用的JNI的方法。
public class MainActivity extends AppCompatActivity {
private TextView text1;
private TextView text2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (TextView) findViewById(R.id.text1);
text2 = (TextView) findViewById(R.id.text2);
text1.setText("Return String is: "+returnString());
text2.setText("Return add value is : "+add(55,11));
}
static {
System.loadLibrary("hellojni");
}
private native int add(int a, int b);
private native String returnString();
}
步骤二,配置build.gradle
defaultConfig {
applicationId "com.adc.tiny4412.adc"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
ndk{
moduleName "hellojni"
}
sourceSets.main{
jni.srcDirs = []
jniLibs.srcDir "src/main/libs"
}
}
配置gradle.properties:
android.useDeprecatedNdk=true
编译 Build->Make Project
步骤三 ,生成 javah -jni com.adc.tiny4412.adc.MainActivity
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_adc_tiny4412_adc_MainActivity */
#ifndef _Included_com_adc_tiny4412_adc_MainActivity
#define _Included_com_adc_tiny4412_adc_MainActivity
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_adc_tiny4412_adc_MainActivity
* Method: add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_adc_tiny4412_adc_MainActivity_add
(JNIEnv *, jobject, jint, jint);
/*
* Class: com_adc_tiny4412_adc_MainActivity
* Method: returnString
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_adc_tiny4412_adc_MainActivity_returnString
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
在studio里面创jni文件夹
创建main.c
#include <jni.h>
/*
* Class: com_adc_tiny4412_adc_MainActivity
* Method: add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_adc_tiny4412_adc_MainActivity_add
(JNIEnv *env, jobject jobj, jint a, jint b){
return a+b;
}
/*
* Class: com_adc_tiny4412_adc_MainActivity
* Method: returnString
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_adc_tiny4412_adc_MainActivity_returnString
(JNIEnv *env, jobject jobj){
return (*env)->NewStringUTF(env,"Hi man,I come from JNI!");
}
添加脚本文件Android.mk
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := hellojni
LOCAL_SRC_FILES := main.c
include $(BUILD_SHARED_LIBRARY)