Photo gallery with paging and permissions

Build an Android photo gallery with the photo picker, MediaStore, Paging 3, Coil and LazyVerticalGrid, handling Android 13 and 14 media permissions. About 30 hours.

What you will build

The finished app has two ways to show photos. A "Pick photos" button opens the system photo picker, which needs no permission. A "Gallery" tab shows every image on the device in a scrolling grid, read from MediaStore and loaded page by page with Paging 3. Tapping a photo opens a full-screen detail screen.

The gallery tab needs storage permissions, and they differ by Android version. On Android 13 and higher the app asks for READ_MEDIA_IMAGES. On Android 12 and lower it asks for READ_EXTERNAL_STORAGE. On Android 14 and higher the user can choose "Select photos", which grants READ_MEDIA_VISUAL_USER_SELECTED instead. Then MediaStore returns only the photos the user chose, and the app must show them and offer a way to select more.

Start with the picker. Google recommends the photo picker for most apps, because it gives the user control and the app needs no permission. Build the full gallery only because a gallery app really needs to browse the whole library, and because it teaches you MediaStore, Paging and permissions.

This project proves you can work with a system content provider, page a large local data set, load images at the right size, and measure scrolling with real tools.

Skills you practise

  • The photo picker with PickVisualMedia and PickMultipleVisualMedia
  • Media permissions on Android 12, 13 and 14+, including partial access
  • MediaStore queries with ContentResolver, projections, sort order, limit and offset
  • A custom Paging 3 PagingSource that reloads when MediaStore changes
  • Coil 3 AsyncImage in a LazyVerticalGrid with keys and content types
  • UI tests, a Macrobenchmark scroll test and a Baseline Profile

Architecture

The app has a data layer and a UI layer. A domain layer is optional at this size.

The data layer has a MediaStorePagingSource that queries MediaStore.Images through ContentResolver, one page at a time. A PhotoRepository builds the Pager and returns Flow<PagingData<Photo>>. ContentResolver.query() is a blocking call, so the paging source runs it with withContext on an injected IO dispatcher. Tests can swap that dispatcher for a test one.

The UI layer has a GalleryViewModel with two separate outputs. photos: Flow<PagingData<Photo>> comes from the repository with cachedIn(viewModelScope), so rotation does not reload from scratch. uiState: StateFlow<GalleryUiState> holds everything else, such as the media access state (full, partial or denied). PagingData stays out of the UiState class, as in the infinite image feed system design round. The screen collects the paging flow with collectAsLazyPagingItems().

Permissions can change while the app is in the background, for example from Settings. So the screen re-checks the access state each time it resumes, and the gallery refreshes. The app never stores the permission state in preferences.

Module or layerResponsibility
Photo modelid, content uri, display name and date added. The id is the MediaStore _ID.
MediaStorePagingSourceQueries one page of images with limit and offset, maps cursor rows to Photo, and invalidates itself when MediaStore changes.
PhotoRepositoryBuilds Pager(PagingConfig(...)) { MediaStorePagingSource(...) } and exposes its flow.
GalleryViewModelphotos with cachedIn(viewModelScope) and a separate StateFlow<GalleryUiState> for access state.
UIPicker button, permission screen, LazyVerticalGrid of AsyncImage, detail screen with a type-safe route.
TestsPaging source tests, Compose UI tests, a benchmark module with Macrobenchmark and Baseline Profile tests.

Milestones

1. Project setup and the photo picker

Show photos the user picks, with no permission at all.

  1. Create a Compose project with minSdk 26 or higher. Add Hilt, Paging (paging-runtime and paging-compose), Navigation Compose, and Coil 3 (io.coil-kt.coil3:coil-compose). Coil loads content:// URIs without a network artifact.
  2. Register rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()). Launch it with PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly).
  3. Show the returned List<Uri> in a small row of AsyncImage. Keep the URIs in a ViewModel so they survive rotation.
  4. Read the availability rules: the picker runs on Android 11 (API 30) and higher with Google System Updates. Older devices that support Google Play services can get a backported picker if you add the ModuleDependencies service entry from the docs to your manifest. Where no picker is available, the Activity library falls back to ACTION_OPEN_DOCUMENT.
  5. Note that access to picked URIs is temporary. Call takePersistableUriPermission only if you must keep a URI after a restart.

Done when: You can pick several images on an API 33+ emulator and see them, the app declares no storage permission yet, and the picked photos survive rotation.

Lessons: Runtime permissions, ViewModel and UI state

2. Media permissions: full, partial and denied

Ask for the right permission on each Android version and model the result as state.

  1. In the manifest, declare READ_EXTERNAL_STORAGE with android:maxSdkVersion="32", READ_MEDIA_IMAGES, and READ_MEDIA_VISUAL_USER_SELECTED.
  2. Use ActivityResultContracts.RequestMultiplePermissions(). On API 34+ request READ_MEDIA_IMAGES and READ_MEDIA_VISUAL_USER_SELECTED together. On API 33 request READ_MEDIA_IMAGES. On API 32 and lower request READ_EXTERNAL_STORAGE.
  3. Write a checkMediaAccess(context) function that returns Full, Partial or Denied with ContextCompat.checkSelfPermission. Check READ_MEDIA_IMAGES first (API 33+), then READ_MEDIA_VISUAL_USER_SELECTED (API 34+), then READ_EXTERNAL_STORAGE (API 32 and lower).
  4. Re-check on every resume with LifecycleEventEffect(Lifecycle.Event.ON_RESUME) and push the result into GalleryUiState.
  5. For Partial, show a banner "Showing selected photos" with a "Select more" button. The button simply launches the same permission request again, which opens the system's selection dialog.
  6. For Denied, show an explanation, a button to request again, and, after a permanent denial, a button that opens the app's settings page.

Done when: On an API 34+ emulator, "Allow all" gives Full, "Select photos" gives Partial, and "Don't allow" gives Denied. Changing the choice in Settings and returning to the app updates the state without a restart. On an API 32 emulator the app asks for READ_EXTERNAL_STORAGE.

Lessons: Runtime permissions, Side effects: LaunchedEffect and friends, The manifest and app components

3. MediaStore PagingSource

Load the image library one page at a time.

  1. Pick the collection URI: MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL) on API 29+, MediaStore.Images.Media.EXTERNAL_CONTENT_URI below that.
  2. Query only the columns you need (_ID, DISPLAY_NAME, DATE_ADDED), sorted by DATE_ADDED DESC, _ID DESC. The _ID tie-break keeps the order stable when several photos share a timestamp.
  3. Page with limit and offset. On API 30+ pass a Bundle with QUERY_ARG_SQL_SORT_ORDER, QUERY_ARG_LIMIT and QUERY_ARG_OFFSET to query(uri, projection, queryArgs, cancellationSignal). On older versions, add LIMIT and OFFSET to the sort order string.
  4. Build each item's URI with ContentUris.withAppendedId(collection, id).
  5. Run the query with withContext(ioDispatcher). Catch only SecurityException (access revoked) and return LoadResult.Error. Do not catch Exception, because that also catches CancellationException.
  6. Implement getRefreshKey so a refresh starts around the item the user was looking at.
  7. Register a ContentObserver on the collection and call invalidate() when it fires. Unregister it in registerInvalidatedCallback. Pager then creates a fresh paging source.
  8. In the repository, return Pager(PagingConfig(pageSize = 60)) { MediaStorePagingSource(resolver, ioDispatcher) }.flow. The page size is a starting point; tune it after testing.

Done when: A test or a log shows that the first load returns only one page (not the whole library), scrolling loads further pages with no duplicates, and taking a new photo with the camera app makes it appear at the top of the gallery.

Lessons: Paging 3, Dispatchers and threading, Exception handling in coroutines, Repository pattern

4. The photo grid with Coil

Show the paged photos in a smooth grid.

  1. In the ViewModel, expose val photos = repository.photos().cachedIn(viewModelScope).
  2. In the screen, call collectAsLazyPagingItems() and render a LazyVerticalGrid(columns = GridCells.Adaptive(minSize = 96.dp)).
  3. Use items(count = photos.itemCount, key = photos.itemKey { it.id }, contentType = photos.itemContentType { "photo" }). The MediaStore _ID is a stable, unique key.
  4. Give each cell a bounded size with Modifier.aspectRatio(1f) and use AsyncImage(model = photo.uri, contentScale = ContentScale.Crop). Coil reads the size from the layout constraints and decodes a downsampled bitmap, not the full camera image.
  5. Show a placeholder for null items, and use loadState.refresh for the first-load spinner and the empty state ("No photos on this device").
  6. When the access state changes on resume, call photos.refresh(), because partial access changes which rows MediaStore returns.

Done when: With a few thousand images on the emulator, a fast fling shows no blank grid for long, rotation keeps the scroll position, and the Memory Profiler shows no steady growth while you scroll up and down.

Lessons: Lists with LazyColumn, Performance: lists and deferred reads, Design an image loading library

5. Detail screen

Open a full-screen view of the tapped photo.

  1. Add a type-safe route, @Serializable data class PhotoDetail(val id: Long), and navigate to it on tap.
  2. In the detail screen, rebuild the URI from the id with ContentUris.withAppendedId. Pass the id, not the whole Photo object.
  3. Load the image with AsyncImage and ContentScale.Fit. Coil still limits the decode to the screen size.
  4. Handle a missing photo: if the user deleted it or partial access no longer includes it, show an error state instead of crashing.

Done when: Tapping a thumbnail opens the same photo full screen, back returns to the same scroll position, and the detail screen survives rotation and process death (test with "Don't keep activities" or adb shell am kill).

Lessons: Navigation in Compose, SavedStateHandle and process death

6. Tests and performance

Prove the gallery works and scrolls well.

  1. Unit test the paging source with TestPager from paging-testing against a fake data source, or as an instrumented test against MediaStore with seeded images.
  2. Write Compose UI tests for the permission screens. Use GrantPermissionRule for the granted path and test the denied UI by feeding state to the screen composable directly.
  3. Add a benchmark module (the Android Studio Baseline Profile template creates one). Seed the emulator with a few hundred images, and grant the permission in the setupBlock with device.executeShellCommand("pm grant <package> android.permission.READ_MEDIA_IMAGES").
  4. Write a Macrobenchmark with MacrobenchmarkRule.measureRepeated and FrameTimingMetric() that flings the grid several times.
  5. Generate a Baseline Profile with BaselineProfileRule.collect() that starts the app and scrolls the grid, using the androidx.baselineprofile Gradle plugin.
  6. Compare frame timings with and without the profile (CompilationMode.None() against CompilationMode.Partial()), and open a Perfetto trace for the slowest frames.

Done when: The UI tests pass, the benchmark runs on a physical device or emulator and reports frame timings, and you can show before and after numbers for the Baseline Profile from your own runs.

Lessons: Compose UI tests, App startup and Baseline Profiles, Jank, frames and Perfetto, Memory leaks and LeakCanary

Key code

data class Photo(val id: Long, val uri: Uri, val name: String, val dateAdded: Long)
 
private val collection: Uri =
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
        MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)
    } else {
        MediaStore.Images.Media.EXTERNAL_CONTENT_URI
    }
 
class MediaStorePagingSource(
    private val resolver: ContentResolver,
    private val ioDispatcher: CoroutineDispatcher,
) : PagingSource<Int, Photo>() {
 
    private val observer = object : ContentObserver(null) {
        override fun onChange(selfChange: Boolean) = invalidate()
    }
 
    init {
        resolver.registerContentObserver(collection, true, observer)
        registerInvalidatedCallback { resolver.unregisterContentObserver(observer) }
    }
 
    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Photo> {
        // Refresh and Append keys are the first row of the page.
        // A Prepend key is the row where the page must end, so pages never overlap.
        val start: Int
        val size: Int
        if (params is LoadParams.Prepend) {
            start = maxOf(0, params.key - params.loadSize)
            size = params.key - start
        } else {
            start = params.key ?: 0
            size = params.loadSize
        }
        return try {
            val photos = withContext(ioDispatcher) { queryPage(start, size) }
            LoadResult.Page(
                data = photos,
                prevKey = if (start == 0) null else start,
                nextKey = if (photos.size < size) null else start + photos.size,
            )
        } catch (e: SecurityException) {
            LoadResult.Error(e) // permission revoked while the app was running
        }
    }
 
    override fun getRefreshKey(state: PagingState<Int, Photo>): Int? =
        state.anchorPosition?.let { anchor ->
            maxOf(0, anchor - state.config.initialLoadSize / 2)
        }
 
    private fun queryPage(offset: Int, limit: Int): List<Photo> {
        val projection = arrayOf(
            MediaStore.Images.Media._ID,
            MediaStore.Images.Media.DISPLAY_NAME,
            MediaStore.Images.Media.DATE_ADDED,
        )
        val order = "${MediaStore.Images.Media.DATE_ADDED} DESC, ${MediaStore.Images.Media._ID} DESC"
        val cursor = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val args = Bundle().apply {
                putString(ContentResolver.QUERY_ARG_SQL_SORT_ORDER, order)
                putInt(ContentResolver.QUERY_ARG_LIMIT, limit)
                putInt(ContentResolver.QUERY_ARG_OFFSET, offset)
            }
            resolver.query(collection, projection, args, null)
        } else {
            resolver.query(collection, projection, null, null, "$order LIMIT $limit OFFSET $offset")
        }
        return cursor?.use { c ->
            val idCol = c.getColumnIndexOrThrow(MediaStore.Images.Media._ID)
            val nameCol = c.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME)
            val dateCol = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_ADDED)
            buildList {
                while (c.moveToNext()) {
                    val id = c.getLong(idCol)
                    add(
                        Photo(
                            id = id,
                            uri = ContentUris.withAppendedId(collection, id),
                            name = c.getString(nameCol).orEmpty(),
                            dateAdded = c.getLong(dateCol),
                        )
                    )
                }
            }
        } ?: emptyList()
    }
}
  • The blocking query() runs on the injected IO dispatcher, and cursor.use closes the cursor even if mapping throws.
  • Only SecurityException is caught, so cancellation still propagates when the user leaves the screen.
  • The prepend branch matters. If a prepend page overlapped the page after it, the same _ID would appear twice and LazyVerticalGrid would crash on the duplicate key.
  • The ContentObserver turns any MediaStore change (new photo, deletion, a new partial selection) into invalidate(). Paging then builds a new source and reloads around getRefreshKey.
  • DATE_ADDED is set for every row. DATE_TAKEN comes from metadata and can be missing, which makes it a weak sort key.

Pitfalls

  • Building a gallery when the picker would do. If users only need to choose a few photos (a profile picture, an attachment), the photo picker needs no permission and has no partial-access states to handle. Ask for media permissions only when the app really browses the library.
  • Querying all images at once. Reading every row into a list before showing anything is slow on large libraries and holds everything in memory. Page with limit and offset in a PagingSource.
  • Relying on LIMIT in the sort order everywhere. Adding LIMIT to the sort order string is an old workaround, and newer MediaStore versions may reject it. Use the Bundle with QUERY_ARG_LIMIT and QUERY_ARG_OFFSET on API 30 and higher, and keep the string workaround only for older versions.
  • Treating partial access as denied. On Android 14+, "Select photos" grants READ_MEDIA_VISUAL_USER_SELECTED, not READ_MEDIA_IMAGES. If the app checks only READ_MEDIA_IMAGES, it shows a "permission denied" screen while MediaStore would return the selected photos. Model full, partial and denied as three states.
  • Caching the permission result. The user can change access in Settings while the app is in the background. Re-check on every resume and refresh the paging data.
  • Catching Exception in load(). It turns CancellationException into a LoadResult.Error. Catch SecurityException only.
  • Duplicate keys in the grid. Overlapping pages, or offsets that shift when a photo is added between two loads, put the same id twice into the list, and LazyVerticalGrid throws on duplicate keys. Use non-overlapping prepend loads and invalidate the source when MediaStore changes.
  • Loading full-resolution images in the grid. A 12-megapixel photo decoded at full size for a 100 dp cell wastes memory and causes GC pauses and jank. Give each cell a bounded size so Coil downsamples. On API 29+ you can also fetch a system thumbnail with ContentResolver.loadThumbnail(uri, size, signal).
  • Putting PagingData inside UiState. Keep photos as its own flow with cachedIn(viewModelScope) and keep access state in UiState. Creating the Pager in a composable reloads everything after rotation.

Code review finding

The 'empty gallery' bug on Android 14
  • The user chose "Select photos" in the permission dialog.
  • The app checked only READ_MEDIA_IMAGES, which is not granted for partial access, so it showed the "Permission denied" screen and never queried MediaStore.
  • Later the user changed the choice in Settings, but the app had stored "denied" in DataStore, so the gallery stayed empty until a reinstall.
The fix
  • Declare READ_MEDIA_VISUAL_USER_SELECTED and request it together with READ_MEDIA_IMAGES on API 34+.
  • Model access as Full, Partial or Denied, and query MediaStore for both Full and Partial. MediaStore itself limits the rows to what the user selected.
  • In Partial, show "Showing selected photos" and a "Select more" button that launches the same permission request again.
  • Remove the stored permission state. Re-check with checkSelfPermission on every resume and call refresh() on the paging items when the state changes.

Stretch goals

  • Add a shared element transition from the grid cell to the detail screen with SharedTransitionLayout, Modifier.sharedElement and rememberSharedContentState(key = "photo-$id"), using the AnimatedContentScope that Navigation Compose gives each destination.
  • Add albums by grouping on BUCKET_ID and BUCKET_DISPLAY_NAME, with one paging source per album.
  • Add a videos tab with MediaStore.Video and READ_MEDIA_VIDEO, showing the duration on each cell.
  • Add multi-select delete with MediaStore.createDeleteRequest (API 30+), which shows a system confirmation dialog.
  • Add favourites stored in Room by MediaStore id, and handle ids that no longer exist.
  • Add screenshot tests for the grid, the permission screens and the partial-access banner.

Done checklist

  • The photo picker works with no storage permission declared for that flow.
  • The manifest declares READ_EXTERNAL_STORAGE with maxSdkVersion="32", READ_MEDIA_IMAGES and READ_MEDIA_VISUAL_USER_SELECTED.
  • Full, partial and denied access each have their own UI, and partial access offers "Select more".
  • Access is re-checked on every resume, and nothing about permissions is stored on disk.
  • The PagingSource queries one page at a time, on an injected IO dispatcher, and invalidates on MediaStore changes.
  • The ViewModel exposes photos with cachedIn(viewModelScope), separate from UiState.
  • The grid uses itemKey { it.id } and itemContentType, and each cell has a bounded size for Coil.
  • Empty library, revoked access and deleted photos show clear states instead of crashing.
  • UI tests pass, and you have benchmark numbers with and without the Baseline Profile.

Talking about it in an interview

  • Explain when you would use the photo picker instead of media permissions, and why Google recommends the picker for most apps.
  • Walk through the permission matrix: READ_EXTERNAL_STORAGE up to Android 12, READ_MEDIA_IMAGES on 13, and partial access with READ_MEDIA_VISUAL_USER_SELECTED on 14+.
  • Explain how your PagingSource pages MediaStore, why prepend loads must not overlap, and how invalidate() from a ContentObserver keeps the grid in sync.
  • Explain why PagingData stays out of UiState, and what cachedIn(viewModelScope) saves on rotation.
  • Explain how Coil picks the decode size from the layout, and why unbounded cells waste memory.
  • Show the frame timings from your Macrobenchmark before and after the Baseline Profile, and say what the Perfetto trace showed for the slowest frames.