Reputation: 422
I'm using a SharedPreference
in a service and it works correctly the first time I run the app. If I change the value in another activity, then I found out that the value in service hasn't changed (in activity the value is correct). If I restart the app, then it has the correct value. That's to say, the SharedPreference
in my service can only work normally once before I restart app.
I can't figure out the problem, code is like this:
in service
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);
Logger.d(this, "" + sp.getInt(SPConst.KEY_AVOID_DISTURB, 0));
in activity
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(mContext);
SharedPreferences.Editor editor editor = sp.edit();
editor.putInt(SPConst.KEY_AVOID_DISTURB, 1);
editor.commit();
If both set and get are done in service or activity, it worked right, if set in activity, and get in service, then it's wrong.
Upvotes: 3
Views: 1831
Reputation: 422
Finally, I find out the answer, maybe background service and activity are not in the same process, so set mode to MODE_MULTI_PROCESS
:
SharedPreferences sp = SnsService.this.getSharedPreferences("data", Context.MODE_MULTI_PROCESS);
Upvotes: 1
Reputation: 422
If you want to update your data in service class ,just put your code in onStartCommand() method. and call again start-service . Passing an Intent that specifies the service and includes any data for the service to use. The service receives this Intent in the onStartCommand() method.
Upvotes: 0