Android:需要在c ++ NDK中创建共享首选项对象并存储一些布尔值

Amjad Khan 07/29/2017. 3 answers, 887 views
java android android c++ android-ndk android-ndk jni

我是新来的这个不知道如何开始这个,

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

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

这是我的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对象并设置布尔值

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

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

请指导我如何去做。 谢谢

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

需要在c ++中使用这个方法

3 Answers


vikas kumar 08/05/2017.

我从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 #include 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 

这里是链接探索更多 ..

快乐编码!


mko 07/31/2017.

我想你想从你的代码中调用Java类。 我建议从你的C ++代码中调用Java。

看看这里:

https://github.com/mkowsiak/jnicookbook/tree/master/recipeNo032

在这个例子中,你所做的是:

  • Java调用C ++
  • 根据从Java传递的信息,C ++附加到JVM
  • C ++代码从另一个类调用Java代码(在你的情况下,它将是SharedPreferences对象)

可能你会需要一些辅助类来使事情变得更简单。 例如PreferencesStorer - 您将在其中获得适当的首选项类并传递要存储的值。

看看这里:

public static int fun() {
  System.out.println("From JVM");
  return 0;
} 

这是你想调用的方法,但你希望它是:store(String value,int mode)。

在你的代码中(用Java),你需要创建这个对象并将它作为参数传递给你的C ++代码。 在C ++里面你想调用这个对象的方法。 在JVM内部,它已经存在 - 准备好被调用。

如果这不是你正在寻找的东西,我认为你需要提供一些更多的信息来使整个用例变得更加清晰。

与JNI玩得开心


Amjad Khan 09/06/2017.

我需要调用getSharedPreferences()方法,那么如何调用该方法并存储布尔值。

所以,我创建了两个简单的方法来存储和检索NDK C ++中的布尔值

MainActivity.java

public class MainActivity extends Activity {
    // Used to load the 'native-lib' library on application startup.
    static {
        System.loadLibrary("Native");
    }
    private Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity=MainActivity.this;
        setStoreBoolValues(activity, true);

        if (getStoreValues(activity))
            Log.e("Store Value", " ** true **");
        else
            Log.e("Store Value", " ** false **");
    }

    public native boolean getStoreValues(Activity activity);
    public native void setStoreBoolValues(Activity activity, boolean flag);
} 

在MainActivity中声明本地方法,也称为我的.so文件

NativeClass.Cpp

jobject mainClass;

jstring spname(JNIEnv *env) {
    return env->NewStringUTF("sharedstore");
}

jstring objectname(JNIEnv *env) {
    return env->NewStringUTF("boolvaluestore");
}

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_ebizzinfotech_amjad_contentresolverproj_MainActivity_getStoreValues(JNIEnv *env,
                                                                             jobject instance,
                                                                             jobject activity) {

    jclass spcls = env->FindClass("android/content/SharedPreferences");
    jclass contextcls = env->FindClass("android/content/Context");
    mainClass = env->NewGlobalRef(activity);
    jmethodID mid = env->GetMethodID(contextcls, "getSharedPreferences",
                                     "(Ljava/lang/String;I)Landroid/content/SharedPreferences;");
    jmethodID midbool = env->GetMethodID(spcls, "getBoolean",
                                         "(Ljava/lang/String;Z)Z");
    jobject jobjectshared = env->CallObjectMethod(mainClass, mid, spname(env), 0);
//    jobject jobjectsharededit  = env->CallObjectMethod(jobjectshared,midedit);
    jboolean jboolean1 = env->CallBooleanMethod(jobjectshared, midbool,objectname(env), JNI_FALSE);

    env->DeleteLocalRef(spcls);
    env->DeleteLocalRef(contextcls);
    return jboolean1;
}


extern "C"
JNIEXPORT void JNICALL
Java_com_ebizzinfotech_amjad_contentresolverproj_MainActivity_setStoreBoolValues(JNIEnv *env,
                                                                                 jobject instance,
                                                                                 jobject activity,
                                                                                 jboolean flag) {
    jclass spcls = env->FindClass("android/content/SharedPreferences");
    jclass speditorcls = env->FindClass("android/content/SharedPreferences$Editor");
    jclass contextcls = env->FindClass("android/content/Context");

    mainClass = env->NewGlobalRef(activity);

    jmethodID mid = env->GetMethodID(contextcls, "getSharedPreferences",
                                     "(Ljava/lang/String;I)Landroid/content/SharedPreferences;");

    jmethodID midedit = env->GetMethodID(spcls, "edit",
                                         "()Landroid/content/SharedPreferences$Editor;");

    jmethodID midputbool = env->GetMethodID(speditorcls, "putBoolean",
                                            "(Ljava/lang/String;Z)Landroid/content/SharedPreferences$Editor;");

    jmethodID midapply = env->GetMethodID(speditorcls, "apply",
                                          "()V");
    jobject jobjectshared = env->CallObjectMethod(mainClass, mid,spname(env), 0);
    jobject jobjectsharededit = env->CallObjectMethod(jobjectshared, midedit);
    env->CallVoidMethod(env->CallObjectMethod(jobjectsharededit, midputbool, objectname(env), flag),
                        midapply);
    env->DeleteLocalRef(spcls);
    env->DeleteLocalRef(contextcls);
    env->DeleteLocalRef(speditorcls);
} 

HighResolutionMusic.com - Download Hi-Res Songs

1 (G)I-DLE

POP/STARS flac

(G)I-DLE. 2018. Writer: Riot Music Team;Harloe.
2 Ariana Grande

​Thank U, Next flac

Ariana Grande. 2018. Writer: Crazy Mike;Scootie;Victoria Monét;Tayla Parx;TBHits;Ariana Grande.
3 Clean Bandit

Baby flac

Clean Bandit. 2018. Writer: Jack Patterson;Kamille;Jason Evigan;Matthew Knott;Marina;Luis Fonsi.
4 Imagine Dragons

Bad Liar flac

Imagine Dragons. 2018. Writer: Jorgen Odegard;Daniel Platzman;Ben McKee;Wayne Sermon;Aja Volkman;Dan Reynolds.
5 Halsey

Without Me flac

Halsey. 2018. Writer: Halsey;Delacey;Louis Bell;Amy Allen;Justin Timberlake;Timbaland;Scott Storch.
6 BTS

Waste It On Me flac

BTS. 2018. Writer: Steve Aoki;Jeff Halavacs;Ryan Ogren;Michael Gazzo;Nate Cyphert;Sean Foreman;RM.
7 Nicki Minaj

No Candle No Light flac

Nicki Minaj. 2018. Writer: Denisia “Blu June” Andrews;Kathryn Ostenberg;Brittany "Chi" Coney;Brian Lee;TJ Routon;Tushar Apte;ZAYN;Nicki Minaj.
8 Backstreet Boys

Chances flac

Backstreet Boys. 2018.
9 BlackPink

Kiss And Make Up flac

BlackPink. 2018. Writer: Soke;Kny Factory;Billboard;Chelcee Grimes;Teddy Park;Marc Vincent;Dua Lipa.
10 Little Mix

The Cure flac

Little Mix. 2018. Writer: Pete Kelleher;Camille Purcell;Tom Barnes;Ben Kohn.
11 Fitz And The Tantrums

HandClap flac

Fitz And The Tantrums. 2017. Writer: Fitz And The Tantrums;Eric Frederic;Sam Hollander.
12 Diplo

Close To Me flac

Diplo. 2018. Writer: Ellie Goulding;Savan Kotecha;Peter Svensson;Ilya;Swae Lee;Diplo.
13 The Chainsmokers

Beach House flac

The Chainsmokers. 2018. Writer: Andrew Taggart.
14 Bradley Cooper

Always Remember Us This Way flac

Bradley Cooper. 2018. Writer: Lady Gaga;Dave Cobb.
15 Kelly Clarkson

Never Enough flac

Kelly Clarkson. 2018. Writer: Benj Pasek;Justin Paul.
16 Lady Gaga

I'll Never Love Again flac

Lady Gaga. 2018. Writer: Benjamin Rice;Lady Gaga.
17 Frida Sundemo

Apologize flac

Frida Sundemo. 2018.
18 Little Mix

Woman Like Me flac

Little Mix. 2018. Writer: Nicki Minaj;Steve Mac;Ed Sheeran;Jess Glynne.
19 Imagine Dragons

Machine flac

Imagine Dragons. 2018. Writer: Wayne Sermon;Daniel Platzman;Dan Reynolds;Ben McKee;Alex Da Kid.
20 Billie Eilish

When The Party's Over flac

Billie Eilish. 2018. Writer: Billie Eilish;FINNEAS.

Related questions

Hot questions

Language

Popular Tags