52

I'm developing an android application. I'm using android 2.2

In my application I am capturing GPS data and sending it to service with the 1 hour time interval. If user exits from application it's also working (it is required).

I'm using 2 services (User defined), one for capturing GPS data and other for sending to the server.

Here my doubt

  • In service, can we use shared preferences.

  • If we store any data in shared preferences in any activity of the application, will we be able to use that data in service with the help of shared preferences?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
SIVAKUMAR.J
  • 4,258
  • 9
  • 45
  • 80

6 Answers6

47

You can access the default shared preferences instance, which is shared across all your Activity and Service classes, by calling PreferenceManager.getDefaultSharedPreferences(Context context):

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

This is great for storing simple primitives (like booleans) or serializable objects. However, if you're capturing a lot of location data, you might consider using a SQLite database instead.

twaddington
  • 11,607
  • 5
  • 35
  • 46
  • 4
    This answer combined with this: The context within the service will not be visible until onStart or onStartCommand in services: http://stackoverflow.com/questions/7619917/how-to-get-context-in-android-service-class solved this for me. – class Aug 15 '13 at 20:56
  • 2
    You can always pass in the result of the service's `getApplicationContext()` method instead. – twaddington Aug 16 '13 at 05:51
  • @twaddington So if we use `getSharedPreferences(String, Context)` the preferences would not be shared? – Sohaib Apr 17 '15 at 07:20
  • @twaddington: I also use the shared preference across my activity and services like mPrefsRead = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE); . But sometimes, I get the default values from the preferences like if I write mPrefsWrite.putBoolean(KEY, true) but I get false when reading like mPrefsRead.getBoolean(KEY_LOGIN_STATUS, false);. I also confirmed that the value is not set false anywhere. My app and services run as different processes, which leads to get default values from preferences as told in some SO answers. Is it possible to resolve this using your answer. – Madhan Aug 15 '17 at 16:36
  • This is the proper answer Thanks to twaddington and for example in MyService Class and Method below: @Override public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String email = preferences.getString("email_address", "default@google.com"); mythread = new MyThread(email); Toast.makeText(this, email, Toast.LENGTH_LONG).show(); } – Dung Aug 29 '18 at 17:36
18


I find the solution.
Inside a service we call the following method to get the shared preferences

myapp.bmodel.getApplicationContext().getSharedPreferences("myPrefs_capture_gps_per_hour", Context.MODE_PRIVATE);


In the above code myapp is a object of the application class which is derived from Application

SIVAKUMAR.J
  • 4,258
  • 9
  • 45
  • 80
8

You need a context to get access to shared preferences. The best way is to create MyApplication as a descendant of Application class, instantiate there the preferences and use them in the rest of your application as MyApplication.preferences:

public class MyApplication extends Application {
    public static SharedPreferences preferences;

    @Override
    public void onCreate() {
        super.onCreate();

        preferences = getSharedPreferences( getPackageName() + "_preferences", MODE_PRIVATE);

For example, if you need access to your preferences somewhere else, you may call this to read preferences:

String str = MyApplication.preferences.getString( KEY, DEFAULT );

Or you may call this to save something to the preferences:

MyApplication.preferences.edit().putString( KEY, VALUE ).commit();

(don't forget to call commit() after adding or changing preferences!)

lenik
  • 23,228
  • 4
  • 34
  • 43
  • 2
    This would technically work, but why wouldn't you just use the provided `PreferenceManager#getDefaultSharedPreferences(Context context);` static method? That's exactly what it's for. – twaddington Nov 26 '12 at 04:35
  • 1
    @twaddington you should read more carefully. my answer allows access to preferences when `context` is **not** available. – lenik Nov 26 '12 at 05:08
  • 2
    Sure, but he's specifically asking about using shared preferences in an `Activity` and a `Service`, both of which have a `Context` available. – twaddington Nov 26 '12 at 05:17
  • 1
    It shouldn't matter which context you provide, `getDefaultSharedPreferences` should always return the same `SharedPreference` instance. – twaddington Nov 26 '12 at 06:17
  • and does MyApplication need to be created inside variable in any activities or something? – gumuruh Jan 11 '21 at 19:19
  • @gumuruh no, it's a separate file, MyApplication.java (or .kt). – lenik Jan 12 '21 at 04:20
  • okay. I made that file now and so when the onCreate() method was called ? – gumuruh Jan 12 '21 at 14:59
8

Yes Shivkumar, you can use your share preferences in any kind of services as normal as you are using in your Activity.

same like

SharedPreferences preferences = getSharedPreferences("<PrefName>",
            MODE_PRIVATE);
Jignesh Ansodariya
  • 12,583
  • 24
  • 81
  • 113
5

There are two ways to create instance of SharedPreference:

Case 1:

SharedPreferences preferences = activity.getSharedPreferences("<PrefName>", MODE_PRIVATE);

Case 2:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

Notice if you create a preference with the same name (case 1) or same context (case 2) even at different places, it's still the same, and can share data, obviously.

Satan Pandeya
  • 3,747
  • 4
  • 27
  • 53
Nguyen Tan Dat
  • 3,780
  • 1
  • 23
  • 24
0

In a Service, I would use

  SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.SHARED_PREF, Context.MODE_PRIVATE);
chobela
  • 305
  • 3
  • 5