50

In my app,i want to use Shared Preferences inside a broadcast receiver...But i cant access the getPreferences() method inside...

 SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);

I cant call with the context object...any other method???

subrussn90
  • 1,142
  • 1
  • 14
  • 27

1 Answers1

104

You can use Context from onReceive(Context arg0, Intent arg1) of BroadReceiver.

@Override
    public void onReceive(Context arg0, Intent arg1) {
        SharedPreferences prefs = arg0.getSharedPreferences("myPrefs", 
                                                        Context.MODE_PRIVATE);
}
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242
  • No, it depends on your usage. – Lalit Poptani Jan 31 '12 at 06:10
  • @subrussn90 there is, security issue. – Yousha Aleayoub Oct 30 '17 at 19:59
  • @YoushaAleayoub please ellaborate it more or give better answer! – Lalit Poptani Oct 31 '17 at 04:36
  • @LalitPoptani so let me teach you: android doc: "Creating world-readable files is very dangerous, and likely to cause security holes in applications. It is strongly discouraged; instead, applications should use more formal mechanism for interactions such as ContentProvider, BroadcastReceiver, and Service. There are no guarantees that this access mode will remain on a file, such as when it goes through a backup and restore. " – Yousha Aleayoub Oct 31 '17 at 09:02
  • @YoushaAleayoub and where is world-readable? used in my answer? – Lalit Poptani Oct 31 '17 at 14:15
  • @LalitPoptani well, because you didnt even read my FIRST message and you just started flaming me... I was talking to subrussn90, NOT you. look above – Yousha Aleayoub Oct 31 '17 at 18:56