我试图从jni调用java,不能正常工作,我做错了什么。
#include <jni.h>
extern "C" {
JNIEXPORT jboolean JNICALL Java_com_mycompany_myndkapp_HelloJni_stringFromJNI(JNIEnv* env, jobject thiz, jstring pkg)
{
try{
// context
jclass native_context = env->GetObjectClass(thiz);
// context.getPackageManager()
jmethodID methodID_func = env->GetMethodID(native_context, "getPackageManager", "()Landroid/content/pm/PackageManager;");
jobject package_manager = env->CallObjectMethod(thiz,methodID_func);
jclass pm_clazz = env->GetObjectClass(package_manager);
//packageManager.getPackageInfo()
jmethodID methodId_pm = env->GetMethodID(pm_clazz,"getPackageInfo","(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;");
env->CallObjectMethod(package_manager,methodId_pm,pkg,0);
} catch(...)
{
return 0;
}
return 1;
}
}
如果安装了app,则返回true但未安装app强制关闭我的应用程序。
FATAL EXCEPTION: main
06-10 11:51:19.554 3768 3768 E AndroidRuntime Process: com.mycompany.myndkapp, PID: 3768
06-10 11:51:19.554 3768 3768 E AndroidRuntime java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mycompany.myndkapp/com.mycompany.myndkapp.HelloJni}: android.content.pm.PackageManager$NameNotFoundException: com.demo.ndk2
06-10 11:51:19.554 3768 3768 E AndroidRuntime at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2455)
06-10 11:51:19.554 3768 3768 E AndroidRuntime at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2517)
06-10 11:51:19.554 3768 3768 E AndroidRuntime at android.app.ActivityThread.access$800(ActivityThread.java:162)
我如何修复并返回false应用程序未安装?
答案 0 :(得分:0)
C ++的try
/ catch
没有捕获Java异常。您需要的是ExceptionCheck
和ExceptionClear
:
env->CallObjectMethod(package_manager, methodId_pm, pkg, 0);
if (env->ExceptionCheck()) {
env->ExceptionClear();
return 0;
}
return 1;
(请注意,您应该将这些用于每个 JNI调用,这可能导致抛出Java异常)