2011-09-13 10 views
5

Sto costruendo un'applicazione Android e ho bisogno di scaricare un file da un url, che è grande 33 MB.Android: eccezione "Inaspettata fine del flusso" di download di file di grandi dimensioni

Qui l'attività di download:

try { 
      int MAX_BUFFER_SIZE = 4096; 
      URL mUrl = new URL(params[0]); 
      HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection(); 
      connection.setRequestMethod("GET"); 
      long length = connection.getContentLength(), downloaded = 0; 
      int read; 
      byte [] buffer = new byte[(((int)length) > MAX_BUFFER_SIZE) ? MAX_BUFFER_SIZE : (int)length]; 
      String filename = getFilename(mUrl); 
      File file = new File (SDCARD_ROOT); 
      if (!file.exists() || !file.isDirectory()){ 
       file.mkdir(); 
      } 
      this.filename = filename; 
      file = new File (SDCARD_ROOT + this.filename); 
      FileOutputStream fos = new FileOutputStream (file); 
      //Start downloading 
      InputStream stream = connection.getInputStream(); 

      while ((read=stream.read(buffer)) > -1){ 
       fos.write(buffer, 0, read); 
       downloaded += read; 
       publishProgress((int) ((float) downloaded/length * 100)); 
      } 
      fos.close(); 
      return 1; 
     } catch (Exception e){ 
      Log.e("REV-PARTS", "Revolver parts error in DownloadTask: " + e.getMessage()); 
      return 2; 
     } 

Funziona scorretto con file di piccole dimensioni (1-15 mb), ma restituirà un "fine inaspettata di flusso" eccezione con file di grandi dimensioni. Grazie in anticipo.

+0

Quale chiamata genera l'eccezione? 'Stream.Read()'? –

+1

Sì, stream.read – Gnufabio

+0

@Gnufabio, sei riuscito a risolvere questo problema? –

risposta

-2

mentre si cattura l'eccezione, provo il metodo downContinue(), posso mostrare il mio codice: metodo

private void downloadApk() { 
    thread1 = new Thread() { 
     public void run() { 
      File oFile = null; 
      try { 
       URL url = new URL(PQGLApplication.resrootURL + "apk/PQGLMap.apk"); 
       HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
       ReadableByteChannel channel = 
         Channels.newChannel(urlConnection.getInputStream()); 
       oFile = 
         new File(Environment.getExternalStorageDirectory().getAbsolutePath() 
           + "/" + "hy_ht_new/" + "test2" + ".apk"); 
       oFile.setWritable(true); 
       oFile.setReadable(true); 
       if (oFile.exists()) { 
        oFile.delete(); 
       } 
       FileOutputStream fos = new FileOutputStream(oFile); 
       fileSize = urlConnection.getContentLength(); 
       ByteBuffer buffer = ByteBuffer.allocate(1024); 
       int noOfBytes = 0; 
       byte[] data = null; 
       sendApkMessage(0, 0); 
       while ((noOfBytes = channel.read(buffer)) > 0) { 
        data = new byte[noOfBytes]; 
        System.arraycopy(buffer.array(), 0, data, 0, noOfBytes); 
        buffer.clear(); 
        fos.write(data, 0, noOfBytes); 
        downLoadFileSize += noOfBytes; 
        sendApkMessage(1, downLoadFileSize); 
       } 
       fos.flush(); 
       fos.close(); 
       channel.close(); 
       sendApkMessage(2, oFile.getAbsolutePath()); 
      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
       downContinue(); 
      } 
     }; 
    }; 
    thread1.start(); 
} 

private void downContinue() { 
    continueTime++; 
    try { 
     if (continueTime == 3) { 
      continueTime = 0; 
      sendApkMessage(4, 0); 
      Log.e("what is the fucking continuetime", "continueTime" + continueTime); 
     } else { 
      URL url = new URL(PQGLApplication.resrootURL + "apk/PQGLMap.apk"); 
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); 
      File oFile = 
        new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" 
          + "hy_ht_new/" + "test2" + ".apk"); 
      RandomAccessFile oSavedFile = new RandomAccessFile(oFile, "rw"); 
      FileOutputStream fos = new FileOutputStream(oFile); 
      ReadableByteChannel channel = Channels.newChannel(urlConnection.getInputStream()); 
      // oSavedFile.seek(nPos); 
      ByteBuffer buffer = ByteBuffer.allocate(1024); 
      byte[] data = null; 
      int temp = 0; 
      sendApkMessage(3, oFile.getAbsolutePath()); 
      while ((temp = channel.read(buffer)) > 0) { 
       data = new byte[temp]; 
       System.arraycopy(buffer.array(), 0, data, 0, temp); 
       buffer.clear(); 
       fos.write(data, 0, temp); 
      } 
      fos.flush(); 
      fos.close(); 
      oSavedFile.close(); 
      sendApkMessage(2, oFile.getAbsolutePath()); 
      continueTime = 0; 
     } 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     Log.e("what is the fucking exception", e.toString() + continueTime); 
     downContinue(); 
    } 

} 

questo downContinue viene utilizzato per risolvere questo problem.At almeno, il file viene scaricato con successo! Vengo dalla Cina. Il mio inglese non è molto buono.

+0

puoi spiegare il metodo sendApkMessage(), che cosa sta facendo esattamente? – skygeek

+0

Non è necessario impostare il file di output leggibile o scrivibile o pre-eliminarlo se esiste. 'new FileOutputStream()' ha già tutti quegli effetti. Non hai nemmeno bisogno di 'System.arraycopy()'. Il metodo si basa su un codice esterno non specificato. – EJP

-1

Per i file di grandi dimensioni è necessario impostare il timeout della connessione manualmente utilizzando il codice seguente. Ho impostato il tempo per 3 minuti

connection.setConnectTimeout(180000); 
    connection.setReadTimeout(180000); 
+0

Come risolverà un problema di "fine imprevisto del flusso"? – EJP

+0

sarà come questo errore si verifica durante il download a causa del timeout, –

0

ho una risposta per questo. dovresti aggiungere un'intestazione alla tua connessione.

connection.setRequestProperty("Accept-Encoding", "identity"); 

questo mi aiuterà a you.say se aiutare ...

0

Impostazione di un formato pezzo sembrava funzionare per me.

connection.setChunkedStreamingMode(1048576); 
Problemi correlati