I have a GPS service and Settings Fragment. When Service called first time or stopped and started again by user because settings may changed I want to access values at the shared Preferences which was written by Settings Fragment.
Code at Service:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
setLOCATION_INTERVAL(sharedPreferences.getInt("KEY_GPS_FREQ", 1) * 1000);
Toast.makeText(getBaseContext(), "Interval Value from SharedPref " + LOCATION_INTERVAL, Toast.LENGTH_SHORT).show();
Here, I also tried getBaseContext(). But both of them only returns 1000 this means it doesn't read correct value.
And at the Settings Fragment side here is my code:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KEY_GPS_FREQ", seekBar.getProgress());
editor.apply();
I also tried :
SharedPreferences preferences = getApplicationContext().getSharedPreferences("myPref",MODE_PRIVATE);
at service side and at fragment side:
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("myPref",Context.MODE_PRIVATE);
they did not work too.