2012-12-27 30 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