我是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