下载多个文件一直停止android

时间:2013-07-08 09:59:59

标签: java android httpurlconnection urlconnection androidhttpclient

尝试使用下面的代码从服务器下载大约38个视频文件,由于某种原因,它在下载过程中不断停止,我主要是在

java.net.SocketException: Connection timed out

我想知道如何以更少的错误执行此操作

我的代码

private class DownloadFile extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog.show();
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            mProgressDialog.setProgress(progress[0]);
            mProgressDialog.setMessage("Downloading "+(i+1)+" of "+downloadURL.length);
        }

        @Override
        protected String doInBackground(String... sUrl) {
            try {

                for(int i = 0; i < sUrl.length; i++){

                    URL url = new URL("http://myvideo.info/videos/"+sUrl[i]);
                    URLConnection connection = null;
                    try {

                        connection = url.openConnection();
                        connection.setConnectTimeout(15000);
                        connection.setReadTimeout(15000);
                    } catch (java.net.SocketTimeoutException e) {
                        e.printStackTrace();
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                    connection.connect();
                    // this will be useful so that you can show a typical 0-100% progress bar
                    int fileLength = connection.getContentLength();

                    // download the file
                    InputStream input = new BufferedInputStream(url.openStream());
                    OutputStream output = new FileOutputStream("/sdcard/"+file_rename[i]);

                    byte data[] = new byte[1024];
                    long total = 0;
                    int count;
                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        publishProgress((int) (total * 100 / fileLength));
                        output.write(data, 0, count);
                    }

                    output.flush();
                    output.close();
                    input.close();
                }

            } catch (Exception e) {
                Log.e("PP", "PP", e);
            }
            return null;
        }

        protected void onPostExecute(String jsonResult) {
            mProgressDialog.dismiss();
        }
    }

2 个答案:

答案 0 :(得分:0)

你确定服务器的响应时间不到15秒吗?(这是我看到你设置的超时)。如果文件很大,你应该单独下载它们,看看Downloader manager,你可以用它来轻松下载大文件。

答案 1 :(得分:0)

您使用的是哪位下载管理器? 我建议将超时更改为最大值。就个人而言,你的代码似乎很好我认为这将是你的下载管理器和超时。希望这会有所帮助。