Skip to content
Tutorials Center
My learning

Topics

Lesson 100 of 104 ยท Projects

Project: Utility Apps (Flashlight, Converter, Alarm, QR Scanner, Contacts, Media Player)

Build useful single-purpose Android apps: a torch, a binary and decimal converter, an alarm setter, a QR code scanner, a contacts list, a photo viewer and a media player, with testable logic.

Some of the best first apps do one practical thing: switch on the flashlight, convert a number, ring at a set time, scan a QR code, list your contacts, play a song. Each one teaches one Android system service and the permission or lifecycle rule that goes with it. This project walks through seven of them in the same format: what the app does, which Android API does the work, the permission it needs, the read-only Android code and, where there is real logic, a runnable Kotlin version of it.

As in Mini games, keep the logic in plain Kotlin, the state in a ViewModel and the screen a function of that state. Android code is read-only on this site (it needs the SDK and a device). The TryIts run the logic.

1. Flashlight

API: CameraManager.setTorchMode(cameraId, true). Permission: none on Android 6 (API 23) and later for the torch alone; CAMERA before that. Check that the device has a flash and that the camera you pick supports it.

Kotlin
// read-only example: toggle the torch
class Torch(private val context: Context) {
    private val manager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
    private val cameraId: String? = manager.cameraIdList.firstOrNull {
        manager.getCameraCharacteristics(it).get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true
    }

    val available get() = cameraId != null

    fun set(on: Boolean) {
        val id = cameraId ?: return
        try {
            manager.setTorchMode(id, on)
        } catch (e: CameraAccessException) {
            e.printStackTrace()          // camera in use by another app; show a message instead in a real app
        }
    }
}

Two real-world details: register a CameraManager.TorchCallback so your switch follows changes made elsewhere (for example the quick-settings tile), and turn the torch off when the user leaves the app unless it is a deliberate long-running feature. For other lessons about the camera itself see Media and camera.

2. Binary and decimal converter

A converter is pure logic and a good test target. The screen has one OutlinedTextField, a mode switch and a result line; the work is validating and converting.

Kotlin Binary, decimal and hex converter

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.

toLongOrNull(radix) does the hard part: it returns null for bad digits, so one ?: gives the error message. Use BigInteger when numbers may exceed 63 bits.

3. Alarm setter

API: AlarmManager with a PendingIntent that targets a BroadcastReceiver; the receiver shows a notification or plays a sound. Permissions: SCHEDULE_EXACT_ALARM or USE_EXACT_ALARM for exact alarms on Android 12 and later, and POST_NOTIFICATIONS on Android 13 and later (Services and notifications, Broadcast receivers). Alarms do not survive a reboot, so a BOOT_COMPLETED receiver must re-schedule them. If you only need work "some time later", WorkManager is simpler; for a user-visible alarm clock, AlarmManager.setAlarmClock is the right call.

Kotlin
// read-only example: schedule and cancel
fun schedule(context: Context, triggerAtMillis: Long) {
    val manager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val intent = Intent(context, AlarmReceiver::class.java)
    val pending = PendingIntent.getBroadcast(
        context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )
    if (Build.VERSION.SDK_INT < 31 || manager.canScheduleExactAlarms()) {
        manager.setAlarmClock(AlarmManager.AlarmClockInfo(triggerAtMillis, pending), pending)
    }
}

The calculation of when the next alarm fires from "07:30 on these weekdays" is where bugs hide: time zones, daylight saving and "it is already 07:31 today". Do it with java.time:

Kotlin Next alarm time with weekdays

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.

The last line shows why ZonedDateTime matters: Java moves the nonexistent 02:30 to 03:30 instead of throwing. Store the local time and days and recompute the next trigger each time instead of storing one epoch value, or the alarm drifts by an hour after daylight saving changes.

4. QR code scanner

API: Google ML Kit Barcode Scanning (or ZXing) fed by CameraX, or the ready-made Google Code Scanner which needs no camera permission in your app. Permission for your own CameraX preview: CAMERA, requested at run time (Permissions).

Kotlin
// read-only example: ML Kit analyzer on CameraX
class QrAnalyzer(private val onResult: (String) -> Unit) : ImageAnalysis.Analyzer {
    private val scanner = BarcodeScanning.getClient(
        BarcodeScannerOptions.Builder().setBarcodeFormats(Barcode.FORMAT_QR_CODE).build()
    )

    @OptIn(ExperimentalGetImage::class)
    override fun analyze(proxy: ImageProxy) {
        val media = proxy.image ?: return proxy.close()
        val image = InputImage.fromMediaImage(media, proxy.imageInfo.rotationDegrees)
        scanner.process(image)
            .addOnSuccessListener { codes -> codes.firstOrNull()?.rawValue?.let(onResult) }
            .addOnCompleteListener { proxy.close() }         // always close the frame or the stream stalls
    }
}

The scanner gives you a string. What your app does with it is the real feature: a URL opens in the browser, WIFI:S:Home;T:WPA;P:secret;; offers to join a network, mailto: composes an email, plain text is copied. Never auto-open or auto-join without asking: QR codes are a common phishing vector. This parser is the testable heart of the app:

Kotlin Classify what a QR code contains

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.

5. Contacts list

API: ContentResolver querying ContactsContract.CommonDataKinds.Phone.CONTENT_URI. Permission: READ_CONTACTS, requested at run time. Contacts are a content provider owned by another app, see Content providers.

Kotlin
// read-only example: read names and numbers (call off the main thread)
suspend fun loadContacts(resolver: ContentResolver): List<Contact> = withContext(Dispatchers.IO) {
    val result = mutableListOf<Contact>()
    val projection = arrayOf(
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.NUMBER
    )
    resolver.query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null,
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"
    )?.use { cursor ->
        val nameCol = cursor.getColumnIndexOrThrow(projection[0])
        val numberCol = cursor.getColumnIndexOrThrow(projection[1])
        while (cursor.moveToNext()) result += Contact(cursor.getString(nameCol), cursor.getString(numberCol))
    }
    result
}

Show the result in a lazy list with a search field. If the user denies the permission, show an explanation and a button that opens app settings, instead of a blank screen. To add a contact without needing WRITE_CONTACTS, send an Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI) so the user's contacts app does it. Group the list by first letter with groupBy { it.name.first().uppercaseChar() } for the classic sticky-header index.

6. Photo viewer

A grid of thumbnails that opens a full-screen pager. Load images with Coil (Image loading), query the device's pictures with MediaStore.Images (needs READ_MEDIA_IMAGES, or the photo picker which needs no permission: see Files and storage), and show full-screen with HorizontalPager plus zoomable gestures (Gestures). Pass only the image ID or URI to the detail screen, never the bitmap (Navigation arguments).

7. Media player (audio and video)

APIs: MediaPlayer is the simple built-in choice for one short sound; Media3 ExoPlayer is the modern, flexible player for streaming, playlists and video. A music app that continues when the screen is off needs a foreground service and a MediaSession, so the notification and lock screen controls work (Services and notifications).

Kotlin
// read-only example: Media3 in a ViewModel
class PlayerViewModel(app: Application) : AndroidViewModel(app) {
    val player: ExoPlayer = ExoPlayer.Builder(app).build().apply {
        setMediaItem(MediaItem.fromUri("https://example.com/song.mp3"))
        prepare()
    }
    override fun onCleared() { player.release() }        // always release the player
}

For a video, show it with a PlayerView inside AndroidView. Pause in onStop (or when the lifecycle leaves STARTED) unless audio should continue. The seek bar needs two formatted numbers, position and duration; format hours only when the media is longer than an hour:

Kotlin Format playback position

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 voice mail idea for accessibility

A "voice-based mail" app for users who cannot read or type reads each message aloud with TextToSpeech and records a reply with SpeechRecognizer, then sends it through an email Intent (so the user's mail app does the sending and you need no mail credentials). The pieces are all in Timers, clocks, sensors and speech and Accessibility. Always confirm out loud before sending, since speech recognition makes mistakes.

Common mistakes

  • Requesting permissions at app start instead of when the feature is used.
  • Leaving the camera, the torch or a MediaPlayer held after the screen closed.
  • Keeping an alarm only in memory: reboots and process death wipe it.
  • Trusting QR content, for example auto-opening a link or auto-joining a network.
  • Querying contacts or media on the main thread.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which permission does a torch-only flashlight app need on Android 6 and later?

    CameraManager.setTorchMode works without the CAMERA permission from API 23; check that a camera has a flash unit.
  2. 2. Why recompute the next alarm time instead of storing one timestamp?

    Store the local time and days, and compute the next trigger with time-zone rules each time.
  3. 3. What should your app do with a scanned URL or Wi-Fi QR code?

    QR codes are a phishing vector, so classify the content and let the user decide.
  4. 4. How should a reading of the contacts list be done?

    Queries can be slow, so use a background dispatcher, and the READ_CONTACTS runtime permission must be granted first.

Summary

  • Each utility app teaches one system service: CameraManager, AlarmManager, CameraX with ML Kit, ContentResolver, MediaStore and Media3.
  • Keep the testable logic (conversion, next alarm time, QR classification, time formatting) in plain Kotlin.
  • Request permissions when a feature is used and handle denial with an explanation.
  • Release camera, player and listeners with the lifecycle; do slow queries off the main thread.
  • Never trust scanned content, and use local time plus recomputation for alarms.

Next: Practice: architecture and navigation.