Get preferences in AppWidget Provider

泪湿孤枕 提交于 2019-11-29 01:10:43

问题


I seem to be having trouble reading preferences from my AppWidgetProvider class. My code works in an Activity, but it does not in an AppWidgetProvider. Here is the code I am using to read back a boolean:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean autoreplyon = settings.getBoolean("autoreplyon", false);

However, I get the "The method getSharedPreferences(String, int) is undefined for the type widget" error (widget is the name of my AppWidgetProvider class).

Thanks in advance for any suggestions!


回答1:


getSharedPreferences(), should you choose to use it, is only available on subclasses of Context, like Activity or Service. AppWidgetProvider is a subclass of BroadcastReceiver, which is not a Context.

That being said, if you are going to use the PreferenceScreen system, or if you are not certain that it's gotta gotta gotta be getSharedPreferences(), I would use PreferenceManager.getDefaultSharedPreferences() instead. Those are the SharedPreferences that PreferenceScreen/PreferenceActivity will use.




回答2:


You should have been passed a context in widget's onUpdate() method so you can call context.getSharedPreferences().

For per-appwidget preferences, I have used this:

public static String getSharedPreferencesNameForAppWidget(Context context, int appWidgetId) {
    return context.getPackageName() + "_preferences_" + appWidgetId;
}

public static SharedPreferences getSharedPreferencesForAppWidget(Context context, int appWidgetId) {
    return context.getSharedPreferences(
        getSharedPreferencesNameForAppWidget(context, appWidgetId), 0);
}


来源:https://stackoverflow.com/questions/2748268/get-preferences-in-appwidget-provider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!