android - 在 Android 中从 AsyncTask 检索返回的字符串

标签 android android-asynctask

我想检索 this file 的内容并将其保存到字符串中。

我试过使用 AsyncTask(基于 this answer),这是我的类(class)。

class RetreiveURLTask extends AsyncTask<Void, Void, String> {

    private Exception exception = null;
    public String ResultString = null;

    protected String doInBackground(Void ... something) {
        URL url;
        try {
            url = new URL("http://stream.lobant.net/ccfm.info");
            HttpURLConnection urlConnection;
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            String stream_url = IOUtils.toString(in, "UTF-8");
            urlConnection.disconnect();

            return stream_url;

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        } catch (Exception e) {
            this.exception = e;
            return null;
        }
    }

    protected void onPostExecute(String stream_url) {
    // TODO: check this.exception 
    // TODO: do something with the feed
    if (this.exception != null)
        this.exception.printStackTrace();

    this.ResultString = stream_url;
    }
}   

我试过像这样使用我的 AsyncTask 类:

  AsyncTask<Void, Void, String> stream_task = new RetreiveURLTask().execute();
  String stream_url = stream_task.ResultString;

但无法识别 ResultString。

我对这一切的运作方式感到困惑。由于 AsyncTask 在后台运行,即使我可以将我的字符串分配给公共(public)变量之一,也不能保证在我进行分配时它会有效。即使我要使用某种 getResult() 函数,我也需要知道何时调用它以便代码完成执行。

那么,这通常是如何完成的?

(还有,我的http读取代码可以吗?)


我的能力:我会编码,但我是 android 新手。

最佳答案

使用接口(interface)

new RetreiveURLTask(ActivityName.this).execute();

在你的异步任务中

TheInterface listener;

在构造函数中

 public RetreiveURLTask (Context context)
{

    listener = (TheInterface) context;
}  

界面

public interface TheInterface {

    public void theMethod(String result);

     }

在onPostExecute中

if (listener != null) 
  {
  listener.theMethod(stream_url);
  }

在你的 Activity 类中实现接口(interface)

 implements RetreiveURLTask.TheInterface

实现方法

 @Override
 public void theMethod(String result) {
 // update ui using result
 }

关于android - 在 Android 中从 AsyncTask 检索返回的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18870065/

相关文章:

android - 未执行异步任务 doInBackground

java - NETWORK_PROVIDER 未提供位置更新

android - 错误 : R cannot be resolved

将项目添加到 GoogleMap 时 Android AsyncTask 错误

java - 先等待方法完成,然后再继续运行

java - android asynctask处理程序如何正确创建它加上奇怪的无法销毁 Activity 异常

android - 如何在 AsyncTask 中通过 Json 加载 Spinners

android - 错误构建gradle

android - 如何防止用户更改系统日期/时间(在 Android 中)?

android - gradle:根据构建类型(或变体)执行代码