1、创建com_wq_demo_test.h头文件
#include <jni.h>
#ifndef _Included_com_zqc_log_QcLog
#define _Included_com_zqc_log_QcLog
#ifdef __cplusplus
extern "C" {
#endif
JNIEXPORT void JNICALL Java_com_wq_demo_test_init
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
2、创建一个test.cpp文件
#include <utils/Log.h>
#define LOG_TAG "Demo"
#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<errno.h>
#include<unistd.h>
#include<sys/ioctl.h>
#include<jni.h> // 一定要包含此文件
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include <android/log.h>
#define LOGI(fmt, args...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, fmt, ##args)
#define LOGD(fmt, args...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, fmt, ##args)
#define LOGE(fmt, args...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, fmt, ##args)
#include <com_wq_demo_test.h>
JNIEXPORT void JNICALL Java_com_com_wq_demo_test_init(JNIEnv* env, jobject obj){
LOGI("Java_com_com_wq_demo_test_init()");
}
JNIEXPORT jint JNICALL JNI_OnLoad (JavaVM* vm,void* reserved){
ALOGD(" JNI_OnLoad enter");
JNIEnv *env = NULL;
if (vm->GetEnv ((void **) &env, JNI_VERSION_1_6)) {
ALOGE(" JNI_OnLoad err 1");
return JNI_ERR;
}
ALOGD(" JNI_OnLoad end");
return JNI_VERSION_1_6;
}
3、Android.mk文件编写
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := test
LOCAL_SRC_FILES := test.cpp
LOCAL_SHARED_LIBRARIES := \
libutils \
liblog
LOCAL_MODULE_TAGS := optional
include $(BUILD_SHARED_LIBRARY)
4、在应用层调用native方法
public class test {
private static test mtest = null;
static {
System.loadLibrary("test ");
}
private test () {
}
public static test getInstance() {
if (null == mtest ) {
mtest = new test ();
}
return mtest ;
}
public native void init();
}
备注:以上编写的动态库,应用必须要在系统签名下才能使用so库,如果我们直接用AS编译apk在机器运行会报错,报错如下所示
java.lang.UnsatisfiedLinkError: dlopen failed: library "/system/lib/libqc_log.so" needed or dlopened by "/system/lib/libnativeloader.so" is not accessible for the namespace "classloader-namespace"