簡體   English   中英

下載多個文件不斷停止android

[英]download multiple files keeps stopping android

嘗試使用下面的代碼從服務器上下載約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();
        }
    }

您確定服務器的響應時間不到15秒?(這是我所看到的已設置的超時時間)。 如果文件很大,您應該單獨下載它們,請查看Downloader Manager ,您可以使用它輕松下載大文件。

您正在使用什么下載管理器? 我建議您將超時時間更改為最大。 就個人而言,您的代碼看起來還不錯。 我認為這將是您的下載管理器和超時時間。 希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM