4

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

谢谢

从活动中调用下载:

            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]);

}
4

2 回答 2

1

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

您应该考虑在您的程序中支持下载恢复,而不是每次都从头开始。

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

此外,您可能会考虑lock为 Wi-Fi 和处理器获取一个,以保持您的程序运行,直到下载完成。

编辑

在您的代码中,尝试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
    }
于 2013-02-14T11:15:33.463 回答
0

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

这是一个示例:DownloadManager Example

并查看文档:DownloadManager

于 2013-02-14T11:21:42.380 回答