Photo gallery with paging and permissions
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
PickVisualMediaandPickMultipleVisualMedia - Media permissions on Android 12, 13 and 14+, including partial access
MediaStorequeries withContentResolver, projections, sort order, limit and offset- A custom Paging 3
PagingSourcethat reloads when MediaStore changes - Coil 3
AsyncImagein aLazyVerticalGridwith 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 layer | Responsibility |
|---|---|
Photo model | id, content uri, display name and date added. The id is the MediaStore _ID. |
MediaStorePagingSource | Queries one page of images with limit and offset, maps cursor rows to Photo, and invalidates itself when MediaStore changes. |
PhotoRepository | Builds Pager(PagingConfig(...)) { MediaStorePagingSource(...) } and exposes its flow. |
GalleryViewModel | photos with cachedIn(viewModelScope) and a separate StateFlow<GalleryUiState> for access state. |
| UI | Picker button, permission screen, LazyVerticalGrid of AsyncImage, detail screen with a type-safe route. |
| Tests | Paging 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.
- Create a Compose project with
minSdk26 or higher. Add Hilt, Paging (paging-runtimeandpaging-compose), Navigation Compose, and Coil 3 (io.coil-kt.coil3:coil-compose). Coil loadscontent://URIs without a network artifact. - Register
rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia()). Launch it withPickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly). - Show the returned
List<Uri>in a small row ofAsyncImage. Keep the URIs in aViewModelso they survive rotation. - 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
ModuleDependenciesservice entry from the docs to your manifest. Where no picker is available, the Activity library falls back toACTION_OPEN_DOCUMENT. - Note that access to picked URIs is temporary. Call
takePersistableUriPermissiononly 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.
- In the manifest, declare
READ_EXTERNAL_STORAGEwithandroid:maxSdkVersion="32",READ_MEDIA_IMAGES, andREAD_MEDIA_VISUAL_USER_SELECTED. - Use
ActivityResultContracts.RequestMultiplePermissions(). On API 34+ requestREAD_MEDIA_IMAGESandREAD_MEDIA_VISUAL_USER_SELECTEDtogether. On API 33 requestREAD_MEDIA_IMAGES. On API 32 and lower requestREAD_EXTERNAL_STORAGE. - Write a
checkMediaAccess(context)function that returnsFull,PartialorDeniedwithContextCompat.checkSelfPermission. CheckREAD_MEDIA_IMAGESfirst (API 33+), thenREAD_MEDIA_VISUAL_USER_SELECTED(API 34+), thenREAD_EXTERNAL_STORAGE(API 32 and lower). - Re-check on every resume with
LifecycleEventEffect(Lifecycle.Event.ON_RESUME)and push the result intoGalleryUiState. - 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. - 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.
- Pick the collection URI:
MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL)on API 29+,MediaStore.Images.Media.EXTERNAL_CONTENT_URIbelow that. - Query only the columns you need (
_ID,DISPLAY_NAME,DATE_ADDED), sorted byDATE_ADDED DESC, _ID DESC. The_IDtie-break keeps the order stable when several photos share a timestamp. - Page with limit and offset. On API 30+ pass a
BundlewithQUERY_ARG_SQL_SORT_ORDER,QUERY_ARG_LIMITandQUERY_ARG_OFFSETtoquery(uri, projection, queryArgs, cancellationSignal). On older versions, addLIMITandOFFSETto the sort order string. - Build each item's URI with
ContentUris.withAppendedId(collection, id). - Run the query with
withContext(ioDispatcher). Catch onlySecurityException(access revoked) and returnLoadResult.Error. Do not catchException, because that also catchesCancellationException. - Implement
getRefreshKeyso a refresh starts around the item the user was looking at. - Register a
ContentObserveron the collection and callinvalidate()when it fires. Unregister it inregisterInvalidatedCallback.Pagerthen creates a fresh paging source. - 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.
- In the ViewModel, expose
val photos = repository.photos().cachedIn(viewModelScope). - In the screen, call
collectAsLazyPagingItems()and render aLazyVerticalGrid(columns = GridCells.Adaptive(minSize = 96.dp)). - Use
items(count = photos.itemCount, key = photos.itemKey { it.id }, contentType = photos.itemContentType { "photo" }). The MediaStore_IDis a stable, unique key. - Give each cell a bounded size with
Modifier.aspectRatio(1f)and useAsyncImage(model = photo.uri, contentScale = ContentScale.Crop). Coil reads the size from the layout constraints and decodes a downsampled bitmap, not the full camera image. - Show a placeholder for
nullitems, and useloadState.refreshfor the first-load spinner and the empty state ("No photos on this device"). - 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.
- Add a type-safe route,
@Serializable data class PhotoDetail(val id: Long), and navigate to it on tap. - In the detail screen, rebuild the URI from the id with
ContentUris.withAppendedId. Pass the id, not the wholePhotoobject. - Load the image with
AsyncImageandContentScale.Fit. Coil still limits the decode to the screen size. - 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.
- Unit test the paging source with
TestPagerfrompaging-testingagainst a fake data source, or as an instrumented test against MediaStore with seeded images. - Write Compose UI tests for the permission screens. Use
GrantPermissionRulefor the granted path and test the denied UI by feeding state to the screen composable directly. - Add a
benchmarkmodule (the Android Studio Baseline Profile template creates one). Seed the emulator with a few hundred images, and grant the permission in thesetupBlockwithdevice.executeShellCommand("pm grant <package> android.permission.READ_MEDIA_IMAGES"). - Write a Macrobenchmark with
MacrobenchmarkRule.measureRepeatedandFrameTimingMetric()that flings the grid several times. - Generate a Baseline Profile with
BaselineProfileRule.collect()that starts the app and scrolls the grid, using theandroidx.baselineprofileGradle plugin. - Compare frame timings with and without the profile (
CompilationMode.None()againstCompilationMode.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, andcursor.usecloses the cursor even if mapping throws. - Only
SecurityExceptionis 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
_IDwould appear twice andLazyVerticalGridwould crash on the duplicate key. - The
ContentObserverturns any MediaStore change (new photo, deletion, a new partial selection) intoinvalidate(). Paging then builds a new source and reloads aroundgetRefreshKey. DATE_ADDEDis set for every row.DATE_TAKENcomes 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
LIMITin the sort order everywhere. AddingLIMITto the sort order string is an old workaround, and newer MediaStore versions may reject it. Use theBundlewithQUERY_ARG_LIMITandQUERY_ARG_OFFSETon 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, notREAD_MEDIA_IMAGES. If the app checks onlyREAD_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
Exceptioninload(). It turnsCancellationExceptioninto aLoadResult.Error. CatchSecurityExceptiononly. - 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
LazyVerticalGridthrows 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
PagingDatainsideUiState. Keepphotosas its own flow withcachedIn(viewModelScope)and keep access state inUiState. Creating thePagerin a composable reloads everything after rotation.
Code review finding
- 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.
- Declare
READ_MEDIA_VISUAL_USER_SELECTEDand request it together withREAD_MEDIA_IMAGESon API 34+. - Model access as
Full,PartialorDenied, and query MediaStore for bothFullandPartial. 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
checkSelfPermissionon every resume and callrefresh()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.sharedElementandrememberSharedContentState(key = "photo-$id"), using theAnimatedContentScopethat Navigation Compose gives each destination. - Add albums by grouping on
BUCKET_IDandBUCKET_DISPLAY_NAME, with one paging source per album. - Add a videos tab with
MediaStore.VideoandREAD_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_STORAGEwithmaxSdkVersion="32",READ_MEDIA_IMAGESandREAD_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
PagingSourcequeries one page at a time, on an injected IO dispatcher, and invalidates on MediaStore changes. - The ViewModel exposes
photoswithcachedIn(viewModelScope), separate fromUiState. - The grid uses
itemKey { it.id }anditemContentType, 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_STORAGEup to Android 12,READ_MEDIA_IMAGESon 13, and partial access withREAD_MEDIA_VISUAL_USER_SELECTEDon 14+. - Explain how your
PagingSourcepages MediaStore, why prepend loads must not overlap, and howinvalidate()from aContentObserverkeeps the grid in sync. - Explain why
PagingDatastays out ofUiState, and whatcachedIn(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.