在NDK的应用程序访问Android的环境应用程序、环境、NDK、Android

2023-09-13 23:50:19 作者:快乐是选择

有没有什么办法,我可以通过/获取的android背景的对象在我的NDK蒋云良。我想用共享preferences 在通过JNI接口我NDK的应用程序。要获得一个实例共享preferences 的对象,我需要调用 getShared preferences()上下文对象。但我没有访问上下文对象。

Is there any way in which I can pass/get an object of android context in my ndk appliation. I want to use SharedPreferences in my ndk application via jni interface. To get an instance of SharedPreferences object, I need to call getSharedPreferences() on Context object. But I do not have access to the context object.

我怎么能读写从NDK一个XML文件?

How can I read and write an xml file from NDK ?

任何指针将AP preciated。

Any pointers will be appreciated.

推荐答案

没有什么特别的你需要做的,它就像普通JNI机制。你需要得到一个指向上下文对象,然后检索要呼叫,然后与你想要的ARGS调用它的方法ID。

There is nothing special you have to do, it is just like regular JNI mechanism. You need to get a pointer to the context object, then retrieve the method ID you want to call and then invoke it with the args you want.

当然中的单词听起来非常简单,但在code它变得非常凌乱,因为所有的检查和JNI调用。

Of course in words it sounds super straightforward, but in code it gets really messy since the all the checks and JNI calls.

所以,在我看来,我不会试图实现从本地/ JNI code整个事情,相反,我会在Java中实现一个辅助方法,使所有的东西,只得到所需要的数据读/写的preference。

So in my opinion i will not try to implement the whole thing from native/JNI code, instead i will implement a helper method in Java that makes all the stuff and just receives the needed data to read/write the preference.

这将简化很多本机code,它会更容易维护。

That will simplify a lot your native code and it will make it easier to maintain.

例如:

//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);
        }
    }
}

请注意,我只写了从内存中code所以我们期待没有工作的开箱即用。的