gpt4 book ai didi

java - 尝试理解 AsyncTask

转载 作者:行者123 更新时间:2023-12-01 14:15:23 25 4
gpt4 key购买 nike

我正在做一些修改,因为我是一名菜鸟程序员 - 目前正在尝试理解 AsyncTask。我有一个关于如何使用它来下载和显示网页内容的示例,但我正在努力弄清楚哪些位的作用。不幸的是我的笔记都是垃圾。有谁能帮忙解释一下吗?

最佳答案

private class DownloadWebpageTask extends AsyncTask<String, Void, String> {

@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();

BufferedReader buffer = new BufferedReader(
new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
// since this is the background thread, we need to return the string reponse so that onPostExecute can update the textview.
return response
}

@Override
protected void onPostExecute(String result) {
// only onPostExecute,onProgressUpdate(Progress...), and onPreExecute can touch modify UI items since this is the UI thread.
textView.setText(result);
}

关于java - 尝试理解 AsyncTask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18152236/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com