SoFunction
Updated on 2025-04-07

Android calls system album to select photos

Preface

Selecting pictures in the album is also a very common function, such as WeChat Moments, etc. But they are custom selectors that can select multiple images and modify them. Here we talk about the simplest thing: call the system's album to select a picture and display it. In addition, some readers also think of the function of selecting pictures through the camera, so you can also refer to another article of mine.Android uses the system camera to take photos

Steps to use

Here I will explain how to implement this function through a simple demo. First look at the layout:

 <Button
  android:
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginTop="5dp"
  android:layout_marginEnd="52dp"
  android:layout_marginRight="52dp"
  android:text="choose"
  app:layout_constraintEnd_toEndOf="parent"
  app:layout_constraintTop_toTopOf="parent" />

 <ImageView
  android:
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_marginTop="29dp"
  app:layout_constraintEnd_toEndOf="parent"
  app:layout_constraintStart_toStartOf="parent"
  app:layout_constraintTop_toBottomOf="@+id/button"
  app:srcCompat="@mipmap/ic_launcher_round" />

It's very simple, it's a button and an imageView. Then let's think about how to implement this function:

First, open the album, then you must implicitly start the album activity; then the album returns to a path, and we will use this path to display the corresponding photos on the path. The idea is quite simple, let's write:
First look at the code:

 private Uri imageUri;
 private ImageView imageView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView(.activity_main);
  imageView = findViewById();
  Button button1 = findViewById(.button2);
  (new () {
   @Override
   public void onClick(View v) {
   //Dynamic application permission    if ((,
      .WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
     (,new String[]{.WRITE_EXTERNAL_STORAGE},1);
    }else{
    //Execute the method to start the album     openAlbum();
    }
   }
  });
  }
//Result of obtaining permission@Override
 public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  if (requestCode == 1){
   if (&gt;0&amp;&amp;grantResults[0] == PackageManager.PERMISSION_GRANTED) openAlbum();
   else (,"You refused",Toast.LENGTH_SHORT).show();
  }
 }

//How to start the albumprivate void openAlbum(){
  Intent intent = new Intent(".GET_CONTENT");
  ("image/*");
  startActivityForResult(intent,2);
 }

Here we initialize the control first, and then apply for permissions dynamically, because we must read the photos, we must read the permissions in memory. Remember to write permissions in AndroidManifest:

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

After obtaining permission, open the album and select it. The corresponding action of the album is .GET_CONTENT, setType("image/*") This method indicates that all photos are displayed and then the activity is enabled. After starting the activity and selecting the photo, an intent will be returned to the onActivityResult method, so the main task next is to get the returned path.

We know that after Android 4.4, the real path of the file cannot be directly used to other applications, so the returned uri is encapsulated, so we need to parse and retrieve the path inside. So here we need to judge the Android version to perform different logic, first look at the code:

@Override
 protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
 if (requestCode == 2){
 //Judge Android version    if (resultCode == RESULT_OK&amp;&amp;data!=null){
    if (.SDK_INT&gt;=19)
    handImage(data);
    else handImageLow(data);
   }
  }
 }

//How to deal with Android version greater than 4.4@RequiresApi(api = Build.VERSION_CODES.KITKAT)
 private void handImage(Intent data){
  String path =null;
  Uri uri = ();
  //Different analysis according to different uri  if ((this,uri)){
   String docId = (uri);
   if ("".equals(())){
    String id = (":")[1];
    String selection = ._ID+"="+id;
    path = getImagePath(.EXTERNAL_CONTENT_URI,selection);
   }else if("".equals(())){
    Uri contentUri = (("content://downloads/public_downloads"),(docId));
    path = getImagePath(contentUri,null);
   }
  }else if ("content".equalsIgnoreCase(())){
   path = getImagePath(uri,null);
  }else if ("file".equalsIgnoreCase(())){
   path = ();
  }
  //Show pictures  displayImage(path);
 }


//How to deal with Android less than 4.4private void handImageLow(Intent data){
  Uri uri = ();
  String path = getImagePath(uri,null);
  displayImage(path);
 }

// Method for obtaining image path of uri of content typeprivate String getImagePath(Uri uri,String selection) {
  String path = null;
  Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
  if (cursor!=null){
   if (()){
    path = (());
   }
   ();
  }
  return path;
 }

//How to display pictures according to the pathprivate void displayImage(String imagePath){
  if (imagePath != null){
   Bitmap bitmap = (imagePath);
   (bitmap);
  }else{
   (this,"fail to set image",Toast.LENGTH_SHORT).show();
  }
 }

There are a lot of codes above, but don’t panic. Let’s come one by one, it’s not difficult to understand. First of all, we know that different versions have two different ways to display images, namely: handImage and handImageLow. The uri of content type can be used to obtain the real path through the getImagePath method, and the real path can be displayed through the displayImage method. So the main job is how to get the real path. Now that the idea is clear, let's take a look one by one:

First, let’s take a look at two tool methods: getImagePath and displayImage.

  • getImagePath After learning content providers, you will know that this is to get data through content providers. Get a Cursor object through this uri and selection. What is Cursor? Readers who don't know can check out this blog Cursor in Android. Then, through this parameter of this Cursor object, you can get the real path.
  • The displayImage method collects a real path string, and directly obtains it to the Bitmap through this method and then displays it.

After understanding the tool method, our purpose is very clear: content type uri or real path String.
First of all, the version is lower than 4.4, because the return is the real uri, which is the one at the beginning of the content, so you can directly obtain the real path through getImagePath and then display it through displayImage.

This next one may seem a bit of a headache because you want to parse different types of Uri. Let's look at it one by one:

  • The first is a document type uri. As for what is a document type uri, I won’t go into it here. As long as you know there is this type of uri, how to deal with it. First we need to get a DocumentId, and then we will process it in two cases:

The first one is media format, and then we have to take out the second half of the string before we can get the real id. Here the real id refers to the id in the corresponding database table, which is used for selection. .EXTERNAL_CONTENT_URI is the content type uri of this photo, and then put the selection in it.
The second method can obtain the content type uri through this method. This method is responsible for connecting the id and contentUri into a new Uri. This method will not be explained in detail here.

  • The second type is content type, so it's fine to use it directly
  • The third type is file type, which is the real path, and you can get it by getting it directly by gettingPath.

OK, all our questions will be resolved here.

summary

After reading it, do you find that the idea is simple but there are many blind spots in knowledge that can be realized? That's true. But when we solve all these details, we will learn a lot, which is equivalent to taking the point to lead the whole. There are many more that are not explained in detail in the article:
ContentUris, BitmapFactory, Cursor, DocumentsContract, and more. Because this is another relatively large part of content, if you want to talk about it, it will easily deviate from our topic, so just know what it is.

References

"The First Line of Code" Guo Lin

The above is the detailed content of selecting photos for Android calling system albums. For more information about Android calling system albums, please follow my other related articles!