传递共享preferences到doInBackground() [英] Passing SharedPreferences to doInBackground()
问题描述
我试图通过共享preferences preFS,在AsyncTask的一个参数传递给doInBackground功能。我已经传递一个字符串(URL)到它,所以我还需要通过preFS为字符串。我可以简单地使用,prefs.toString()将其转换成字符串?
这是我设置preFS:
如果(prefs.getBoolean(firstrun,真)){
prefString = prefs.toString();
prefs.edit()putBoolean(firstrun,假).commit()。
}
您不能,你不应该。您可以轻松地阅读preferences刚内 doInBackground()
withou通过什么方法,只要使用<一个href="http://developer.android.com/reference/android/$p$pference/$p$pferenceManager.html"><$c$c>$p$pferenceManager$c$c>:
公共类DownloadFiles延伸的AsyncTask&LT;网址,虚空,虚空&GT; {
上下文CTX;
DownloadFiles(上下文CTX){
this.ctx = CTX;
}
@覆盖
公共无效doInBackground(网址...网址){
// ...
共享preferences preFS = preferenceManager.getDefaultShared preferences(CTX);
// ...
}
}
I am trying to pass the SharedPreferences prefs, as an argument to doInBackground function in AsyncTask. I am already passing a string(url) to it, so I would need to pass the prefs also as a string. Can I simply use, prefs.toString() to convert it into string?
This is where I set the prefs:
if (prefs.getBoolean("firstrun", true)) {
prefString = prefs.toString();
prefs.edit().putBoolean("firstrun", false).commit();
}
You can't and you shouldn't. You can easily read the preferences just inside doInBackground()
withou passing anything to the method, simply by using the 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);
// ...
}
}
这篇关于传递共享preferences到doInBackground()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!