我不知道为什么调用本地方法会抛出异常。
native 代码:
JNIEXPORT jstring JNICALL Java_org_amk_lockscreen_JNIActivity_getPackege(JNIEnv *env,jclass cls,jobject context){
jclass Context_class = (*env).FindClass("android/content/Context");
jmethodID midGetPackageName = (*env).GetMethodID(Context_class, "getPackageName", "(V)Ljava/lang/String;");
if(midGetPackageName==0){
return (*env).NewStringUTF("Not Found Method");
}
else{
jobject packageName=(*env).CallObjectMethod( context, midGetPackageName);
return (jstring)packageName;
}
}
和我的java代码:
public class JNIActivity extends Activity {
static {
System.loadLibrary("myjni"); // "myjni.dll" in Windows, "libmyjni.so" in Unixes
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jni);
TextView txt = (TextView) findViewById(R.id.txtMessage);
try {
txt.setText(getPackege(getApplicationContext()));
} catch (Exception exp) {
txt.setText(exp.getMessage());
}
}
public native String getMessage();
public native String getPackege(Context con);
}
但是当运行这个时,它会抛出异常:
JNI DETECTED ERROR IN APPLICATION: JNI NewStringUTF called with pending exception 'java.lang.NoSuchMethodError' thrown in java.lang.String org.amk.lockscreen.JNIActivity.getPackege(android.content.Context):-2
in call to NewStringUTF
from java.lang.String org.amk.lockscreen.JNIActivity.getPackege(android.content.Context)
我测试了不同的方法签名,例如:
(Ljava/lang/Void;)Ljava/lang/String;
(V;)Ljava/lang/String;
但它再次抛出异常。
我哪里做错了?
最佳答案
GetMethodID 引发异常。您不会检查是否使用 env->ExceptionCheck(env) 引发了异常,然后使用 ExceptionClear() 清除它或立即从函数返回以便 JVM 处理它。请在此处查看有关 getMethodId 的 Oracle 文档:http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html
例如(来自 http://www.ibm.com/developerworks/library/j-jni/ :) findClass、GetStaticMethodID 和 CallStaticVoidMethod 调用都生成类似于 GetMethodID 的异常。
int val=1;
jmethodID method;
jclass cls;
cls = (*env)->FindClass(env, "com/ibm/example/TestClass");
if ((*env)->ExceptionCheck(env)) {
return ERR_FIND_CLASS_FAILED;
}
method = (*env)->GetStaticMethodID(env, cls, "setInfo", "(I)V");
if ((*env)->ExceptionCheck(env)) {
return ERR_GET_STATIC_METHOD_FAILED;
}
(*env)->CallStaticVoidMethod(env, cls, method,val);
if ((*env)->ExceptionCheck(env)) {
return ERR_CALL_STATIC_METHOD_FAILED;
}
关于java - JNI NewStringUTF 调用时出现未决异常 'java.lang.NoSuchMethodError',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33674631/