2010-09-11 12 views
16

Tengo un archivo de video en un sitio web en formato .MP4 y quiero permitir que el usuario pueda descargar el video a su tarjeta SD haciendo clic en un enlace. Hay una forma fácil de hacer esto. Actualmente tengo este código pero no funciona ... no estoy seguro de lo que estoy haciendo mal. ¡Gracias por cualquier ayuda!ANDROID: ¿Cómo descargo un archivo de video a la tarjeta SD?

import java.io.BufferedInputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.net.URL; 
import java.net.URLConnection; 

import org.apache.http.util.ByteArrayBuffer; 

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 

public class VideoManager extends Activity { 
/** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState);} 



     private final String PATH = "/sdcard/download/"; //put the downloaded file here 


     public void DownloadFromUrl(String VideoURL, String fileName) { //this is the downloader method 
       try { 
         URL url = new URL("http://www.ericmoyer.com/episode1.mp4"); //you can write here any link 
         File file = new File(fileName); 

         long startTime = System.currentTimeMillis(); 
         Log.d("VideoManager", "download begining"); 
         Log.d("VideoManager", "download url:" + url); 
         Log.d("VideoManager", "downloaded file name:" + fileName); 
         /* Open a connection to that URL. */ 
         URLConnection ucon = url.openConnection(); 

         /* 
         * Define InputStreams to read from the URLConnection. 
         */ 
         InputStream is = ucon.getInputStream(); 
         BufferedInputStream bis = new BufferedInputStream(is); 

         /* 
         * Read bytes to the Buffer until there is nothing more to read(-1). 
         */ 
         ByteArrayBuffer baf = new ByteArrayBuffer(50); 
         int current = 0; 
         while ((current = bis.read()) != -1) { 
           baf.append((byte) current); 
         } 

         /* Convert the Bytes read to a String. */ 
         FileOutputStream fos = new FileOutputStream(PATH+file); 
         fos.write(baf.toByteArray()); 
         fos.close(); 
         Log.d("VideoManager", "download ready in" 
             + ((System.currentTimeMillis() - startTime)/1000) 
             + " sec"); 

       } catch (IOException e) { 
         Log.d("VideoManager", "Error: " + e); 
       } 

     } 
} 
+0

¿Estás seguro de que la ruta/sdcard/download/existe? Puede crearlo a través del shell adb –

Respuesta

35

¿no se están quedando sin memoria? Imagino que un archivo de video es muy grande, que está almacenando en el búfer antes de escribir en el archivo.

Sé que su código de ejemplo está en Internet, ¡pero es MALO para descargar! Utilice esto:

private final int TIMEOUT_CONNECTION = 5000;//5sec 
private final int TIMEOUT_SOCKET = 30000;//30sec 


      URL url = new URL(imageURL); 
      long startTime = System.currentTimeMillis(); 
      Log.i(TAG, "image download beginning: "+imageURL); 

      //Open a connection to that URL. 
      URLConnection ucon = url.openConnection(); 

      //this timeout affects how long it takes for the app to realize there's a connection problem 
      ucon.setReadTimeout(TIMEOUT_CONNECTION); 
      ucon.setConnectTimeout(TIMEOUT_SOCKET); 


      //Define InputStreams to read from the URLConnection. 
      // uses 3KB download buffer 
      InputStream is = ucon.getInputStream(); 
      BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5); 
      FileOutputStream outStream = new FileOutputStream(file); 
      byte[] buff = new byte[5 * 1024]; 

      //Read bytes (and store them) until there is nothing more to read(-1) 
      int len; 
      while ((len = inStream.read(buff)) != -1) 
      { 
       outStream.write(buff,0,len); 
      } 

      //clean up 
      outStream.flush(); 
      outStream.close(); 
      inStream.close(); 

      Log.i(TAG, "download completed in " 
        + ((System.currentTimeMillis() - startTime)/1000) 
        + " sec");5 
+2

agregó 'outStream.flush();' esto resuelve el problema de los archivos de 0 bytes –

+1

¿Es posible reproducir el video que se está descargando actualmente? Lo que significa que, digamos que one.mp4 se encuentra actualmente en estado de descarga, ¿es posible reproducir el mismo durante la descarga con MediaPlayer? – Scorpion

+0

@SomeoneSomewhere Tengo un video en formato .swf? ¿Se descargará usando tu código? – Dhasneem

23

Nunca instale una ruta, especialmente en el almacenamiento externo. Tu camino está mal en muchos dispositivos. Use Environment.getExternalStoragePath() para obtener la raíz del almacenamiento externo (que puede sea /sdcard o /mnt/sdcard o algo más).

Asegúrese de crear su subdirectorio, utilizando el objeto File que obtiene de Environment.getExternalStoragePath().

Y, finalmente, no solo diga "pero no funciona". No tenemos idea de qué significa "pero no funciona" en su caso. Sin esa información, es muy difícil ayudarte.

+0

Muchas gracias. Lo recordaré la próxima vez. –

Cuestiones relacionadas