ZZZ*_*ZZZ 1 android android-asynctask
我有一个扩展 AsyncTask 的类
public class MyClass extends AsyncTask<Void, Void, Void> {
private String response;
public String getResponse(){
return response;
}
@Override
protected Void doInBackground(Void... arg0) {
/* code */
return null;
}
@Override
protected void onPostExecute(Void result) {
response = aString;
super.onPostExecute(result);
}
}
Run Code Online (Sandbox Code Playgroud)
在其他活动中,我创建了一个 MyClass 实例
MyClass c = new MyClass();
c.execute();
response = c.getResponse();
Toast.makeText(getApplicationContext(), "response = " + response, Toast.LENGTH_LONG).show();
Run Code Online (Sandbox Code Playgroud)
但是我的响应变量为空,可能是因为 Toast 是在任务完成之前执行的。你能给我正确的方法,以便我在任务完成后得到结果吗?
结果不需要类字段。在AsyncTask<Params, Progress, Result>提供您所需要的一切。
所以你想String从任务中得到一个回报。为了实现这一点,您必须Result将String. 基本上是这样的:
public class MyClass extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... arg0) {
/* do background stuff to get the String */
return string; // the one you got from somewhere
}
}
Run Code Online (Sandbox Code Playgroud)
您还必须通过调用方法等待计算get()。
String response = new MyClass().execute().get();
Toast.makeText(getApplicationContext(), "response = " + response, Toast.LENGTH_LONG).show();
Run Code Online (Sandbox Code Playgroud)
在此处阅读有关AsyncTask 的更多信息#get
| 归档时间: |
|
| 查看次数: |
7264 次 |
| 最近记录: |