我是Android新手。我有一个正在下载URL内容的AsyncTask。 我不希望AsyncTask直接操作用户界面,并希望它将它作为可重用的代码,因此我将它放在它自己的文件中,并返回一个字符串。 问题是,返回发生在AsyncTask完成之前(即使我使用.excecute())的.get(),所以我没有得到任何回报。 这里是啥子我在此刻:Android AsyncTask无法直接访问UI
package com.example.mypackage;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutionException;
import android.os.AsyncTask;
public class URLContent {
private String content = "default value";
public String getContent(String URL){
try {
new getAsyncContent().execute(URL).get();
} catch (InterruptedException e) {
content = e.getMessage();
} catch (ExecutionException e) {
content = e.getMessage();
}
return content;
}
private class getAsyncContent extends AsyncTask<String, Integer, String>
{
@Override
protected void onPostExecute(String result) {
content = result;
}
@Override
protected String doInBackground(String... urls) {
try{
return URLResponse(urls[0]);
} catch (Exception e){
return e.getMessage();
}
}
}
private String IStoString(InputStream stream) throws IOException, UnsupportedEncodingException {
try {
return new java.util.Scanner(stream, "UTF-8").useDelimiter("\\A").next();
} catch (java.util.NoSuchElementException e) {
return "";
}
}
private String URLResponse(String URLToget) throws IOException {
InputStream is = null;
try {
URL url = new URL(URLToget);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = IStoString(is);
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
}
什么是解决这个让我的主线程莫名其妙地回来了结果的最佳方式是什么? 我来过一些提及事件和回调的文章。这是最好的方式..?
更新在它完成之前?可能是你的方法'URLResponse'返回'null',你认为它不起作用。顺便说一下,你的'AsyncTask'是通过你使用它的方式同步的。 –
作为一个附注,您应该遵循Java代码约定。 Java类必须以大写字母 – Bostone