gpt4 book ai didi

java - 安卓 : Need to create Shared Preferences object in c++ NDK and Store some Boolean value

转载 作者:可可西里 更新时间:2023-11-01 16:39:47 30 4
gpt4 key购买 nike

我是新手,不知道怎么开始,

我已经使用 Android.mk 创建了一个链接到 C++ 的项目

所以当我从 java 调用一个方法时,它应该将 boolean 值存储到我的共享首选项对象中。

这是我的 JNI 方法

extern "C"
JNIEXPORT void JNICALL
Java_com_example_sample_storeBoolean(JNIEnv *env,jobject instance){
//TODO
const char *name ="hello";
__android_log_print(ANDROID_LOG_ERROR, "TRACKERS", "***** %s *****", name);
}

我打印的正常日志现在可以正常工作了,只需要创建 sharepreference 对象并设置 boolean 值

SharedPreferences prefs = context.getSharedPreferences("myprefdata", Context.MODE_PRIVATE);

prefs.edit().putBoolean("settingnootification", true).commit();

请指导我该怎么做。谢谢

public abstract SharedPreferences getSharedPreferences(String name, int mode);

需要在c++中使用该方法

最佳答案

我刚刚在 JNI 的 MainActivity 中调用了 saveBoolean(boolean bool) 并保存了值。这是代码:MainActivity

public class MainActivity extends AppCompatActivity {

// Used to load the 'native-lib' library on application startup.
static {
System.loadLibrary("native-lib");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stringFromJNI(this);
}

/**
* A native method that is implemented by the 'native-lib' native library,
* which is packaged with this application.
*/
public native void stringFromJNI(MainActivity mainActivity);

public void saveBoolean(boolean bool){
SharedPreferences sharedPreferences = this.getSharedPreferences("Test", Context.MODE_PRIVATE);
sharedPreferences.edit().putBoolean("testBool",bool).commit();
Log.d("MainActivity","saveBoolean Called "+bool);
}

#include <jni.h>
#include <string>

extern "C"
JNIEXPORT void JNICALL
Java_com_android_techgig_sharedpref_MainActivity_stringFromJNI(JNIEnv *env,jobject obj /* this */) {

jclass cls = (env)->GetObjectClass(obj); //for getting class
jmethodID mid = (env)->GetMethodID(cls, "saveBoolean", "(Z)V"); //for getting method signature, Z for boolean
if (mid == 0)
return;
//will return 0 in case of class not found
(env)->CallVoidMethod(obj, mid, true); //now calling actual method
printf("native called");
}

这是方法签名类型

Signature   Java Type
Z boolean
B byte
C char
S short
I int
J long
F float
D double

这是探索的链接more ..

编码愉快!!!

关于java - 安卓 : Need to create Shared Preferences object in c++ NDK and Store some Boolean value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45385460/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com