download image and save to External Media - Android android.os

Android examples for android.os:External Storage

Description

download image and save to External Media

Demo Code

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import android.content.Context;
import android.net.Uri;
import android.webkit.MimeTypeMap;

public class Main {

  public static Uri downloadExternalMedia(Context context, Uri imageUri) {
    if (context == null || imageUri == null) {
      return null;
    }/* w  w  w  . j  av a  2s.  co m*/
    File cacheDir = null;

    String mimeType = context.getContentResolver().getType(imageUri);
    boolean isVideo = (mimeType != null && mimeType.contains("video"));

    // If the device has an SD card
    if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
      String mediaFolder = isVideo ? "video" : "images";
      cacheDir = new File(android.os.Environment.getExternalStorageDirectory() + "/WordPress/" + mediaFolder);
    } else {
      if (context.getApplicationContext() != null) {
        cacheDir = context.getApplicationContext().getCacheDir();
      }
    }

    if (cacheDir != null && !cacheDir.exists()) {
      cacheDir.mkdirs();
    }
    try {
      InputStream input;
      // Download the file
      if (imageUri.toString().startsWith("content://")) {
        input = context.getContentResolver().openInputStream(imageUri);
        if (input == null) {
          return null;
        }
      } else {
        input = new URL(imageUri.toString()).openStream();
      }

      String fileName = "wp-" + System.currentTimeMillis();
      if (isVideo) {
        fileName += "." + MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
      }

      File f = new File(cacheDir, fileName);

      OutputStream output = new FileOutputStream(f);

      byte data[] = new byte[1024];
      int count;
      while ((count = input.read(data)) != -1) {
        output.write(data, 0, count);
      }

      output.flush();
      output.close();
      input.close();

      return Uri.fromFile(f);
    } catch (Exception e) {
    }

    return null;
  }

}

Related Tutorials