JNI全称是Java Native Interface,就是实现java代码与本地c/c++
代码的交互
jni开发的步骤
①写java代码 声明本地方法 用到native关键字 本地方法不用去实现
②项main目录下创建jni文件夹
③在jni文件夹下创建.c文件
* 本地函数命名规则: Java_包名类名本地方法名
* JNIENV* env JNIEnv 是JniNativeInterface这个结构体的一级指针
* JniNativeInterface这个结构体定义了大量的函数指针
* env 就是结构体JniNativeInterface这个结构体的二级指针
* (*env)->调用结构体中的函数指针
* 第二个参数jobject 调用本地函数的java对象就是这个jobject
④ 导入jni.h
⑤ 修改gralde文件
⑥ 在java代码中加载动态链接库 System.loadlibrary(“动态链接库的名字”);
下面我们从代码层面看
首先在main下创建一个jni文件夹,里面写一个hello.c的文件
#include <stdlib.h>
#include <stdio.h>
#include <jni.h>
//jstring
//Java_com_example_hellojni_HelloJni_stringFromJNI( JNIEnv* env,
// jobject thiz )
//JNIEnv* env 是结构体JNINativeInterface 的二级指针
// JNIEnv 是结构体JNINativeInterface 的一级指针
// JNINativeInterface结构体中定义了大量的函数指针 这些函数指针在jni开发中很常用
// (*env)->
//jobject 调用本地函数的java对象 在这个例子中 就是MainActivity的实例
//c本地函数命名规则 Java_包名_类名_本地方法名
//jstring (*NewStringUTF)(JNIEnv*, const char*);
jstring Java_com_mengxin_jnihelloworld_MainActivity_hello_1FromC(JNIEnv* env,jobject thiz){
char* cstr = "hello from c123!";
return (*env)->NewStringUTF(env,cstr);
}
然后看MainActivity
public class MainActivity extends Activity {
static{
System.loadLibrary("hello");
}
public native String hello_FromC();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View v){
//System.loadLibrary("hello");
String result = hello_FromC();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="调用C函数" />
</LinearLayout>
最后修改build.gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24.0.1"
defaultConfig {
applicationId "com.mengxin.jnihelloworld"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
ndk {
moduleName "hello" // <-- This is the name of my C++ module!
}
}
productFlavors {
x86 {
ndk {
abiFilter "x86"
}
}
arm {
ndk {
abiFilter "armeabi-v7a"
}
}
mips {
ndk {
abiFilter "mips"
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:24.2.0'
}
参考文献:
http://www.cnblogs.com/flyme/p/4431762.html
http://blog.csdn.net/u012341163/article/details/51065745
http://blog.csdn.net/silver_R/article/details/48457077