Android8.1使用JNI編譯動態so庫

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"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章