简体   繁体   中英

How to read shared preferences from Android NDK C++ code?

I'd like to read shared preferences from C++ code directly. Is that possible?

Any piece of code for that? Thanks.

Here's what I would transcript to C++:

val sharedPref = applicationContext.getSharedPreferences("OF_IR", MODE_PRIVATE)
val paramFromPref = sharedPref.getString("parameter", "")
if (paramFromPref != "") {

}

You can call Kotlin function from JNI easily. Here is JNI Docs.

https://docs.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

You can find method for FindClass, GetMethodId, CallVoidMethod, etc.

Here is example for read sharedpreferences.

jclass jcContext = env->FindClass("android/content/Context");
jclass jcSharedPreferences = env->FindClass("android/content/SharedPreferences");

if(jcContext==nullptr || jcSharedPreferences== nullptr){
    __android_log_print(ANDROID_LOG_DEBUG, "SharedPreferences","Cannot find classes");
}

jmGetString=env->GetMethodID(jcSharedPreferences,"getString","(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
jmethodID jmGetSharedPreferences=env->GetMethodID(jcContext,"getSharedPreferences","(Ljava/lang/String;I)Landroid/content/SharedPreferences;");
joSharedPreferences=env->CallObjectMethod(androidContext,jmGetSharedPreferences,env->NewStringUTF(name),MODE_PRIVATE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM