Access android context in ndk application

前端 未结 2 1125
甜味超标
甜味超标 2020-12-03 08:51

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 interf

2条回答
  •  Happy的楠姐
    2020-12-03 09:30

    Looks like things have changes recently and the solution above and few others posted on other SO posts didn't work for me. After few tries I was able to make following solution work. My goal was to pass Context Object to JNI and get absolute storage path.

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

提交回复
热议问题