有没有办法在我的NDK应用程序中传递/获取Android上下文对象。我想通过JNI接口在我的NDK应用程序中使用SharedPreferences。为了获取SharedPreferences对象的实例,我需要在Context对象上调用getSharedPreferences()方法。但是我无法访问该上下文对象。
或者
我该如何从NDK中读写XML文件?
欢迎提供任何指导。
或者
我该如何从NDK中读写XML文件?
欢迎提供任何指导。
你不需要做什么特别的事情,它就像普通的JNI机制一样。你需要获取上下文对象的指针,然后检索你想要调用的方法ID,最后使用你想要的参数来调用它。
当然,听起来很简单,但在代码中,由于所有的检查和JNI调用,它变得非常混乱。
因此,在我看来,我不会尝试从本地/JNI代码实现整个东西,而是将一个帮助方法实现在Java中,它可以完成所有的工作,只需接收需要读取/写入首选项的数据即可。
这将大大简化你的本地代码,并使其更易于维护。
例如:
//Somewhere inside a function in your native code
void Java_com_example_native_MainActivity_nativeFunction(JNIEnv* env, jobject thiz)
{
jclass cls = (*env)->FindClass(env,"PreferenceHelper");
if (cls == 0) printf("Sorry, I can't find the class");
jmethodID set_preference_method_id;
if(cls != NULL)
{
set_preference_method_id = (*env)->GetStaticMethodID(env, cls, "setPreference", "(Ljava/lang/String;Ljava/lang/StringV");
if(set_preference_method_id != NULL )
{
jstring preference_name = (*env)->NewStringUTF(env, "some_preference_name");
jstring value = (*env)->NewStringUTF(env, "value_for_preference");
(*env)->CallStaticVoidMethod(env, cls, get_main_id, preference_name, value);
}
}
}
env
变量是什么?它是要在Android中传递的上下文吗? - IgorGanapolsky看起来最近事情有所改变,上面的解决方案以及其他一些SO帖子上发布的解决方案对我无效。经过几次尝试,我成功地实现了以下解决方案。我的目标是将上下文对象传递给JNI并获取绝对存储路径。
void Java_com_path_to_my_class_jniInit(JNIEnv* env, jobject thiz, jobject contextObject) {
try {
//Get Context Class descriptor
jclass contextClass = env->FindClass("android/content/Context");
//Get methodId from Context class
jmethodID getFilesDirMethodId = env->GetMethodID(contextClass,"getFilesDir","()Ljava/io/File;");
//Call method on Context object which is passed in
jobject fileObject = env->CallObjectMethod(contextObject,getFilesDirMethodId);
//Get File class descriptor
jclass fileClass = env->FindClass("java/io/File");
//Get handle to the method that is to be called
jmethodID absolutePathMethodId = env->GetMethodID(fileClass,"getAbsolutePath","()Ljava/lang/String;");
//Call the method using fileObject
jstring stringObject = (jstring)env->CallObjectMethod(fileObject,absolutePathMethodId);
}
catch(exception& ex){
JNIExceptionHelper::throwException(env, ex.what());
return;
}
}