JNI是Java Native Interface的缩写,它提供了若干的API实现了Java和其他语言的通信(主要是C&C++)
下边以一个示例说明:
结构
JNIHelloworld
|-- jni_c
|-- helloworld_jni.cpp
|-- Android.mk
|-- src
|-- com.example.helloworld
|-- jni_java
|-- HelloWorld.java
|-- ManiActivity.java
|-- res
|-- Android.mk
|-- AndroidManifest.xml
上述为 代码结构,主要文件已由红色标注
先看 ManiActivity.java 程序入口代码
package com.example.helloworld;
import com.example.helloworld.jni_java.HelloWorld;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.hello_world);
int text = HelloWorld.getHelloWorld();
textView.setText(text+"");
}
}
该程序调用了 HelloWorld的 getHelloWorld()方法, HellowWorld代码如下
package com.example.helloworld.jni_java;
public class HelloWorld {
static{
System.loadLibrary("helloworldjni");
}
public static native int getHelloWorld();
}
改类 加载了一个 helloworldjni 库 并且声明了一个 getHelloWorld本地方法。本地方法实现是在cpp代码中实现。
实现方法如下:
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <utils/misc.h>
#include <utils/Log.h>
#include "jni.h"
#include "JNIHelp.h"
static jint getHelloWorld(JNIEnv *env, jobject clazz) {
return 1;
}
// --------------------------------------------------------------------------
static JNINativeMethod gMethods[] = {
{"getHelloWorld", "()I", (void*)getHelloWorld},
};
static const char *classPathName = "com/example/helloworld/jni_java/HelloWorld";
static int registerNatives(JNIEnv* env){
jclass clazz;
clazz = env->FindClass(classPathName);
if(clazz == NULL){
return JNI_FALSE;
}
if(env->RegisterNatives(clazz,gMethods,sizeof(gMethods)/sizeof(gMethods[0]))<0){
return JNI_FALSE;
}
return JNI_TRUE;
}
jint JNI_OnLoad(JavaVM* vm,void* reserved){
jint result = -1;
JNIEnv* env = NULL;
if(vm->GetEnv((void**)&env,JNI_VERSION_1_4) != JNI_OK){
goto bail;
}
if(registerNatives(env) != JNI_TRUE){
goto bail;
}
result = JNI_VERSION_1_4;
bail:
return result;
}
jni_c 目录下的Android.mk 文件配置如下
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_SHARED_LIBRARIES += liblog libnativehelper
LOCAL_PRELINK_MODULE := false
LOCAL_C_INCLUDES := $(JNI_H_INCLUDE)
LOCAL_SRC_FILES := \
helloworld_jni.cpp
LOCAL_MODULE := libhelloworldjni
include $(BUILD_SHARED_LIBRARY)
LOCAL_MODULE 生成lib库文件 libhelloworldjni对应Java中的 helloworldjni
如上为一个JNI的基本架构。关键代码已由不同颜色标出。
附类型对应表
JAVA类型 | 本地类型 | 对应字母 |
---|---|---|
boolean | jboolean | Z |
byte | jbyte | B |
char | jchar | C |
short | jshort | S |
int | jint | I |
long | jlong | J |
float | jfloat | F |
double | jdouble | D |
object | jobject | L |
void | void | V |