在 AppWidget Provider 中获取首选项
我似乎无法从 AppWidgetProvider 类中读取首选项。我的代码可以在 Activity 中运行,但不能在 AppWidgetProvider 中运行。这是我用来读回布尔值的代码:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean autoreplyon = settings.getBoolean("autoreplyon", false);
但是,我收到“方法 getSharedPreferences(String, int) 对于类型小部件未定义”错误(小部件是我的 AppWidgetProvider 类的名称)。
预先感谢您的任何建议!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
getSharedPreferences()
(如果您选择使用它)仅在Context
的子类上可用,例如Activity
或Service
>。AppWidgetProvider
是BroadcastReceiver
的子类,它不是Context
。话虽这么说,如果您要使用
PreferenceScreen
系统,或者如果您不确定它一定是getSharedPreferences()
,我会使用相反,PreferenceManager.getDefaultSharedPreferences()
。这些是PreferenceScreen
/PreferenceActivity
将使用的SharedPreferences
。getSharedPreferences()
, should you choose to use it, is only available on subclasses ofContext
, likeActivity
orService
.AppWidgetProvider
is a subclass ofBroadcastReceiver
, which is not aContext
.That being said, if you are going to use the
PreferenceScreen
system, or if you are not certain that it's gotta gotta gotta begetSharedPreferences()
, I would usePreferenceManager.getDefaultSharedPreferences()
instead. Those are theSharedPreferences
thatPreferenceScreen
/PreferenceActivity
will use.您应该已在小部件的
onUpdate()
方法中传递了一个上下文,以便您可以调用context.getSharedPreferences()
。对于每个应用程序小部件的首选项,我使用了这个:
You should have been passed a context in widget's
onUpdate()
method so you can callcontext.getSharedPreferences()
.For per-appwidget preferences, I have used this: