Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get data from shared preferences inside a service?

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?

like image 304
SIVAKUMAR.J Avatar asked Nov 26 '12 04:11

SIVAKUMAR.J


People also ask

How can I get shared preferences data?

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

Where is shared preference data stored?

Android Shared Preferences Overview Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.

Which type of data is stored in shared preferences files?

Shared Preferences is the way in which one can store and retrieve small amounts of primitive data as key/value pairs to a file on the device storage such as String, int, float, Boolean that make up your preferences in an XML file inside the app on the device storage.

What is the difference between internal storage and shared preferences?

what is the difference between shared preferences and internal storage in Android? Internal storage refers to a place on the on-board flash that is private to your app and not visible to users. SharedPreferences is one way of storing data on internal storage.


2 Answers

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.

like image 71
twaddington Avatar answered Oct 02 '22 13:10

twaddington



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

like image 25
SIVAKUMAR.J Avatar answered Oct 02 '22 15:10

SIVAKUMAR.J