2012-12-27 33 views
0

我想通过SharedPreferences偏好设置,作为AsyncTask中doInBackground函数的参数。我已经传递了一个字符串(url),所以我需要将prefs也作为字符串传递。我可以简单地使用prefs.toString()将其转换为字符串吗?将SharedPreferences传递给doInBackground()

这是我设置首选项:

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

当您尝试使用“prefs.toString() “将其转换为字符串,会发生什么? –

+1

为什么不参考背景中的前缀? –

+0

我不知道该怎么做! – defiant

回答

4

你不能和你不应该。您可以轻松地阅读喜好只是内部doInBackground() withou通过什么方法,只要使用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); 
    // ... 
    } 
} 
+0

你能告诉我如何使用PreferenceManager来实现我想要做的事吗? – defiant

+0

@oDx查看更新 – Raffaele

+0

http://developer.android.com/reference/android/preference/PreferenceManager.html – JoseLSegura

0

试试这个代码:

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(); 
     } 
    } 
+0

我可以理解downvote的原因吗? – Houcine

+0

解释丢失。 –

+0

解释在代码 – Houcine