TP Icon 136

Android CameraX: Let’s take a selfie


With Android, using the camera has always been a bit of a challenge. After Google marked the old API as deprecated with Android 5 (Lollipop) due to insufficient functionality, the Camera2 API was introduced in return. Now, manufacturers and developers have been able to integrate even complex functions into the camera. In return, however, the effort and complexity of the implementation has also increased considerably.


To counter the increased complexity, the CameraX library was introduced at Google IO 2019, which is part of the Android Jetpack component set. CameraX is based on the Camera2 API and can be used from Android 5 and beyond. It implements the idea of use-cases to ensure a simple API. Currently, three use-cases are provided:

  • Preview: displays a preview of the images
  • Image analysis: provides access to a stream of images for subsequent processing
  • Image capture: stores images in high resolution

CameraX does not only offer various use cases, but also takes over the configuration of device-specific settings. Google provides its own test lab for this purpose, in which many different devices are tested automatically.

In addition, an optional add-on called "extensions" is provided, which enables access to device-specific effects (such as HDR, night, or potrait mode).

The following snippet shows how little effort is required to integrate the preview use case into the system. The result can be seen in the screenshot.

Android CameraX Preview-Use-Case


private fun bindPreviewUseCase() {
    // Get screen metrics used to setup camera for full screen resolution
    val metrics = DisplayMetrics().also { textureView.display.getRealMetrics(it) }
    val screenAspectRatio = Rational(metrics.widthPixels, metrics.heightPixels)

    // Set up the view finder use case to display camera preview
    val viewFinderConfig = PreviewConfig.Builder().apply {

    // Use the auto-fit preview builder to automatically handle size/orientation changes
    preview =, textureView)

    // Apply declared configs to CameraX using the same lifecycle owner
    CameraX.bindToLifecycle(viewLifecycleOwner, preview)
Android CameraX: Let’s take a selfie - jambit ToiletPaper

Cookie Settings

This website uses cookies to personalize content and ads, provide social media features, and analyze website traffic. In addition, information about your use of the website is shared with social media, advertising, and analytics partners. These partners may merge the information with other data that you have provided to them or that they have collected from you using the services.

For more information, please refer to our privacy policy. There you can also change your cookie settings later on.

contact icon

Contact us now