2010-07-21 5 views

Respuesta

46

Primero debe asegurarse de que su aplicación tenga permiso para escribir en la tarjeta SD. Para hacer esto, debe agregar el permiso de usos escribir el almacenamiento externo en el archivo de manifiesto de la aplicación. Ver Setting Android Permissions

A continuación, puede usted puede descargar el URL de un archivo en la tarjeta sd. Una forma sencilla es:

URL url = new URL ("file://some/path/anImage.png"); 
InputStream input = url.openStream(); 
try { 
    //The sdcard directory e.g. '/sdcard' can be used directly, or 
    //more safely abstracted with getExternalStorageDirectory() 
    File storagePath = Environment.getExternalStorageDirectory(); 
    OutputStream output = new FileOutputStream (new File(storagePath,"myImage.png")); 
    try { 
     byte[] buffer = new byte[aReasonableSize]; 
     int bytesRead = 0; 
     while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) { 
      output.write(buffer, 0, bytesRead); 
     } 
    } finally { 
     output.close(); 
    } 
} finally { 
    input.close(); 
} 

EDIT: permiso Poner en el manifiesto

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
+1

@Paresh: Gracias, he actualizado el código para usar 'getExternalStorageDirectory()'. ¿Sabes si devuelve una barra final? p.ej. '/ sdcard' o'/sdcard/' – Akusete

+1

Su pregunta es discutible porque' Environment.getExternalStorageDirectory() 'no devuelve un' String' y, por lo tanto, su código no se compila. Corregí tu código por ti. –

+3

¿Qué es un tamaño razonable? –

8

Un excelente ejemplo se puede encontrar en el latest post en el blog de desarrolladores de Android:

static Bitmap downloadBitmap(String url) { 
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android"); 
    final HttpGet getRequest = new HttpGet(url); 

    try { 
     HttpResponse response = client.execute(getRequest); 
     final int statusCode = response.getStatusLine().getStatusCode(); 
     if (statusCode != HttpStatus.SC_OK) { 
      Log.w("ImageDownloader", "Error " + statusCode + 
       " while retrieving bitmap from " + url); 
      return null; 
     } 

     final HttpEntity entity = response.getEntity(); 
     if (entity != null) { 
      InputStream inputStream = null; 
      try { 
       inputStream = entity.getContent(); 
       final Bitmap bitmap = BitmapFactory.decodeStream(inputStream); 
       return bitmap; 
      } finally { 
       if (inputStream != null) { 
        inputStream.close(); 
       } 
       entity.consumeContent(); 
      } 
     } 
    } catch (Exception e) { 
     // Could provide a more explicit error message for IOException or 
     // IllegalStateException 
     getRequest.abort(); 
     Log.w("ImageDownloader", "Error while retrieving bitmap from " + url, 
      e.toString()); 
    } finally { 
     if (client != null) { 
      client.close(); 
     } 
    } 
    return null; 
} 
+4

Esto no describe cómo guardar la imagen en la tarjeta SD, solo cómo descargar la imagen en la memoria. –

+1

¿Cómo obtuvo esta respuesta 9 votos ascendentes?! ... –

Cuestiones relacionadas