OopsUser
OopsUser

Reputation: 4774

Simplest way to save persistent data on android (BroadcastReceiver)

I need to save one int in a persistent manner.

The simplest way i found is : SharedPreferences but it requires activity, i don't have an activity because I inherited from BroadcastReciever and want to save and read the data in

public void onReceive(final Context arg0, Intent arg1) 
{
  // Save data here
}

What is my best and simplest option.

Upvotes: 0

Views: 656

Answers (2)

devrocca
devrocca

Reputation: 2547

SharedPreferences are related to a Context, not an Activity, so you could use

public void onReceive(final Context arg0, Intent arg1) 
{
    PreferenceManager.getDefaultSharedPreference(arg0).edit().putInt(yourInt).apply();
}

Upvotes: 1

MysticMagicϡ
MysticMagicϡ

Reputation: 28823

You already have the context in onReceive. So it's easy:

public void onReceive(final Context context, Intent arg1) 
{
    SharedPreferences prefs = context.getSharedPreferences("myPrefs", 
                                                        Context.MODE_PRIVATE);
    Editor editor = pref.edit();
    editor.putString("key_name", "string value");
    editor.commit();
}

Hope it helps.

Upvotes: 1

Related Questions