1.准备工作:
在app/src/main/目录下创建jni目录,并新建一个.c文件并编写要生成so库的函数。
main.c
#include <jni.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
JNIEXPORT jstring JNICALL native_OutHelloWorld(JNIEnv *env, jobject obj){
return (*env)->NewStringUTF(env,"Hello World");
}
static JNINativeMethod gMethods[] = {
{"OutHelloWorld","()Ljava/lang/String;",(void*)native_OutHelloWorld},
};
//注册native方法到java中
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = (*env)->FindClass(env, className);
if (clazz == NULL) {
return JNI_FALSE;
}
if ((*env)->RegisterNatives(env, clazz, gMethods,numMethods) < 0){
return JNI_FALSE;
}
return JNI_TRUE;
}
int register_ndk_load(JNIEnv *env)
{
return registerNativeMethods(env, "qumy/com/jnitest3/MainActivity",
gMethods,sizeof(gMethods) / sizeof(gMethods[0]));
//NELEM(gMethods));
}
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv *env = NULL;
jint result = -1;
if((*vm)->GetEnv(vm, (void**) &env, JNI_VERSION_1_4) != JNI_OK) {
return result;
}
register_ndk_load(env);
// 返回jni的版本
return JNI_VERSION_1_4;
}
在app/目录下的build.gradle中加入ndk节点,
在local.properties中加入androi.useDeprecatedNdk=true,
执行Build->Make Project,在app/build/intermediates/ndk/debug/目录下生成.so库,
在MainActivity.java中调用so库中的函数:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private String TAG="MainActivity";
static {
System.loadLibrary("JniTest3");
}
private native String OutHelloWorld();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG,OutHelloWorld());//调用库中的函数,结果打印在Log中
}
}
结果如图: