Android Open Source - android-utils Photo Helper






From Project

Back to project page android-utils.

License

The source code is released under:

Apache License

If you think the Android project android-utils listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.omegar.android.utils;
// w w w  .j a  v  a  2 s  .c o  m
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

/**
 * Helper for taking photo from camera or other source (gallery, etc) and
 * processing incoming intent.
 */
public class PhotoHelper {
  private static final String FILE_PREFIX = "image_";
  private static final String IMAGE_EXTENSION = ".jpg";
  private static final String IMAGE_INTENT_TYPE = "image/*";

  @SuppressLint("InlinedApi")
  public static Uri dispatchTakePictureIntent(Activity activity,
      int requestCode, int chooserTitleResourceId) {
    Uri tempFileUri = null;

    if (isExternalStorageWritable()) {
      tempFileUri = createTempFile(activity);

      List<Intent> cameraIntents = getCameraIntents(activity, tempFileUri);

      Intent galleryIntent;
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        galleryIntent = new Intent(
            Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
      } else {
        galleryIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
      }
      galleryIntent.setType(IMAGE_INTENT_TYPE);

      Intent chooserIntent = Intent.createChooser(galleryIntent,
          activity.getString(chooserTitleResourceId));

      chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
          cameraIntents.toArray(new Parcelable[] {}));

      activity.startActivityForResult(chooserIntent, requestCode);
    }

    return tempFileUri;
  }

  private static List<Intent> getCameraIntents(Activity activity,
      Uri tempFileUri) {
    List<Intent> cameraIntents = new ArrayList<Intent>();

    Intent captureIntent = new Intent(
        android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

    if (activity != null) {
      PackageManager packageManager = activity.getPackageManager();
      List<ResolveInfo> listCam = packageManager.queryIntentActivities(
          captureIntent, PackageManager.MATCH_DEFAULT_ONLY);
      for (ResolveInfo res : listCam) {
        String packageName = res.activityInfo.packageName;
        Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(
            res.activityInfo.packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, tempFileUri);
        cameraIntents.add(intent);
      }
    }

    return cameraIntents;
  }

  private static boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
      return true;
    }
    return false;
  }

  private static Uri createTempFile(Activity activity) {
    String tempFileName = FILE_PREFIX
        + new Random().nextInt(Integer.MAX_VALUE) + IMAGE_EXTENSION;

    File tempFile = new File(
        activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES),
        tempFileName);

    return Uri.fromFile(tempFile);
  }

  @SuppressLint("NewApi")
  public static String getRealPathFromURI(final Context context, final Uri uri) {

    final boolean isKitKatOrHigher = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKatOrHigher && DocumentsContract.isDocumentUri(context, uri)) {
      // ExternalStorageProvider
      if (isExternalStorageDocument(uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        if ("primary".equalsIgnoreCase(type)) {
          return Environment.getExternalStorageDirectory() + "/"
              + split[1];
        }

        // TODO handle non-primary volumes
      }
      // DownloadsProvider
      else if (isDownloadsDocument(uri)) {

        final String id = DocumentsContract.getDocumentId(uri);
        final Uri contentUri = ContentUris.withAppendedId(
            Uri.parse("content://downloads/public_downloads"),
            Long.valueOf(id));

        return getDataColumn(context, contentUri, null, null);
      }
      // MediaProvider
      else if (isMediaDocument(uri)) {
        final String docId = DocumentsContract.getDocumentId(uri);
        final String[] split = docId.split(":");
        final String type = split[0];

        Uri contentUri = null;
        if ("image".equals(type)) {
          contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        } else if ("video".equals(type)) {
          contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        } else if ("audio".equals(type)) {
          contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }

        final String selection = "_id=?";
        final String[] selectionArgs = new String[] { split[1] };

        return getDataColumn(context, contentUri, selection,
            selectionArgs);
      }
    } // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
      // Return the remote address
      if (isGooglePhotosUri(uri))
        return uri.getLastPathSegment();

      return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
      return uri.getPath();
    }

    return null;
  }

  private static String getDataColumn(Context context, Uri uri,
      String selection, String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = { column };

    try {
      cursor = context.getContentResolver().query(uri, projection,
          selection, selectionArgs, null);
      if (cursor != null && cursor.moveToFirst()) {
        final int index = cursor.getColumnIndexOrThrow(column);
        return cursor.getString(index);
      }
    } finally {
      if (cursor != null)
        cursor.close();
    }
    return null;
  }

  private static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri
        .getAuthority());
  }

  private static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri
        .getAuthority());
  }

  private static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri
        .getAuthority());
  }

  private static boolean isGooglePhotosUri(Uri uri) {
    return "com.google.android.apps.photos.content".equals(uri
        .getAuthority());
  }

  public static void clearPhotosDirectory(Activity activity) {
    if (isExternalStorageWritable()) {
      File dir = activity
          .getExternalFilesDir(Environment.DIRECTORY_PICTURES);
      File[] files = dir.listFiles();
      if (files != null) {
        for (File file : files) {
          file.delete();
        }
      }
    }
  }

  public static Uri processTakingPhotoIntent(Intent data, Uri photoUri) {
    boolean isCamera = true;
    if (data != null) {
      String action = data.getAction();
      isCamera = (action == null) ? false : action
          .equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    }

    if (!isCamera) {
      photoUri = data == null ? null : data.getData();
    }

    return photoUri;
  }
}




Java Source Code List

com.omegar.android.utils.BaseDialog.java
com.omegar.android.utils.Logger.java
com.omegar.android.utils.PhotoHelper.java
com.omegar.android.utils.components.DividedLinearLayout.java
com.omegar.android.utils.components.NetworkImageView.java
com.omegar.android.utils.components.NonScrollableGridView.java
com.omegar.android.utils.components.NonScrollableListView.java
com.omegar.android.utils.components.ProportionalLinearLayout.java
com.omegar.android.utils.components.UnderlineTextView.java