kitzz
kitzz

Reputation: 41

accessing shared preferences from broadcast receiver

this is a click event from main activity. s3 is edit text value which i want to use in broadcast receiver when an incoming call arrives.

 public void clicksave(View shilpa)
 {
   SharedPreferences sharedPreferences = getSharedPreferences("my_prefs", MODE_PRIVATE);
   SharedPreferences.Editor editor = sharedPreferences.edit();
   editor.putString("message", s3);
   editor.commit();
}

This is what i am using in broadcast receiver to access the value of s3 :

String pref = PreferenceManager.getDefaultSharedPreferences(context).getString("message", "Does not exist");

but when i try to get value here ,it comes as "does not exist" instead of correct value. please tell me where am i going wrong

Upvotes: 2

Views: 4809

Answers (4)

Mike Yang
Mike Yang

Reputation: 2934

You can access your shared preference from broadcast receiver like this

@Override
public void onReceive(Context arg0, Intent arg1) {
    SharedPreferences prefs = arg0.getSharedPreferences("myPrefs", 
                                                    Context.MODE_PRIVATE);
}

NOTE

<receiver android:name="MySmsReceiver" android:process=":remote" />

If you are using android:process=":remote" then you might have to remove this. This attribute cause the receiver to run on a different/new process when it is called. But SharedPreferences is NOT supported between different processes.

As long as you are not doing big task in the receiver there isn't any issue with that.

Upvotes: 0

shreedhar bhat
shreedhar bhat

Reputation: 4825

Try this in broadcast receiver

SharedPreferences pref = context.getSharedPreferences("my_prefs", Context.MODE_PRIVATE); 

Upvotes: 0

kitzz
kitzz

Reputation: 41

finally i got solution for this

in main activity:

 SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
   Editor editor = pref.edit();
   editor.putString("message", message);
   editor.commit();

in broadcast receiver:

SharedPreferences pref = context.getSharedPreferences("MyPref", context.MODE_PRIVATE); 
        String a=pref.getString("message", null);

Upvotes: 2

Galax
Galax

Reputation: 365

Might be because you are using getDefaultSharedPreferences, try using

SharedPreferences prefs = getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
String yourString = prefs.getString("message", "Doesn't exist");

Upvotes: -1

Related Questions