Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

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 != "") {

}
question from:https://stackoverflow.com/questions/65847581/how-to-read-shared-preferences-from-android-ndk-c-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...