异步任务中的 HTTP 请求阻塞了 UI
我正在发出 HTTP 请求来下载文件。对数据的请求以及将数据写入磁盘是在 AsyncTask
内完成的。但是,在下载文件时,应用程序会随机冻结 5-10 秒,同时使用 inputStream.read()
读取下一个数据块。由于这是在 AsyncTask
中,因此应用程序不应冻结,对吗?
以下是启动 AsyncTask
的代码(伪代码):
MyClass {
public boolean onContextItemSelected(MenuItem item) {
(...)
DownloadMedia dm = new DownloadMedia();
dm.startDownload();
}
}
以及执行下载的代码:
public class DownloadMedia {
public void startDownload() {
DownloadMediaTask task = new DownloadMediaTask();
task.execute();
}
private class DownloadMediaTask extends AsyncTask<Void, Integer, Void> {
protected Void doInBackground(Void... params) {
(...)
URL url = new URL(file.getUrl());
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[1024 * 50];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer, 0, buffer.length)) != -1) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
return null;
}
}
I'm making an HTTP request to download a file. This request for the data as well as writing the data to disk is done within an AsyncTask
. However, randomly when downloading the file the application will freeze for 5-10 seconds while the next block of data is read using inputStream.read()
. Since this is in an AsyncTask
, the application should not freeze, correct?
The following is the code to start the AsyncTask
(pseudocode):
MyClass {
public boolean onContextItemSelected(MenuItem item) {
(...)
DownloadMedia dm = new DownloadMedia();
dm.startDownload();
}
}
And the code that does the downloading:
public class DownloadMedia {
public void startDownload() {
DownloadMediaTask task = new DownloadMediaTask();
task.execute();
}
private class DownloadMediaTask extends AsyncTask<Void, Integer, Void> {
protected Void doInBackground(Void... params) {
(...)
URL url = new URL(file.getUrl());
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
byte[] buffer = new byte[1024 * 50];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer, 0, buffer.length)) != -1) {
fileOutput.write(buffer, 0, bufferLength);
}
fileOutput.close();
return null;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论