如何从 AsyncTask 取回字符串? [英] How to get a string back from AsyncTask?

查看:17
本文介绍了如何从 AsyncTask 取回字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

public class getURLData extends AsyncTask<String, Integer, String>{

@Override
protected String doInBackground(String... params) {
    String line;
    try {  
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(params[0]);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        line = EntityUtils.toString(httpEntity);

    } catch (UnsupportedEncodingException e) {
        line = "<results status="error"><msg>Can't connect to server</msg></results>";
    } catch (MalformedURLException e) {
        line = "<results status="error"><msg>Can't connect to server</msg></results>";
    } catch (IOException e) {
        line = "<results status="error"><msg>Can't connect to server</msg></results>";
    }
    return line;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
}

}

我试着这样称呼它:

String output = null;
output = new getURLData().execute("http://www.domain.com/call.php?locationSearched=" + locationSearched);

但是输出变量没有获取数据,而是出现错误:

But the output variable isn't getting data, instead I am getting an error:

Type mismatch: cannot convert from AsyncTask<String,Integer,String> to String

推荐答案

方法execute返回的是AynscTask本身,需要调用get:

The method execute returns the AynscTask itself, you need to call get:

output =
    new getURLData()
        .execute("http://www.example.com/call.php?locationSearched=" + locationSearched)
        .get();

这将启动一个新线程(通过execute),同时阻塞当前线程(通过get),直到新线程的工作完成并且结果为被退回.

This will start a new thread (via execute) while blocking the current thread (via get) until the work from the new thread has been finished and the result has been returned.

如果你这样做,你只是把你的异步任务变成了一个同步任务.

If you do this, you just turned your async task into a sync one.

然而,使用 get 的问题在于,因为它阻塞,所以需要在工作线程上调用它.但是,AsyncTask.execute() 需要在主线程上调用.因此,尽管此代码可以工作,但您可能会得到一些不希望的结果.我还怀疑 get() 没有经过 Google 的测试,他们可能在此过程中的某个地方引入了一个错误.

However, the problem with using get is that because it blocks, it needs to be called on a worker thread. However, AsyncTask.execute() needs to be called on the main thread. So although this code could work, you may get some undesired results. I also suspect that get() is under-tested by Google, and it is possible that they introduced a bug somewhere along the line.

参考:AsyncTask.get

这篇关于如何从 AsyncTask 取回字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆