Android: "Fin de secuencia inesperada" excepción descargar archivos grandes
Estoy construyendo una aplicación para Android y necesito descargar un archivo de una url, que es de 33 MB de gran tamaño.
Aquí la tarea de descarga:
- ¿Dónde está el navegador predeterminado en Android 4 derivado de?
- Creación de enlaces simbólicos en Android dentro del directorio de activos de una aplicación
- TagSoup vs Jsoup vs HTML Parser vs HotSax vs
- Cómo obtener el espaciado de caracteres de fuente en Android
- Envío de un archivo pdf al cliente desde el servidor a través del servicio web
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; }
Funciona a la derecha con archivos pequeños (1-15 mb), pero devolverá una excepción "inesperado final de secuencia" con archivos grandes. Gracias por adelantado.
- explicar la sintaxis EditText editText = (EditText) findViewById (R.id.edit_message);
- "Error: no se puede encontrar la variable de símbolo xml" al intentar google analytics
- Uso de la modularización en Android
- Diferencia entre close () y disconnect () en Android Bluetooth API?
- Uso de AppBarLayout.Behavior.DragCallback para controlar el desplazamiento del diseño de barra de herramientas que se contrae
- ¿Existe alguna razón para usar el patrón de observador en un receptor de difusión?
- Java: Subclase AsyncTask
- "La aplicación no se ejecutará a menos que actualices los servicios de Google Play" con Google Maps API
Tengo una respuesta para esto. Debe agregar un encabezado a su conexión.
connection.setRequestProperty("Accept-Encoding", "identity");
Esto te ayudará. Dime si ayuda …
Para archivos grandes debe establecer el tiempo de espera de conexión manualmente utilizando el código siguiente. He fijado el tiempo a 3 minutos
connection.setConnectTimeout(180000); connection.setReadTimeout(180000);
Mientras que usted coge la excepción, intento el método downContinue (), puedo mostrar mi código:
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(); } }
Este método downContinue se utiliza para resolver este problema. ¡Por lo menos, el archivo se descarga con éxito! Vengo de China.Mi inglés no es tan bueno.
- EditText en ListView es actualizado por onTextChanged al desplazarse
- Ocultar teclado virtual al hacer clic en un botón