将SharedPreferences传递给doInBackground()

我试图传递SharedPreferences prefs,作为AsyncTask中doInBackground函数的参数。 我已经传递了一个字符串(url),所以我还需要将prefs作为字符串传递。 我可以简单地使用prefs.toString()将其转换为字符串吗?

这是我设置prefs的地方:

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

你不能,也不应该。 只需使用PreferenceManager ,您就可以轻松读取doInBackground()内部的首选项,只需将任何内容传递给方法即可:

 public class DownloadFiles extends AsyncTask { Context ctx; DownloadFiles(Context ctx) { this.ctx = ctx; } @Override public void doInBackground(URL... urls) { // ... SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx); // ... } } 

试试这段代码:

  public class DownloadFiles extends AsyncTask { 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(); } }