我是安卓新手。我有一个正在下载 URL 内容的 AsyncTask。我不希望 AsyncTask 直接操作 UI 并希望它作为可重用的代码片段,所以我将它放在自己的文件中并返回一个字符串。问题是返回发生在 AsyncTask 完成之前(即使我正在使用 .excecute() 的 .get()),所以我什么也得不到。这是我目前拥有的东西:
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();
}
}
}
}
解决这个问题的最佳方法是什么,以便我的主线程以某种方式取回结果?我遇到过一些提到事件和回调的文章。这是最好的方法吗..?