Access android context in ndk application

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.

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

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.

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

eg:

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

Note that i just wrote the code from memory so expect not to work out of the box.

Leave a Comment