问题描述
我需要用JNI代码实现的异常处理。我不擅长jni,找不到任何好的榜样。因此,请为此提供完整的示例。
I need an exception handling implemented in JNI code. I am not good at jni and can't find any good example. So, please provide full example for this.
这就是我在做什么:
jint JNI_OnLoad(JavaVM* vm, void* reserved) {
jint result = -1;
g_JavaVM = vm;
if (vm->GetEnv((void **) &envLocal, JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
jclass clazz;
**clazz = envLocal->FindClass("com/graphics/myclass/MyClass");**
if (clazz == NULL)
__android_log_print(ANDROID_LOG_ERROR, "MyClass",
"clazz value is null");
g_clazz = (jclass) envLocal->NewGlobalRef(clazz);
// STEP 3/3 : Delete the no longer needed local reference
envLocal->DeleteLocalRef(clazz);
result = JNI_VERSION_1_6;
return result;
}
现在我需要在哪里无法使用此MyClass(因为应用程序开发人员没有相应的jar文件),则不应有任何应用崩溃。
使用System.LoadLibrary( libmyclass.so)和此 com / graphics / myclass / MyClass类加载库时,将调用JNI_OnLoad。
Now I have a need where if this MyClass is not available (because app developer does not have corresponding jar file) then, there should not be any app crash.JNI_OnLoad will be called when loading a library using System.LoadLibrary("libmyclass.so") and this "com/graphics/myclass/MyClass" class.
当前,如果此jar不包含在应用程序中,则会导致应用程序崩溃并出现以下异常
Currently, if this jar is not included in the app this causes and app to crash with below exception
F/art (14708): sart/runtime/check_jni.cc:65] JNI DETECTED ERROR IN APPLICATION: JNI NewGlobalRef called with pending exception 'java.lang.ClassNotFoundException' thrown in unknown throw location
F/art (14708): sart/runtime/check_jni.cc:65] in call to NewGlobalRef
F/art (14708): sart/runtime/check_jni.cc:65] from java.lang.String java.lang.Runtime.nativeLoad(java.lang.String, java.lang.ClassLoader, java.lang.String)
F/art (14708): sart/runtime/check_jni.cc:65] "main" prio=5 tid=1 Runnable
我需要的是由Android在某处处理的此异常,应在JNI_OnLoad中进行处理,以使应用程序不会崩溃。我不希望通过Java处理异常。
What I need is rather this exception handled by android somewhere, it should be handled in JNI_OnLoad so that app does not crash. I don't want exception handling by java.
所以我的想法是,如果我捕获到由 clazz = envLocal-> FindClass( com / graphics / systemOp / SystemOp);
so my thinking is if I catch exception thrown by " clazz = envLocal->FindClass("com/graphics/systemOp/SystemOp");" be handled in JNI_OnLoad after this.
有人可以提出一个示例(完整示例),因为我无法实现它。
Can someone suggest an example (complete one) because I can't implement it. With full source code please. Ask me if you need more information.
推荐答案
您可以在执行可能会抛出的jni操作后调用以下代码:
You can call following code after doing jni operations that may throw:
bool checkExc(JNIEnv* env) {
if(env->ExceptionCheck()) {
env->ExceptionDescribe(); // writes to logcat
env->ExceptionClear();
return true;
}
return false;
}
这篇关于Android JNI异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!