cpp*_*dev 6 android android-ndk
有没有什么方法可以在我的ndk appliation中传递/获取android上下文的对象.我想SharedPreferences通过jni接口在我的ndk应用程序中使用.要获得一个实例SharedPreferences对象,我需要调用getSharedPreferences()的Context对象.但我无法访问上下文对象.
要么
如何从NDK读取和写入xml文件?
任何指针将不胜感激.
你不需要做什么特别的事情,就像常规的JNI机制一样.您需要获取指向上下文对象的指针,然后检索要调用的方法ID,然后使用所需的args调用它.
当然,用语言来说听起来非常简单,但在代码中,由于所有的检查和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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我只是从内存中编写代码,所以期望不开箱即用.
看起来事情最近发生了变化,上面的解决方案和其他发布在其他 SO 帖子上的其他解决方案对我不起作用。经过几次尝试,我能够使以下解决方案发挥作用。我的目标是将 Context Object 传递给 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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9469 次 |
| 最近记录: |