如何传递更多的值 doInBackground
我AsyncTask看起来像这样.
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
{
}
}
Run Code Online (Sandbox Code Playgroud)
有可能以某种方式传递更多的价值观 protected String DoInBackground
例如: protected String doInBackground(String... sUrl, String... otherUrl, Context context)
而如何execute在AsyncTask后?new DownloadFile.execute("","",this)或者其他的东西?
sti*_*ike 11
您可以发送多个参数,因为您可以将它们作为varargs发送.但是你必须使用相同类型的参数.所以要做你想做的事,你可以遵循以下任何一项
选项1
你可以使用setter方法设置类成员的某些值,然后在doInBackGround中使用它们.例如
private class DownloadFile extends AsyncTask<String, Integer, String> {
private Context context;
public void setContext(Context c){
context = c;
}
@Override
protected String doInBackground(String... sUrl) {
{
// use context here
}
}
Run Code Online (Sandbox Code Playgroud)
选项2
或者您可以使用构造函数来传递值
private class DownloadFile extends AsyncTask<String, Integer, String> {
private Context context;
public DownloadFile (Context c){
context = c;
}
@Override
protected String doInBackground(String... sUrl) {
{
// use context here
}
}
Run Code Online (Sandbox Code Playgroud)
String... sUrl
Run Code Online (Sandbox Code Playgroud)
三个连续的点意味着多于一个字符串.该点是可变参数
以及如何传递上下文?
你可以强制它添加一个以Context为参数的构造函数:
private Context mContext;
public void setContext(Context context){
if (context == null) {
throw new IllegalArgumentException("Context can't be null");
}
mContext = context;
}
Run Code Online (Sandbox Code Playgroud)
您可以在 doInBackground 方法中执行以下操作:
String a = sUrl[0]
String b = sUrl[1]
Run Code Online (Sandbox Code Playgroud)
以这种方式执行 AsyncTask:
new DownloadFile().execute(string1,string2);
Run Code Online (Sandbox Code Playgroud)
第一个值: sUrl[0] 将是从 string1 传递
的值,surl[1] 将是传递的第二个值,即 string2 !
| 归档时间: |
|
| 查看次数: |
23815 次 |
| 最近记录: |