Can I get data from shared preferences inside a service? Can I get data from shared preferences inside a service? android android

Can I get data from shared preferences inside a service?


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.



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


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!)