【问题标题】:Passing SharedPreferences to doInBackground()将 SharedPreferences 传递给 doInBackground()
【发布时间】:2012-12-27 10:55:09
【问题描述】:

我正在尝试将 SharedPreferences 首选项作为参数传递给 AsyncTask 中的 doInBackground 函数。我已经将字符串(url)传递给它,所以我需要将首选项也作为字符串传递。我可以简单地使用 prefs.toString() 将其转换为字符串吗?

这是我设置首选项的地方:

if (prefs.getBoolean("firstrun", true)) {
            prefString = prefs.toString();
            prefs.edit().putBoolean("firstrun", false).commit();
        }

【问题讨论】:

  • 当您尝试使用“prefs.toString()”将其转换为字符串时,会发生什么?
  • 为什么不在后台引用首选项?
  • 我不知道该怎么做!

标签: java android sharedpreferences


【解决方案1】:

你不能也不应该。您可以轻松读取 doInBackground() 中的首选项,而无需向方法传递任何内容,只需使用 PreferenceManager

public class DownloadFiles extends AsyncTask<URL, Void, Void> {

  Context ctx;

  DownloadFiles(Context ctx) {
    this.ctx = ctx;
  }

  @Override
  public void doInBackground(URL... urls) {
    // ...
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    // ...
  }
}

【讨论】:

  • 你能告诉我如何使用 PreferenceManager 来实现我想要做的事情吗?
  • 这是好习惯吗?我认为你不应该在 doInBackground 方法中使用上下文......
  • @Maxrunner 找不到原因。 Context 仅传递给静态方法,在该方法中读取其字段以解析名称
【解决方案2】:

试试这个代码:

  public class DownloadFiles extends AsyncTask<URL, Void, Void> {

      Context ctx;
    boolean firstLaunch;
    SharedPreferences prefs;


      DownloadFiles(Context ctx) {
        this.ctx = ctx;
        prefs = ctx.getSharedPreferences("Prefs",Context.MODE_PRIVATE);
      }
      @Override
      public void onPreExecute() {
          firstLaunch = prefs.getBoolean("firstrun", true);
      }

      @Override
      public void doInBackground(URL... urls) {

        if(firstLaunch)
          // code for the firstLaunch
        else 
          //code if it isn't the firstLaunch 
      }

      @Override
      public void onPostExecute(Void params) {
          // update prefs after the firstLaunch
          if(firstLaunch)
              prefs.edit().putBoolean("firstrun", false).commit();
      }
    }

【讨论】:

  • @LalitPoptani : 一个很好的注释和很好的解释的代码也是一个很好的答案:)。它不是一堵代码墙
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
  • 2013-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-28
  • 1970-01-01
相关资源
最近更新 更多