Skip to main content

Command Palette

Search for a command to run...

How to Implement the Android Photo Picker in Your App

Updated
4 min read
How to Implement the Android Photo Picker in Your App
E

Software Engineer | Content Creator

Google introduced the Photo Picker in Android 13 to make photo and video selection easier and more secure. It allows users to select media files directly from their device’s library, and the best part is it offers better privacy by letting users share photos and videos without giving apps broad access to storage.

Let’s dive into how to implement this useful feature in your Android app.

Why Use Android’s Photo Picker?

  • User-friendly: Offers a familiar and consistent media-picking interface.

  • Privacy-focused: Users can select only the files they want to share.

  • Easy Integration: Provides an efficient way to handle image selection without extensive permission management.

Prerequisites

Before you begin, make sure you have:

  1. Android Studio: Ensure you’re using the latest version.

  2. Android API Level 33 or above in your app’s configuration.

  3. Android SDK updated to API Level 33.

Step 1: Update Your Project’s Configuration

In your build.gradle file, make sure your compileSdkVersion and targetSdkVersion are at least 33, as the photo picker is available from API level 33 (Android 13).

android {
    compileSdk 33

    defaultConfig {
        targetSdk 33
        ...
    }
}

Step 2: Create the UI for Your Photo Picker

To keep things simple, let’s add a button that triggers the photo picker when clicked.

In your activity_main.xml, add:

<Button
    android:id="@+id/btnSelectPhoto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select Photo" />

Step 3: Launch the Photo Picker Intent

The Android Photo Picker is triggered by an intent. Here’s how to launch it when the button is clicked.

In your MainActivity.kt:

import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    private val pickMedia = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri: Uri? ->
        if (uri != null) {
            handleImageUri(uri)
        } else {
            Toast.makeText(this, "No image selected", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val btnSelectPhoto = findViewById<Button>(R.id.btnSelectPhoto)
        btnSelectPhoto.setOnClickListener {
            openPhotoPicker()
        }
    }

    private fun openPhotoPicker() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            pickMedia.launch(ActivityResultContracts.PickVisualMedia.ImageOnly)
        } else {
            Toast.makeText(this, "Photo Picker requires Android 13+", Toast.LENGTH_SHORT).show()
        }
    }

    private fun handleImageUri(uri: Uri) {
        // Handle the URI, such as displaying the selected image in an ImageView or storing it.
    }
}

Explanation of the Code

  1. pickMedia: This registers the activity result contract for the media picker. ActivityResultContracts.PickVisualMedia is designed specifically for picking media.

  2. openPhotoPicker(): This function checks if the device’s Android version is TIRAMISU (Android 13) or higher before launching the picker.

  3. handleImageUri(uri: Uri): This method handles the selected image URI. Here, you could display it in an ImageView or process it further based on your app's needs.

Step 4: Handle the Selected Image URI

To display the selected image, let’s add an ImageView in activity_main.xml and update the handleImageUri function to display the image.

In activity_main.xml:

<ImageView
    android:id="@+id/selectedImage"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/btnSelectPhoto"
    android:layout_marginTop="16dp" />

In MainActivity.kt, update handleImageUri to display the image:

private fun handleImageUri(uri: Uri) {
    val imageView = findViewById<ImageView>(R.id.selectedImage)
    imageView.setImageURI(uri)
}

Now, when an image is selected, it will be displayed in the ImageView.

Step 5: Testing the Photo Picker

To test the functionality:

  1. Run your app on an Android 13 device or emulator.

  2. Click the "Select Photo" button.

  3. Choose an image from the gallery when the picker opens.

  4. Verify that the selected image appears in the ImageView.

Advanced Customizations

The Android Photo Picker can be customized to select both images and videos or limit the selection count. Here’s how you can implement these advanced customizations:

Selecting Both Photos and Videos

To let users select both images and videos, use ActivityResultContracts.PickVisualMedia.ImageAndVideo:

pickMedia.launch(ActivityResultContracts.PickVisualMedia.ImageAndVideo)

Limiting the Selection Count

For scenarios where multiple selections are needed, use ActivityResultContracts.PickMultipleVisualMedia:

private val pickMultipleMedia = registerForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(5)) { uris: List<Uri> ->
    // Handle the list of selected URIs
}

In this example, users can select up to 5 items.

Wrapping Up

Implementing the Android Photo Picker adds a more secure and consistent way for users to select media in your app. Its simplicity in handling permissions and privacy considerations makes it a great tool for modern Android apps.

Key Benefits Recap

  • Privacy-first: Users only share what they choose.

  • Simple implementation: Reduces the need for complex permission handling.

  • Future-ready: The API is continually being improved for performance and security.

Now you’re ready to implement the Android Photo Picker in your app! This feature provides a polished user experience with minimal code, allowing you to focus on building the core functionality of your app.

Happy coding! 🚀