Android 如何实现在java中调用native lib中的function. 示例代码如下:
java代码中要使用System.loadLibrary 动态加载native lib, 并声明native 函数:
package com.xxx.nfc.simserver;
public class NativeNfcHalTest {
static {
System.loadLibrary("libnfc_hal_test_jni");
}
public native void doSetProperty(String name, String value);
public void setProperty(String name, String value) {
doSetProperty(name, value);
}
}
android.mk中指明jni lib:
LOCAL_JNI_SHARED_LIBRARIES := libnfc_hal_test_jni
include $(BUILD_PACKAGE)
include $(call all-makefiles-under,$(LOCAL_PATH))
native 代码中, 要实现JNI_OnLoad函数并调用jniRegisterNativeMethods注册native function:
namespace android {
const char* gNativeNfcTestClassName =
"com/xxx/nfc/simserver/NativeNfcHalTest";
/*****************************************************************************
**
** JNI functions for android-4.0.1_r1
**
*****************************************************************************/
static JNINativeMethod gMethods[] = {
{"doSetProperty", "(Ljava/lang/String;Ljava/lang/String;)V", (void*)nfc_set_property}
};
/*******************************************************************************
**
** Function: register_com_xxx_nfc_simserver
**
** Description: Regisgter JNI functions with Java Virtual Machine.
** e: Environment of JVM.
**
** Returns: Status of registration.
**
*******************************************************************************/
int register_com_xxx_nfc_simserver_NativeNfcHalTest(JNIEnv * e) {
DLOG_IF(INFO, true) << StringPrintf("%s: enter", __func__);
return jniRegisterNativeMethods(e, gNativeNfcTestClassName, gMethods,
NELEM(gMethods));
}
}
jint JNI_OnLoad(JavaVM* jvm, void*) {
DLOG_IF(INFO, true) << StringPrintf("%s: enter", __func__);
JNIEnv* e = NULL;
LOG(INFO) << StringPrintf("NFC hal test : loading nci JNI");
// Check JNI version
if (jvm->GetEnv((void**)&e, JNI_VERSION_1_6)) return JNI_ERR;
if (android::register_com_xxx_nfc_simserver_NativeNfcHalTest(e) == -1)
return JNI_ERR;
DLOG_IF(INFO, true) << StringPrintf("%s: exit", __func__);
return JNI_VERSION_1_6;
}