Android下载已损坏

时间:2016-07-01 07:37:36

标签: android download

我有以下代码从互联网下载大文件:

                try {
                    url = new URL(IPClass.SERVERIP + path[0].get(i) + "/" + fileName);

                    connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    connection.setReadTimeout(7000);
                    connection.connect();
                    fileLengthOnServer = connection.getContentLength();

                    input = connection.getInputStream();
                    output = new FileOutputStream("/sdcard/Android/appdata/tmp/downloadtmp/" + fileName, true);

                    byte data[] = new byte[1024];
                    int count;

                    while ((count = input.read(data)) != -1 && applicationDownloadList.containsKey(fileName)) {
                        total = total + count;
                        output.write(data, 0, count);
                        dl_progress = (int) ((total * 100L) / fileLengthOnServer);
                        applicationDownloadList.put(fileName, dl_progress);

                        if (total == fileLengthOnServer) {
                            downloadSuccessful();
                        }
                    }
                } catch (Exception e) {
                    if (applicationDownloadList.containsKey(fileName)) {
                        doInBackground(appPathList);
                    }
                } finally {
                    try {
                        if (output != null) output.close();
                        if (input != null) input.close();
                    } catch (IOException ignored) {
                    }
                    if (connection != null) {
                        connection.disconnect();
                    }
                }

但有时并不总是文件下载损坏! 能否请您给我解决方案以保证下载成功!

1 个答案:

答案 0 :(得分:0)

您可以选择同步适配器进行大量下载。这将下载您的文件,虽然您的应用程序正在运行。您还可以显示下载进度的通知。