How do I store data for a widget?
I am creating a widget, and I need to store some data for it. I don't have an Activity
with the widget, so I can't utilize SharedPreferences
. The data I am storing is very small but accessed frequently, so it would be overkill to use a 开发者_如何学编程database for it. I have thought of using simple files, but that doesn't seem like a good solution. Is there any way to store simple data for a widget?
You do not need an Activity
to store preferences, just a Context
. In your class that extends AppWidgetProvider
, you should receive a context in all the pertinent methods such as onUpdate
and onDeleted
.
You can then use PreferenceManager
to get the preference object and store what you need in it, such as this:
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String value = prefs.getString("key-string", null);
if(value != null)
{
// do stuff
}
}
As a side note, you mention that you considered using files but didn't want to for performance reasons. SharedPreferences
objects actually end up using simple files, they are just managed for you by Android. If you are going to be accessing it often, you will still need to be careful about performance. The same holds true for SQLite DBs, as those are just files as well.
Those regular Widget methods contains context is true, but what if those contexts change? For eg one app call an action which listen the widget with onReceive and save data with that context will be able to read it with other app action ? - other context.
What if it would be overridden the Application and get it ? - with activity works, not sure about widget!
精彩评论