当我使用 Asynctask
,执行它并尝试使用 get()
在 onCreate
方法它冻结了我的整个ui。
我的任务类:
public class HTMLDownload extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
e.printStackTrace();
return "Failed";
}
}
我的oncreate方法代码:
HTMLDownload task = new HTMLDownload();
try {
String result = task.execute("https://www.telltalesonline.com/26925/popular-celebs/").get();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.i("Result", result);
如何修复这个问题并在下载html后记录文本而不冻结ui?
谢谢
1条答案
按热度按时间ylamdve61#
如前所述
AsyncTask
已弃用。你最好使用android截击之类的工具内部版本.gradle:
androidmanifest.xml:
在你的片段或类或任何东西里面: