其他分享
首页 > 其他分享> > android-保存小部件状态

android-保存小部件状态

作者:互联网

文件
http://developer.android.com/guide/topics/data/data-storage.html

显示有多种保存数据的方法,我需要在小部件中执行此操作,每次尝试保存时都会出错…

例如

      SharedPreferences settings = getSharedPreferences("NAME", 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", false);

      // Commit the edits!
      editor.commit();

错误

Description Resource    Path    Location    Type
The method getSharedPreferences(String, int) is undefined for the type AWidget

另一尝试:

     String FILENAME = "hello_file";
     String string = "hello world!";

     FileOutputStream fos = openFileOutput("Test.txt", Context.MODE_PRIVATE);
     fos.write(string.getBytes());
     fos.close();

有错误

Description Resource    Path    Location    Type
The method openFileOutput(String, int) is undefined for the type AWidget

这是怎么回事?我没有提到这在小部件中不起作用,那么为什么这些示例对我不起作用?

保存此数据的首选方法是什么?

解决方法:

因此,问题在于,我不能仅仅在没有实质内容的情况下使用此函数,如果我在上下文中使用上述代码,它将可以正常工作.在它前面…

 SharedPreferences settings = context.getSharedPreferences("NAME", 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", false);

      // Commit the edits!
      editor.commit();

如您所见,这就是获取共享首选项所需要的全部…

int [] allids = AppWidgetManager
        .getInstance(上下文)
        .getAppWidgetIds(new ComponentName(context,AwarenessWidget.class));

我可以获取应用程序的所有ID,然后调用onupdate并根据保存的首选项更新每个视图

如果有人需要,我可以详细说明…

让我感到困惑的是,没有人能够找出那个人并帮助我!现在看来非常简单!

标签:android-widget,android
来源: https://codeday.me/bug/20191209/2095940.html