You can get SharedPreferences
in the background using an AsyncTask
.
The mistake is in this line, where you are passing in the wrong type of variable:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
In your case, the word this
refers to the AsyncTask
instance that you are calling if from.
What I do is I pass the Context
in to the task in the execute()
method. See the code below for a working example:
new AsyncTask<Context, Void, String>()
{
@Override
protected String doInBackground(Context... params)
{
Context context = params[0];
SharedPreferences prefs =
context.getSharedPreferences("name of shared preferences file",
Context.MODE_PRIVATE);
String myBackgroundPreference = prefs.getString("preference name", "default value");
return myBackgroundPreference;
}
protected void onPostExecute(String result)
{
Log.d("mobiRic", "Preference received in background: " + result);
};
}.execute(this);
In the above example, this
refers to the Activity
or Service
that I call this from.