我试图从本机代码调用System.getProperty(String)。但我尝试在Android 4.1.2上运行时遇到此错误:
JNI ERROR: (app bug): accessed stale local reference ......... (index .... in a table of size 0)
源代码如下:
JNIEXPORT jstring JNICALL Java_org_morphone_sense_device_DeviceSense_getArchNative
(JNIEnv *pEnv, jobject pObj) {
jclass SCls = (*pEnv)->FindClass(pEnv, "java/lang/System");
if (!SCls)
return NULL;
jmethodID getPropertyMID = (*pEnv)->GetStaticMethodID(pEnv, SCls, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
jobject property = (*pEnv)->CallStaticObjectMethod(pEnv, SCls, getPropertyMID, "os.version");
}
任何人都知道如何解决此错误?
答案 0 :(得分:2)
我发现了问题。我不需要将字符串传递给CallStaticObjectMethod,而是需要构造一个jstring实例,然后传递它。工作代码应为:
JNIEXPORT jstring JNICALL Java_org_morphone_sense_device_DeviceSense_getArchNative
(JNIEnv *pEnv, jobject pObj) {
jclass SystemCls = (*pEnv)->FindClass(pEnv, "java/lang/System");
jstring propertyName = (*pEnv)->NewStringUTF(pEnv, "os.arch");
jmethodID getPropertyMID = (*pEnv)->GetStaticMethodID(pEnv, SystemCls, "getProperty", "(Ljava/lang/String;)Ljava/lang/String;");
jstring property = (*pEnv)->CallStaticObjectMethod(pEnv, SystemCls, getPropertyMID, propertyName);
if (property!=NULL) {
__android_log_print(ANDROID_LOG_INFO, "Morphone", "Got property");
return property;
}
else {
__android_log_print(ANDROID_LOG_INFO, "Morphone", "Error: Cannot get property");
return "";
}
}
答案 1 :(得分:1)
更改
public native String getArchNative();
到
public String getArchNative()
{
return System.getProperty("os.version");
}
并抛弃JNI代码。不要为自己创建工作,也不要为需要维护的额外源文件创建工作。
如果在此阶段可以,我也会从方法名称中删除“Native”。