Kotlin Camera2 API Android Development

Kotlin Camera2 API graphic to signify camera preview

A Guide To Camera2 API

The Android Camera2 API was introduced in Android API level 21 corresponding to Android 5.0 Lollipop. Camera2 API introduced new features to control, capture and manipulate captured images. The AO

Camera2 API Reference provides detailed documentation.

For this tutorial, Camera2 API will be used to place the camera in a TextureView. This is part of the ongoing Chicken Webcam App series. Most of the samples did not work in Android Studio, instead sample code from Tim Stanteford’s article inspired this article.

This is a native Kotlin Android application, the HTML5 application that runs in a web browser. Kotlin is a cross-platform, statically typed, general-purpose high-level programming language with type inference.

Requirements For Native Android Application

Glossary:

IP

Internet Protocol address is a numerical label that is assigned to a device connected to a computer network.

Wi-Fi

Wireless network protocols based on the IEEE 802.11 standards for local area networks.

WLAN

Wireless LAN is a computer network that links 2 or more devices.

TCP/IP

Transmission Control Protocol/Internet Protocol is a framework for computer networking.

USB

Universal Serial Bus is a standard for digital data transmission and power delivery between electronics.

ADB

Android Debug Bridge.

API

Application Programming Interface is a set of rules or protocols that enables software applications to communicate with each other to exchange data, features, and functionality.

UI

User Interface is the point of interaction between humans and machines, allowing effective operation and control of the machine from the human end.

TextureView

Android component used for rendering video and graphics into the Android UI hierarchy.

Android Devices

Recording Devices
Name Description Recording Power
Sony Xperia XA1 Ultra Updated to Android 8.0 and latest web browser. Takes photos and videos on front and back cameras. USB Type-C 2.0 10W charging
Samsung Galaxy S21 FE 5G Updated to Android 14.0 and default camera application. Takes photos and videos on front and back cameras. USB Type-C 2.0 <25W charging
Logitech HD Webcam C525 External webcam connected to workstation via USB cable. Takes audio, photos and videos on front camera. USB 2.0 <2.5W draw
Name Description Example

Open Camera

val manager = getSystemService(Context.CAMERA_SERVICE) as CameraManager
try {
	 val cameraId = manager.cameraIdList[0]
	 val characteristics = manager.getCameraCharacteristics(cameraId)
	 // Confirm Camera Permission
	 if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
		  ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_CODE)
		  return
	 }

	 manager.openCamera(cameraId, object : CameraDevice.StateCallback() {

		  override fun onOpened(camera: CameraDevice) {
				cameraDevice = camera
				if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
					 previewCamera()
				} else {
					 previewCameraLegacy()
				}
		  }
		  override fun onDisconnected(camera: CameraDevice) {
				camera.close()
				cameraDevice = null
		  }
		  override fun onError(camera: CameraDevice, error: Int) {
				camera.close()
				cameraDevice = null
		  }
	 }, null)

} catch (e: CameraAccessException) {
	 e.printStackTrace()
}

Preview Camera

val surfaceTexture = tView.surfaceTexture ?: return
surfaceTexture.setDefaultBufferSize(1920, 1080)
val surface = Surface(surfaceTexture)

val captureRequestBuilder = cameraDevice?.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)

captureRequestBuilder?.let { builder ->
	 builder.addTarget(surface)

	 val outputConfiguration = OutputConfiguration(surface)
	 val executor = Executors.newSingleThreadExecutor()

	 val sessionConfiguration = SessionConfiguration(
		  SessionConfiguration.SESSION_REGULAR,
		  listOf(outputConfiguration),
		  executor,
		  object : CameraCaptureSession.StateCallback() {
				override fun onConfigured(session: CameraCaptureSession) {
					 try {
						  session.setRepeatingRequest(builder.build(), null, null)
					 } catch (e: CameraAccessException) {
						  e.printStackTrace()
					 }
				}

				override fun onConfigureFailed(session: CameraCaptureSession) {
					 // Handle configuration failure
					 println("Camera Capture Failed")
				}
		  }
	 )

	 cameraDevice?.createCaptureSession(sessionConfiguration)
}

Download

The Android SDK tools can be downloaded from SDK Platform Tools and installed on your workstation.

Explanation

  1. Use the ADB tool to connect to your Android device if applicable.
  2. Generate an Android Layout XML file as app -> res/xml/activity_main.xml.
  3. Generate an Android Manifest Permissions of for Camera as app -> manifests/AndroidManifest.xml.
  4. Generate Android code snippet to test camera preview.

Android App Requesting Camera Permission
Android Studio Debug App In Emulator Requesting Camera Permission

Android Emulator App Preview Camera
Android Studio Debug App In Emulator Preview Camera

Android Device App Preview Camera
Android Studio Debug App On Device Preview Camera


Usage

You can use any IDE or text editor to compile and execute Android code. For this tutorial, Android Studio IDE was used, but it was not needed for coding the camera preview.

Open Source

Kotlin is licensed under the Apache License version 2.0. The permissive license requires the preservation of the copyright notice and disclaimer. It allows commercial use, modification, distribution, and allows making derivatives proprietary, consult the license for more specific details.

Android is licensed under the Apache License version 2.0 for the userspace software and GNU General Public License (GPL) version 2 for the Linux kernel. The permissive license requires the preservation of the copyright notice and disclaimer, while the copyleft license comes with strict rules and requirements to ensure the software remains free and open-source. It allows commercial use, modification, distribution, and allows making derivatives proprietary, consult the license for more specific details.

Conclusion:

The Android Camera2 API can be used by Kotlin to preview the camera. The API is supported in Android versions starting from 5.0.

You can use an emulator to test the application but a real device is recommended via USB or WiFi connection for debugging.

If you enjoy this article, consider supporting me by purchasing one of my OjamboShop.com Online Programming Courses or publications at Edward Ojambo Programming Books or simply donate here Ojambo.com Donate

References:

Leave a Reply

Your email address will not be published. Required fields are marked *