【问题标题】:How to read shared preferences from Android NDK C++ code?如何从 Android NDK C++ 代码中读取共享首选项?
【发布时间】:2021-01-22 15:02:52
【问题描述】:

我想直接从 C++ 代码中读取共享首选项。这可能吗?

有任何代码吗?谢谢。

这是我要转录到 C++ 的内容:

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

}

【问题讨论】:

  • 当然可以,但不推荐。原生代码应该做原生工作,让 Android 在 Android 代码中工作。无论如何,您可以像往常一样通过 JNI 进行操作。 env->FindClass("android/content/SharedPreferences")env->GetMethodID(cls, "getSharedPreferences", "(Ljava/lang/String;I)Landroid/content/SharedPreferences;");env->CallObjectMethod(...)

标签: android c++ kotlin android-ndk sharedpreferences


【解决方案1】:

您可以轻松地从 JNI 调用 Kotlin 函数。 这是 JNI 文档。

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

您可以找到 FindClass、GetMethodId、CallVoidMethod 等的方法。

这是读取共享首选项的示例。

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

【讨论】:

  • 好的,谢谢,我会尽快尝试,但这必须在 C++ 类(而不是 JNI 代码)中工作...
  • 如何获取androidContext?
  • 我会试试...谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 2015-07-20
  • 2012-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多