Can I get data from shared preferences inside a service?

SIVAKUMAR.J picture SIVAKUMAR.J · Nov 26, 2012 · Viewed 53.6k times · Source

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?

Answer

twaddington picture twaddington · Nov 26, 2012

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.