我正在发出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;
}
}