Android SharedPreferences Tutorial and Example

Build an Android flashlight with the Camera API

An Android flashlight can be a small app with a large practical value. It can guide a late-night walk, illuminate a lost key, or help a driver spot debris beside a car. The useful version responds immediately, indicates battery cost clearly, and never leaves the LED running after the app leaves the foreground.

Android exposes the camera flash through several generations of APIs. For a dedicated tool, the camera service’s torch control is usually simpler than opening a preview. The implementation below uses CameraManager in Kotlin, sets a sensible minimum SDK, requests permission at runtime, and releases the light when the activity stops.

You will create the project, declare camera access, locate a rear camera with flash hardware, and connect a single toggle button. The examples focus on behaviour that survives real devices: missing flash units, denied permissions, camera contention, rapid taps, rotation, and low battery.

Local use matters as well. Night-time passengers in Sydney and Melbourne may value a torch while moving between stations, bus stops, and dim car parks. The app should assist without pretending to replace safe behaviour, reflective clothing, or a proper vehicle light.

Choose the right camera approach

The main camera options differ in complexity and compatibility. A torch-only app benefits from direct torch control, while a broader photography application may need preview, capture, or image-processing features. Compare these approaches before choosing the foundation for your project.

Approach Best fit Main benefit Main limitation
CameraManager Torch-only apps on Android 6.0 and later Small, direct API with no preview required No image capture features
Camera2 Advanced camera controls Detailed control over hardware and capture states More callbacks and lifecycle handling
CameraX Apps using a modern camera pipeline Consistent lifecycle-aware behaviour Additional dependency and setup
Legacy Camera Older compatibility projects Supports some earlier Android versions Deprecated and unsuitable for new work

For a focused Android flashlight, CameraManager.setTorchMode() offers the clearest path. Set minSdk to 23 or higher. If the application must support Android 5.x, evaluate Camera2 or carefully isolated legacy code before committing to an older compatibility target.

Declare permissions without blocking installation

The camera permission is required to control the torch, but the flash should not be treated as mandatory hardware. Mark it as an optional feature so the application remains installable on devices without an LED.

<uses-permission android:name="android.permission.CAMERA" />

<uses-feature
    android:name="android.hardware.camera.flash"
    android:required="false" />

The CAMERA permission is a dangerous permission on modern Android and must be requested at runtime. Ask for it when the user first enables the torch, rather than during startup. If access is denied, explain that permission is needed and leave the light off instead of repeatedly displaying the system prompt.

Developers preparing a Mac-based workstation can keep platform-specific guidance such as macOS developer tooling separate from the Android build configuration. The manifest, Gradle files, and permission declaration should remain part of the Android module.

Find a camera with usable flash

Camera IDs are assigned by the device manufacturer and are not guaranteed to follow a predictable order. Enumerate the available IDs, then inspect each camera’s characteristics for a rear-facing lens and an available flash.

fun findTorchCamera(manager: CameraManager): String? {
    return manager.cameraIdList.firstOrNull { id ->
        val info = manager.getCameraCharacteristics(id)

        info.get(CameraCharacteristics.LENS_FACING) ==
            CameraCharacteristics.LENS_FACING_BACK &&
            info.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true
    }
}

A device may contain several camera IDs with different capabilities. Selecting the rear camera avoids accidentally activating a front-facing LED intended for photography. The lookup should occur only after camera permission has been granted, and the UI should handle a null result by reporting that no compatible flash was found.

Control the torch safely in Kotlin

setTorchMode() changes the flash state without opening a camera preview. Retain the selected camera ID while the torch is active so the same light can be switched off reliably, including when another application attempts to use the camera.

class TorchController(context: Context) {
    private val appContext = context.applicationContext
    private val manager =
        requireNotNull(appContext.getSystemService(CameraManager::class.java))
    private var activeCameraId: String? = null

    fun setTorch(enabled: Boolean): Boolean {
        if (!enabled) {
            val id = activeCameraId ?: return true
            return try {
                manager.setTorchMode(id, false)
                true
            } catch (_: CameraAccessException) {
                false
            } finally {
                activeCameraId = null
            }
        }

        if (activeCameraId != null) return true
        val id = findTorchCamera(manager) ?: return false

        return try {
            manager.setTorchMode(id, true)
            activeCameraId = id
            true
        } catch (_: CameraAccessException) {
            false
        } catch (_: IllegalArgumentException) {
            false
        }
    }
}

Before invoking the controller, verify that Manifest.permission.CAMERA remains granted. Permission can be revoked from system settings while the application is running. Also catch access failures because camera hardware may be occupied, disconnected, or temporarily unavailable.

Camera2 provides another route through flash modes and capture requests, but it requires considerably more state management for this purpose. Reserve that complexity for applications that already need a camera pipeline or preview.

Connect the button and activity lifecycle

Use the Activity Result API to request camera access from the user’s action. The permission callback should update the interface rather than automatically changing hardware in a surprising way.

private val cameraPermission =
    registerForActivityResult(ActivityResultContracts.RequestPermission()) {
        status.text = if (it) "Ready" else "Permission denied"
    }

private fun enableTorch() {
    if (ContextCompat.checkSelfPermission(
            this, Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED
    ) {
        setTorchState(true)
    } else {
        cameraPermission.launch(Manifest.permission.CAMERA)
    }
}

The button label should reflect the current state, such as “Turn on torch” and “Turn off torch”. Update it only after the controller confirms the requested change. This prevents the interface from claiming that the LED is active when hardware access has failed.

Disable the torch in onStop(), and call the controller again from onDestroy() as a final cleanup safeguard. This prevents an accidental background light from draining the battery or interfering with another camera application. A short debounce also makes rapid button presses less likely to produce inconsistent states.

Test for Australian use and legal expectations

Australia’s Android market includes devices from Samsung, Motorola, Oppo, Xiaomi, and other manufacturers, with Google Play as the primary application storefront. Test on physical hardware from several price ranges because camera implementations and permission behaviour vary even when they use the same Android version.

Sydney and Melbourne night-time commuters may use the light while walking through poorly illuminated station approaches or suburban car parks. Brisbane’s hot summer evenings create another practical consideration: prolonged torch use adds heat and battery consumption. Let the device cool, provide a clear off control, and avoid encouraging users to hold the phone continuously in direct sunlight.

The federal Privacy Act 1988 becomes relevant if the application collects personal information, although a torch-only tool should not capture photographs, video, or location data. Keep analytics disclosures accurate, explain why camera access is requested, and avoid implying that image collection occurs. The Australian Consumer Law also requires care and honest representations, so the store listing should not promise a working torch on every Android device.

Before release, verify permission denial, rotation, backgrounding, rapid tapping, low battery, calls, and competition with other camera applications. Test a device with no flash to ensure the unavailable-hardware message appears correctly. A release candidate is ready when the permission flow, state feedback, and torch cleanup work reliably across physical devices.