我正在尝试从网址获取文本并将其显示为字符串。网址以 .txt 结尾,如 www.gains.com/more.txt 这些文本很长,最大大小为 1MB。我正在尝试使用 AsyncTask 来获取它们。问题是代码有时有效,有时无效。我不知道为什么。
这是 AsyncTask 代码。
class RequestTask extends AsyncTask<String, String, String>{
@Override
// username, password, message, mobile
protected String doInBackground(String... url) {
// constants
int timeoutSocket = 15000; //Is this enough for 1MB files?
int timeoutConnection = 15000;
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpGet httpget = new HttpGet(url[0]);
try {
HttpResponse getResponse = client.execute(httpget);
final int statusCode = getResponse.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK) {
Log.w("MyApp", "Download Error: " + statusCode + "| for URL: " + url);
return null;
}
line = "";
StringBuilder total = new StringBuilder();
HttpEntity getResponseEntity = getResponse.getEntity();
BufferedReader reader = new BufferedReader(new InputStreamReader(getResponseEntity.getContent()));
while((line = reader.readLine()) != null) {
total.append(line);
}
line = total.toString();
return line;
} catch (Exception e) {
Log.w("MyApp", "Download Exception : " + e.toString());
}
return null;
}
@Override
protected void onPostExecute(String result) {
story.add(result); //story is the array which I use to display the downloaded text
}
}
我是这样调用它的。我在不是 OnCreate 的方法中调用它,甚至在新线程中调用它以避免 NetworkOnMainThreadException 错误。
new Thread() {
@Override
public void run() {
new RequestTask().doInBackground("www.gains.com/more.txt");
new RequestTask().onPostExecute(line);
}
}.start();
最佳答案
这不是调用 asynctask 的正确方法。您不能直接调用 doinbackground,也不能调用 postexecute。 你所要做的就是写:
RequestTask MyAsynchTask = new RequestTask().
MyAsynchTask.execute("www.gains.com/more.txt");
它是公共(public)执行方法,它将为您调用所有方法:preexecute、doinbackground 和 postexecute。
使用此解决方案,您不会遇到 ANR 问题(应用程序无响应)。
告诉我这是否适合你
你说:有时有效有时不行?当你写:
requestTask().doInBackground("www.gains.com/more.txt");
new RequestTask().onPostExecute(line);
java 在 postexecute 中无法知道 doinbackground 是否完成!所以有时你会得到你的结果,有时不会,这取决于java在doinbackground方法中工作需要多少时间。
实现异步任务的唯一方法是按照我上面写的那样进行。如果您在结果中没有您希望的数据,那是因为其他原因。
它只能运行一次:如果你想再次运行它,你必须创建 RequestTask 的另一个实例
关于java - 使用 AsyncTask 从 url 获取文本。代码由于某种原因无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20272269/