从没有 get() 方法的 AsyncTask 返回值 [英] Return value from AsyncTask without get() method
问题描述
我正在尝试从 DoInBackground 中的异步任务返回值,但调用 get() 方法会冻结我的 UI.如何将我的代码重写为回调方法?:
I'm trying to return value from my asynctask in DoInBackground, but calling get() method freezes my UI. How can I re-write my code to a callback method? :
public class GetUrlDataTask extends AsyncTask<String, Integer, String> {
String response;
HttpUtils util;
@Override
protected String doInBackground(String... params) {
try {
util = new HttpUtils(params[0]);
response = util.getContent();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
在我的活动中,我得到的结果为 response = new GetUrlDataTask().execute("site").get;
In my activity I get result as response = new GetUrlDataTask().execute("site").get;
推荐答案
[UPDATE] 现在我建议使用注解.使用注释,您可以注入视图,只需几个字母就可以在编译步骤中将函数作为异步过程.在 github 上查看黄油刀库.
[UPDATE] Now i suggest to use annotations. With annotations you can inject views, make function as asyncronous process on the compilation step with just a few letters. Check out butterknife library on github.
您可以创建接口,将其传递给 AsyncTask(在构造函数中),然后在 onPostExecute 中调用方法
You can create interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute
例如:
您的界面:
public interface OnTaskCompleted{
void onTaskCompleted();
}
您的活动:
public YourActivity implements OnTaskCompleted{
//your Activity
}
还有你的 AsyncTask:
And your AsyncTask:
public YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
//required methods
protected void onPostExecute(Object o){
//your stuff
listener.onTaskCompleted();
}
}
这篇关于从没有 get() 方法的 AsyncTask 返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!