Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 104 ยท Building a Real UI

Camera, Media Playback and Sharing Images

Take photos with CameraX and the system camera, pick media with the photo picker, play video with Media3 in Compose, save to MediaStore and share through FileProvider.

Sooner or later an app wants to deal with pictures and sound: take a photo for a profile, let the user attach an image, play a video, save a result to the gallery, share it with another app. Each of these used to mean a pile of legacy APIs and storage permissions. Modern Android has a small set of good answers, and the most important design rule is use the system's own UI whenever you can, because it needs fewer permissions, is already accessible and is the same for every app.

This lesson covers the choices in order of effort: asking the system camera or photo picker (no permission, no UI to build), CameraX when you need your own camera screen, Media3 (ExoPlayer) for playback, MediaStore for saving to shared storage, and a share sheet with FileProvider for sending files out. As elsewhere in this track, the Android code is read-only because the site has no emulator and no camera. The TryIts are plain Kotlin stand-ins that model the rules and the lifecycle, and the text says what each one is pretending.

Pick the lightest tool

System camera TakePicture contract, no permission
Photo picker PickVisualMedia, no permission
CameraX Your own camera screen
Media3 Play audio and video

Start at the left. Move right only when you need more control.

1 / 2

Ask the system: camera and photo picker

If all you need is "a photo from the user", launch the system for it. You use the Activity Result API, the same mechanism as runtime permissions, with a contract that describes the input and output.

Taking a photo. ActivityResultContracts.TakePicture() opens the user's camera app, writes the photo to a Uri that you supply, and returns a Boolean. Because the camera app (not your app) opens the camera, you do not need the CAMERA permission for this. You do need a place for the image to go: a file in your own storage, exposed through a FileProvider (see below), because another app cannot write to your private files directly.

Kotlin
// read-only example: TakePicture with a FileProvider Uri
@Composable
fun AvatarPicker(onPhoto: (Uri) -> Unit) {
    val context = LocalContext.current
    var pendingUri by remember { mutableStateOf<Uri?>(null) }

    val takePicture = rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) { saved ->
        if (saved) pendingUri?.let(onPhoto)       // false means the user cancelled
    }

    Button(onClick = {
        val file = File(context.cacheDir, "images/avatar-${System.currentTimeMillis()}.jpg")
            .apply { parentFile?.mkdirs() }
        val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
        pendingUri = uri
        takePicture.launch(uri)
    }) { Text("Take photo") }
}

Keep pendingUri in saveable state if your screen may be recreated while the camera app is open, because the process can even be killed meanwhile. See saved state.

Choosing an existing photo or video. The photo picker (PickVisualMedia) is a system screen that shows the user's photos and returns only the items they select. Your app never gets broad access to the library, so no storage permission is needed. It works back to Android 4.4 through a Google Play services fallback and is the right default for "attach an image".

Kotlin
// read-only example: the photo picker
val pickMedia = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->
    if (uri != null) viewModel.onImagePicked(uri) else { /* user cancelled */ }
}

Button(onClick = {
    pickMedia.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
}) { Text("Choose photo") }

// Several items: use PickMultipleVisualMedia(maxItems = 5)

The returned Uri is a content:// Uri with temporary read access. Load it with Coil (AsyncImage(model = uri)), or copy the bytes into your own storage if you need the image after the app restarts. Do not store the Uri expecting to read it next week, unless you took persistable permission, and the picker's Uris generally cannot be persisted.

The permissions in short

What you do Permission needed
Launch the system camera (TakePicture) None
Pick with the photo picker None
Your own camera screen (CameraX) CAMERA, runtime
Record audio with your own UI RECORD_AUDIO, runtime
Save a photo to the gallery on API 29+ None (the app's own contributions)
Read all photos yourself (own gallery app) READ_MEDIA_IMAGES (API 33+), partial access on API 34+

The first two rows are the reason to prefer the system UI. The first stand-in models how a contract request behaves: permission rules, a destination Uri, and the cancelled case that every real app must handle.

Kotlin Activity Result contracts and permissions (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

CameraX: your own camera screen

Choose CameraX when the camera must be part of your UI: a document scanner, a QR reader, a custom viewfinder. It is a Jetpack library that wraps the older Camera2 API, behaves the same across thousands of device models and is lifecycle-aware, so it starts and stops the camera for you. You describe use cases and bind them to a lifecycle:

  • Preview shows the live camera image.
  • ImageCapture takes a photo.
  • VideoCapture records video.
  • ImageAnalysis gives you frames to process (a barcode scanner, for instance).

You add the camera-core, camera-camera2, camera-lifecycle, camera-view and (for Compose) camera-compose artifacts. The CAMERA permission goes in the manifest and is requested at run time. A PreviewView from the Views world works in Compose through AndroidView, and recent versions also offer a CameraXViewfinder composable.

Kotlin
// read-only example: bind a preview and a capture use case
@Composable
fun CameraScreen(onPhotoSaved: (Uri) -> Unit) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current
    val imageCapture = remember { ImageCapture.Builder().build() }

    AndroidView(
        modifier = Modifier.fillMaxSize(),
        factory = { ctx ->
            PreviewView(ctx).also { previewView ->
                val providerFuture = ProcessCameraProvider.getInstance(ctx)
                providerFuture.addListener({
                    val provider = providerFuture.get()
                    val preview = Preview.Builder().build().apply {
                        setSurfaceProvider(previewView.surfaceProvider)
                    }
                    provider.unbindAll()
                    provider.bindToLifecycle(
                        lifecycleOwner, CameraSelector.DEFAULT_BACK_CAMERA, preview, imageCapture,
                    )
                }, ContextCompat.getMainExecutor(ctx))
            }
        },
    )

    Button(onClick = {
        val output = ImageCapture.OutputFileOptions.Builder(newPhotoFile(context)).build()
        imageCapture.takePicture(output, ContextCompat.getMainExecutor(context),
            object : ImageCapture.OnImageSavedCallback {
                override fun onImageSaved(result: ImageCapture.OutputFileResults) {
                    result.savedUri?.let(onPhotoSaved)
                }
                override fun onError(exception: ImageCaptureException) {
                    Log.e("Camera", "Capture failed", exception)
                }
            })
    }) { Text("Capture") }
}

Three practical points. First, check the permission before binding and show a clear explanation if it is denied; a camera screen that stays black is the worst failure mode. Second, bind use cases only when the screen is visible, which bindToLifecycle does for you through the lifecycle you pass. Third, test on a real device: emulators have a fake camera, and orientation, aspect ratio and flash behave differently across hardware.

Playing audio and video with Media3

Media3 is the current Jetpack media library, and its ExoPlayer is the standard player. It supports progressive files, adaptive streaming (HLS, DASH), captions, DRM and background playback through a MediaSessionService. The older android.media.MediaPlayer and the standalone ExoPlayer library are legacy; new code uses androidx.media3.

The thing to understand is the player's lifecycle. An ExoPlayer holds decoders, buffers and a network connection, so you must create it when needed and release() it when the screen goes away. A forgotten player keeps playing audio after the user left, or leaks memory.

Kotlin
// read-only example: ExoPlayer in Compose
@Composable
fun VideoPlayer(url: String, modifier: Modifier = Modifier) {
    val context = LocalContext.current
    val player = remember(url) {
        ExoPlayer.Builder(context).build().apply {
            setMediaItem(MediaItem.fromUri(url))
            prepare()                       // starts buffering, does not play yet
            playWhenReady = true            // play as soon as it is ready
        }
    }

    // Pause when the app goes to the background; release when we leave the composition
    val lifecycleOwner = LocalLifecycleOwner.current
    DisposableEffect(player, lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_STOP) player.pause()
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
            player.release()
        }
    }

    AndroidView(
        modifier = modifier,
        factory = { ctx -> PlayerView(ctx).apply { this.player = player } },
    )
}

DisposableEffect is the same tool from Side Effects, used here to tie cleanup to the composition. PlayerView gives you ready-made controls, buffering indicators and captions button. Compose-native player UI components are also available in the Media3 UI Compose module, but PlayerView inside AndroidView is the long-established path.

For music that must continue with the screen off, playback moves out of the UI into a MediaSessionService (a foreground service of type mediaPlayback), as described in Services and Notifications. The player lives in the service, and the UI connects to it with a MediaController. That also gives you lock-screen controls and Bluetooth buttons for free.

Streaming over HTTP needs the INTERNET permission, and Android blocks plain http:// traffic by default since API 28. Use https:// URLs.

The second stand-in models the ExoPlayer state machine and the cleanup rules that cause the usual bugs: playing before the player is ready, pausing at onStop, and a player that is never released.

Kotlin A player and its lifecycle (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A photo your app takes with CameraX in cacheDir or filesDir is private: other apps and the gallery cannot see it, and it disappears when the user clears the cache or uninstalls. To make it a real part of the user's library, insert it into MediaStore, the shared index of photos, videos and audio.

Since Android 10 (API 29), scoped storage means an app can add files to the shared media collections without any permission and can later read and edit only the files it created. The standard pattern marks the row IS_PENDING, writes the bytes, then clears the flag so other apps see a finished file.

Kotlin
// read-only example: save a bitmap to Pictures/MyApp
suspend fun saveToGallery(context: Context, bitmap: Bitmap): Uri? = withContext(Dispatchers.IO) {
    val resolver = context.contentResolver
    val collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
    val values = ContentValues().apply {
        put(MediaStore.Images.Media.DISPLAY_NAME, "photo-${System.currentTimeMillis()}.jpg")
        put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/MyApp")
        put(MediaStore.Images.Media.IS_PENDING, 1)             // hidden from other apps for now
    }
    val uri = resolver.insert(collection, values) ?: return@withContext null
    try {
        resolver.openOutputStream(uri)?.use { out -> bitmap.compress(Bitmap.CompressFormat.JPEG, 92, out) }
        values.clear()
        values.put(MediaStore.Images.Media.IS_PENDING, 0)      // now visible in the gallery
        resolver.update(uri, values, null, null)
        uri
    } catch (e: IOException) {
        resolver.delete(uri, null, null)                       // do not leave a broken row
        null
    }
}

On API 28 and lower you also need WRITE_EXTERNAL_STORAGE, declared with android:maxSdkVersion="28". The main reasons for IS_PENDING are correctness and cleanup: a half-written JPEG should never show up in a gallery, and a failed write must remove its row. For general file rules (private storage, caches, SAF), see Files and Storage.

Sharing with the share sheet and FileProvider

To send an image to another app (a chat, an email), you use an ACTION_SEND intent with a content:// Uri and let the system show the share sheet (Intent.createChooser). Never put a file:// path in an intent: since API 24 that throws FileUriExposedException, because it would expose your private storage layout and the receiving app has no permission to open it.

A FileProvider solves this. It is a content provider that turns a private file into a content:// Uri, and you grant the receiver temporary read permission for that one Uri through a flag on the intent. You declare it once in the manifest and describe which folders it may serve in an XML file.

XML
<!-- read-only example: AndroidManifest.xml -->
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>
XML
<!-- read-only example: res/xml/file_paths.xml -->
<paths>
    <cache-path name="images" path="images/" />
</paths>
Kotlin
// read-only example: share an image file
fun shareImage(context: Context, file: File) {
    val uri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", file)
    val send = Intent(Intent.ACTION_SEND).apply {
        type = "image/jpeg"
        putExtra(Intent.EXTRA_STREAM, uri)
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)       // temporary access for the receiver
    }
    context.startActivity(Intent.createChooser(send, "Share photo"))
}

Only folders you list in file_paths.xml can be shared, which is the safety net: a bug cannot accidentally expose your database. Use <cache-path> or <files-path> for your own storage and share only what the user chose to send. Intents explains how ACTION_SEND and chooser work.

The last stand-in models the FileProvider rule: a Uri only works when the folder is configured, and only the app you granted can read it.

Kotlin FileProvider grants and the share sheet (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Putting it together

A typical "attach a photo" feature needs very little code: the photo picker for existing images, TakePicture for a new one, Coil to display the result, MediaStore only when the user wants the picture saved to the gallery, and FileProvider for the camera destination and sharing. Reach for CameraX only when the camera itself is the product. Whatever the source, keep the state (the picked Uri or null) in a ViewModel and hand the UI a plain value, as in UI state and events.

Common mistakes

  • Requesting CAMERA or storage permission when a system contract would do. Fewer permissions mean more users who say yes.
  • Using file:// Uris in intents. They crash on modern Android; use FileProvider.
  • Not handling cancellation. TakePicture returns false and the picker returns null; both are normal outcomes.
  • Forgetting release() on the player. Audio keeps playing, or memory leaks.
  • Loading a full-size photo into memory. Use a loader that downsamples, as the Coil lesson explains.
  • Leaving partial files in MediaStore. Use IS_PENDING and delete the row on failure.
  • Sharing a private file without a grant flag. The receiver gets a SecurityException.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which approach lets a user attach an existing photo without your app requesting any storage permission?

    The photo picker is a system screen that returns only what the user selects, so your app needs no storage permission.
  2. 2. Your app launches the system camera with TakePicture(). Do you need the CAMERA permission?

    The permission is needed only when your own code opens the camera, for example with CameraX.
  3. 3. What is the correct way to give another app read access to an image in your private storage?

    FileProvider exposes only configured folders as content Uris, and the grant flag gives the receiver temporary access.
  4. 4. Why mark a MediaStore row with IS_PENDING while writing?

    While IS_PENDING is 1 the item is hidden from other apps. You set it to 0 after the bytes are written.
  5. 5. When should an ExoPlayer used inside a composable be released?

    A player holds decoders and network resources. Release it when you no longer need it, and pause it when the app is stopped.

Summary

  • Prefer the system UI: TakePicture and PickVisualMedia need no permission and are easy to implement; always handle the cancelled result.
  • Use CameraX (Preview, ImageCapture, VideoCapture, ImageAnalysis) when the camera is part of your own screen; it needs the CAMERA runtime permission and is lifecycle-aware.
  • Use Media3 ExoPlayer for playback, create it when needed, pause at ON_STOP, and always release() it; use a MediaSessionService for background audio.
  • Save to the shared library with MediaStore (no permission on API 29+), using IS_PENDING while writing.
  • Share files through a FileProvider content Uri with a temporary read grant, never with a file:// path.
  • The Android code here is read-only; the TryIts model contracts and permissions, the player lifecycle and FileProvider grants.

Next: Files and Storage