AsyncTask - 慢下载

时间:2013-02-14 11:09:47

标签: android android-asynctask download

我正在使用AsyncTask从互联网下载~50 MB文件。有时,当我下载此文件时,进度条增益非常慢(即使我使用的是Wi-Fi)。一分钟后,手机显示我,下载完成,但文件本身只有~100kB,没有了。但是当我重新启动设备并尝试下载文件时,下载会暂时快速执行。有人遇到过同样的问题吗?下载新文件之前是否需要擦除相同的下载内存?我正在将文件下载到Environment.externalStoryDirectory()。

THX

从活动中调用下载:

            mProgressDialog = new ProgressDialog(ItemDetails.this);
            mProgressDialog.setTitle("Downloading");
            mProgressDialog.setMessage("Downloading sth...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setMax(100);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            DownloadMapTask downloadFile = new DownloadMapTask(ItemDetails.this);
            downloadFile.execute(web_location_url);
            mProgressDialog.show();

下载异步任务(两种方法):

@Override
protected String doInBackground(String... urls) {
    int count;

    PATH=maps_loc+"/Android/data/test/maps/";

    try {
        URL url = new URL(urls[0]);
        HttpURLConnection connection2 = (HttpURLConnection) url.openConnection();
        connection2.setRequestMethod("GET");
        connection2.setDoOutput(true);
        connection2.connect();
        int lenghtOfFile = connection2.getContentLength();

        File apkdir = new File(PATH);
        apkdir.mkdirs();

        File newInstall = new File(PATH, name+".tmp");

        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream(newInstall);

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1 && running==true) {
            total += count;
            publishProgress((int) (total * 100 / lenghtOfFile));
            output.write(data, 0, count);
        }
        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;

}

public void onProgressUpdate(Integer... args) {

    ItemDetails.mProgressDialog.setProgress(args[0]);

}

2 个答案:

答案 0 :(得分:1)

如果客户端速度较慢且下载时间较长,某些服务器将关闭连接,如果您的程序通过移动数据而非Wi-Fi连接到Internet,则会出现这种情况。

您应该考虑在程序中支持下载简历,以免每次都从头开始。

我认为您需要清除的是下载内存。我有一个应用程序,可以轻松下载超过50MB没有问题。

此外,您可能会考虑为Wi-Fi和处理器获取lock,以便在下载完成之前保持您的程序正常运行。

修改

在您的代码中,尝试在行lenghtOfFile之后打印值int lenghtOfFile = connection2.getContentLength();,以确保它与您下载的实际文件大小相同。

下面是支持我在项目中使用的resume的替代示例代码。 (只是为了说明这个想法,你需要根据需要修改代码)

HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(new URI(fileURL)));
HttpResponse response;
InputStream is = null;
FileOutputStream fos = null;
try {

    boolean continueDownloading = false;
    String tmpFileName = fileName + "_tmp";
    outputFile = new File(downloadFolder, tmpFileName);
    if (outputFile.exists()) {
            localFileLength = outputFile.length();
            if (localFileLength > 0) {
                    continueDownloading = true;
            } 

            if (continueDownloading) {
                    request.addHeader("Range", "bytes=" + localFileLength + "-");
            }

            response = httpClient.execute(request);

            long remoteFileLength = 0;
            Header contentLengthHeader = response.getFirstHeader("Content-Length");
            if (contentLengthHeader != null) {
                    remoteFileLength = Integer.parseInt(contentLengthHeader.getValue());
            }

            long downloaded = 0;

            if (continueDownloading) {
                    downloaded = localFileLength;
            }

            long fullFileLength = downloaded + remoteFileLength;

            fos = new FileOutputStream(outputFile, true);

            is = response.getEntity().getContent();


            byte[] buffer = new byte[DOWNLOAD_BUFFER_SIZE];
            int len = 0;
            while ((len = is.read(buffer)) != -1 && isDownloading) {
                    fos.write(buffer, 0, len);
                    downloaded += len;                                      
            }

            fos.flush();

            boolean success = downloaded == fullFileLength;
            if (success) {
                    outputFile.renameTo(new File(downloadFolder, fileName));
            }

    } catch (Throwable ex) {
            ex.printStackTrace();               
    } finally {
       // clean up resources
    }

答案 1 :(得分:0)

尝试使用downloadManager而不是手动下载,使用它有很多好处。

以下是一个示例:DownloadManager Example

并查看文档:{​​{3}}