SoFunction
Updated on 2025-04-04

Share two ways to achieve Android image selection

Two ways to select pictures from Android:

The first type: single selection

By implicitly launching activity, jump to the album and select a picture to return to the result

The key code is as follows:

Send a request:

private static final int PICTURE = 10086; //requestcode

Intent intent = new Intent();
if (.SDK_INT < 19) {//Because the image action changed after version 4.4 of the Android SDK, so let's make a judgment here first      (Intent.ACTION_GET_CONTENT);
    } else {
      (Intent.ACTION_OPEN_DOCUMENT);
    }
    ("image/*");
    (Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, PICTURE);

Received results:

@Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data == null) {
      ();
      return;
    }
    Uri uri = ();
    switch (requestCode) {
      case PICTURE:
        image = (this, uri); // (Because the image uri has changed after 4.4) Use the file tool class to parse the uri to get the image path        break;
      default:
        break;
    }
    ();
  }

File tool class:

public class FileUtils {
  private static final String TAG = "FileUtils";
  private static final boolean DEBUG = false;
  /**
    * Get the readable file size
    */
  public static String getReadableFileSize(int size) {
    final int BYTES_IN_KILOBYTES = 1024;
    final DecimalFormat dec = new DecimalFormat("###.#");
    final String KILOBYTES = " KB";
    final String MEGABYTES = " MB";
    final String GIGABYTES = " GB";
    float fileSize = 0;
    String suffix = KILOBYTES;
    if(size > BYTES_IN_KILOBYTES) {
      fileSize = size / BYTES_IN_KILOBYTES;
      if(fileSize > BYTES_IN_KILOBYTES) {
        fileSize = fileSize / BYTES_IN_KILOBYTES;
        if(fileSize > BYTES_IN_KILOBYTES) {
          fileSize = fileSize / BYTES_IN_KILOBYTES;
          suffix = GIGABYTES;
        } else {
          suffix = MEGABYTES;
        }
      }
    }
    return ((fileSize) + suffix);
  }
  /**
    * Get the file name (excluding extension)
    */
  public static String getFileNameWithoutExtension(String path) {
    if(path == null) {
      return null;
    }
    int separatorIndex = ();
    if(separatorIndex < 0) {
      separatorIndex = 0;
    }
    int dotIndex = (".");
    if(dotIndex < 0) {
      dotIndex = ();
    } else if(dotIndex < separatorIndex) {
      dotIndex = ();
    }
    return (separatorIndex + 1, dotIndex);
  }
  /**
    * Get the file name
    */
  public static String getFileName(String path) {
    if(path == null) {
      return null;
    }
    int separatorIndex = ();
    return (separatorIndex < 0) ? path : (separatorIndex + 1, ());
  }
  /**
    * Get the extension
    */
  public static String getExtension(String path) {
    if(path == null) {
      return null;
    }
    int dot = (".");
    if(dot >= 0) {
      return (dot);
    } else {
      return "";
    }
  }
  public static File getUriFile(Context context, Uri uri) {
    String path = getUriPath(context, uri);
    if(path == null) {
      return null;
    }
    return new File(path);
  }
  public static String getUriPath(Context context, Uri uri) {
    if(uri == null) {
      return null;
    }
    if(.SDK_INT >= Build.VERSION_CODES.KITKAT && (context, uri)) {
      if("".equals(())) {
        final String docId = (uri);
        final String[] split = (":");
        final String type = split[0];
        if("primary".equalsIgnoreCase(type)) {
          return () + "/" + split[1];
        }
      } else if("".equals(())) {
        final String id = (uri);
        final Uri contentUri = (("content://downloads/public_downloads"), (id));
        return getDataColumn(context, contentUri, null, null);
      } else if("".equals(())) {
        final String docId = (uri);
        final String[] split = (":");
        final String type = split[0];
        Uri contentUri = null;
        if("image".equals(type)) {
          contentUri = .EXTERNAL_CONTENT_URI;
        } else if("video".equals(type)) {
          contentUri = .EXTERNAL_CONTENT_URI;
        } else if("audio".equals(type)) {
          contentUri = .EXTERNAL_CONTENT_URI;
        }
        final String selection = "_id=?";
        final String[] selectionArgs = new String[] {split[1]};
        return getDataColumn(context, contentUri, selection, selectionArgs);
      }
    } else if("content".equalsIgnoreCase(())) {
      if("".equals(())) {
        return ();
      }
      return getDataColumn(context, uri, null, null);
    } else if("file".equalsIgnoreCase(())) {
      return ();
    }
    return null;
  }
  public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {column};
    try {
      cursor = ().query(uri, projection, selection, selectionArgs, null);
      if(cursor != null && ()) {
        final int column_index = (column);
        return (column_index);
      }
    } finally {
      if(cursor != null) ();
    }
    return null;
  }
}

The second method: batch selection of pictures

If we need to select multiple pictures at a time similar to WeChat, it is obvious that the first method is to not meet the needs, so how can we select them in batches? andorid also provides a direct method of batch selection like single selection, so we can only obtain it from the database ourselves.

First of all, we need to understand a class mediastore. All multimedia files in android are stored in this database, such as pictures, videos, audios, etc. It provides data interface to other processes through contentprovider.

To get data from mediastore, we can use the ContentResolver corresponding to ContentProvider

Key Code:

 final String[] projectionPhotos = {
        ._ID,// ID of each column The ID of the picture        .BUCKET_ID,//The folder ID of the picture is located        .BUCKET_DISPLAY_NAME,//The folder name of the picture is located        ,//Picture path        .DATE_TAKEN,//Image creation time    };

 
cursor = ((), .EXTERNAL_CONTENT_URI
    , projectionPhotos, "", null, .DATE_TAKEN + " DESC");

All pictures are in the cursor and then take them out of the cursor