简体   繁体   中英

How to get the sharedPreference value after reboot phone using BroadcastReceiver?

A.java : In this class shared prefreence is stored. I have using below snippet.

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(A.this);
Editor edit = prefs.edit();
edit.putString("Key1", key);
edit.putString("Key2", secret);
edit.commit();

BroadCastReceiver.java : I want to get the value of Key1, Key2 when I reboot my phone. for this I have using below snippet.

@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String a = prefs.getString("Key1", null);
    String b = prefs.getString("Key2", null);
}

Query :

Is this problem by context or not

Output :

I am getting null value. I tried this format in other Activity run fine but in broadcastReceiver got null value.

If I am chossing the wrong way than correct me ?

It looks like you might using two different Context objects. The PreferenceManager.getDefaultSharedPreferences() call returns the default SharedPreferences for the given Context.

Using the application Context for both should solve your problem. Obtain it in the activity using getApplicationContext() and in the BroadcastReceiver using context.getApplicationContext().

This article gives a great overview of Context differences.


Update: as Triode comments, it is better to use Context.getSharedPreferences() . This always returns a single instance.

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences("Name of your preference",Context.MODE_PRIVATE);

To get the Object of Shared Preference,

For example,

SharedPreferences sharedPreferences = context.getSharedPreferences(
           "Demo",
            Context.MODE_PRIVATE);
        edit.putString("Key1", key);
        edit.putString("Key2", secret);
        edit.commit();


SharedPreferences sharedPreferences = context.getSharedPreferences(
           "Demo",
            Context.MODE_PRIVATE);
    String a = prefs.getString("Key1", null);
    String b = prefs.getString("Key2", null);

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