Home / Blog / Android lessons
CricCuts Blog · For Android developers

What a cricket app
taught me about Android

Sensors, looks, video, on-device models, speech, art drawn in Kotlin, and links for AI agents.

CricCuts started as a way to turn a phone video of cricket nets into a highlight reel. It grew into an app that reads the light in the room, dresses Home for the hour, decodes hours of video on the phone, thuds like a bat, reads lessons aloud and can be opened by an assistant. This is what I learned building it, as one developer, written for anyone building on Android.

⏱ ~22 min read 🤖 For Android developers 📱 Kotlin & Jetpack Compose 🗓 24 Nov 2026

The short answer

A phone is a sensor kit, a speaker, a microphone and a small computer that can run real machine-learning models with no connection. Most apps use a fraction of it. The lessons that mattered most to me: read sensors only while a screen needs them, and smooth what they say before you act on it. Let the app's look follow the moment, but never change it under someone who's reading. With video, decode in order rather than seek for every frame, and copy streams rather than re-encode when you can. Treat "on the device" as a promise, and never quietly fall back to a server. Test on old, cheap and odd phones, because that's where native libraries and haptics break. And give every page a link, because that's how assistants and agents get in today.

One thing I'm deliberately leaving out: how CricCuts decides what counts as a shot. That's the product's own recipe. Everything below is about the Android platform around it, and the code is simplified to show the idea.

The phone is a sensor kit

Most phones carry a light sensor, an accelerometer and a gyroscope, and Android fuses them into a gravity sensor that's cleaner than the raw accelerometer. None of them needs a runtime permission. CricCuts uses them in small ways that add up:

The light sensor taught me two things. First, raw lux jumps around: a hand passing over the sensor would flip the pages back and forth. The fix is hysteresis, two thresholds at each edge, so the pages turn light at 30 lux but don't turn back until the room falls below 22. It also takes the middle of the last three seconds of readings, so a passing shadow decides nothing:

// Two thresholds per edge, so a passing hand can't make the pages flicker.
fun classify(previous: RoomLevel, lux: Float): RoomLevel = when {
    lux >= 30f -> RoomLevel.BRIGHT
    previous == RoomLevel.BRIGHT && lux >= 22f -> RoomLevel.BRIGHT
    lux <= 15f -> RoomLevel.DIM
    previous == RoomLevel.DIM && lux <= 18f -> RoomLevel.DIM
    else -> RoomLevel.BETWEEN
}

Second, never change a page under someone who's reading it. Inside a lesson, CricCuts asks first ("Light pages? · Switch"). Anywhere else, a banner says why the look changed ("☀️ Bright here, so pages are light"), with a button to keep the other one.

💡
Tie every sensor listener to the screen's lifecycle. In Compose, register in a DisposableEffect and unregister in its onDispose. A listener left running drains the battery and keeps reporting to a screen nobody is looking at.

Looks that follow the hour and the room

CricCuts has four looks: Floodlights (a night stadium), Daylight (light pages), Scoreboard and Super Over. You can pick one, get a new one each time you open the app (Surprise me), let Home follow the time of day, or choose Auto, where each part of the app wears the look that suits it:

For the reading pages, Auto decides in a fixed order: your own choice, then a "Keep" you pressed this session, then the room if it's clearly bright or dim, then the phone's dark mode, and last the sun. Two details made that order work. A light system setting tells you nothing, because it's every phone's default, so only a dark setting counts as a choice; with the phone left on light, the sun decides. And a bright room beats the phone's dark mode, because dark pages are hard to read in the sun. When the room overrides the phone, a notice says so.

Building four looks in Compose taught me three things:

Haptics: make the phone feel the ball

Face the Pace is a reaction drill against a ball bowled at 120 to 150 km/h. When you middle it, the phone answers with a crisp click and a low thud just after it: the bat's "thock". Android's composition primitives (clicks, thuds, ticks, rises) feel far better than a raw buzz, but they arrived over two releases, not every phone has them, and some tablets have no vibration motor at all. So ask the phone, don't assume:

val effect = when {
    // The phone has these primitives (the thud needs Android 12): the best feel.
    vibrator.areAllPrimitivesSupported(PRIMITIVE_CLICK, PRIMITIVE_THUD) ->
        VibrationEffect.startComposition()
            .addPrimitive(PRIMITIVE_CLICK)
            .addPrimitive(PRIMITIVE_THUD, 0.8f, 30)
            .compose()
    // A motor with amplitude control: shape it with a waveform.
    vibrator.hasAmplitudeControl() -> VibrationEffect.createWaveform(timings, amplitudes, -1)
    // Anything else: one short pulse.
    else -> VibrationEffect.createOneShot(30, VibrationEffect.DEFAULT_AMPLITUDE)
}

Two more rules came out of it. Check hasVibrator(), and where it's false, let a sound stand in and say so. Our own test tablet has no motor, so there the drill says so and plays sounds instead. And never punish: a missed ball gets no buzz at all.

Heat, battery and a screen that must stay on

The recorder films a whole net session from behind the bowler's stumps, often in the sun. Three things fight you:

Starting quickly matters as much as lasting. Instant record starts a recording from a launcher shortcut, a Quick Settings tile or a home-screen widget: swipe down from any app, tap, and it's filming. On a locked phone, Android asks for the unlock first.

Video: decoding, seeking and cutting on the phone

A net session can be 2 to 5 GB of video, and everything CricCuts does with it happens on the phone: reading frames for analysis, previews you can scrub, cutting out the shots and exporting the reel with Media3. Video is where most of the speed was won, and where the strangest bugs lived.

// Through a file descriptor: setDataSource(context, uri) can miss the video track.
val extractor = MediaExtractor()
context.contentResolver.openAssetFileDescriptor(uri, "r")!!.use { afd ->
    extractor.setDataSource(afd.fileDescriptor, afd.startOffset, afd.length)
}
val track = (0 until extractor.trackCount).first {
    extractor.getTrackFormat(it).getString(MediaFormat.KEY_MIME)!!.startsWith("video/")
}
extractor.selectTrack(track)
extractor.seekTo(windowStartUs, MediaExtractor.SEEK_TO_PREVIOUS_SYNC)
// Then feed samples to one MediaCodec decoder and keep each frame up to windowEndUs.

Seeking and cutting run into the same fact: phone and WhatsApp videos often carry a keyframe only every 5 to 8 seconds, and a frame between keyframes can't be shown on its own.

The biggest saving wasn't time but space. After a session, Keep the shots replaces the recording with a copy of only the shots, at full quality. It's a stream copy, a MediaExtractor into a MediaMuxer, so nothing is decoded or re-encoded. Four things to know if you do the same:

And three smaller ones from the player. Let a tap anywhere on the picture play or pause: PlayerView can swallow the touch, so draw a transparent layer over it, under the buttons, hidden from TalkBack. Cancel the pending seek when a drag ends: a slider that debounces its seeks must drop the last one on release, or it lands 40 ms after Play. Keep files an export reads in filesDir, not cacheDir: Android clears the cache when the phone is nearly full, even mid-render, and an end card's image once vanished five seconds before Media3 read it.

Edge models: small, optional and on the phone

CricCuts runs three open-source machine-learning models on the phone: a body model (Google's MediaPipe Pose Landmarker), a words model (Vosk, for offline speech recognition) and a voice-activity model (Silero VAD). Nothing is uploaded: the video, the audio and the results stay on the phone. The interactive course How CricCuts works explains each model. Here's what shipping them on Android taught me:

For the bigger picture, see why the future of AI is small models on the edge and many small models working together.

Speech in: voice that never leaves the phone

Every voice feature in CricCuts runs on the phone:

Android has two speech recognisers, and the difference matters. The ordinary SpeechRecognizer may send audio to a server. From Android 12, createOnDeviceSpeechRecognizer runs on the phone. Voice search and voice review use only the on-device one:

if (!SpeechRecognizer.isOnDeviceRecognitionAvailable(context)) {
    showTypedSearchOnly()   // no quiet fallback to a recogniser that may upload audio
    return
}
// Every SpeechRecognizer call must be made on the main thread.
val recognizer = SpeechRecognizer.createOnDeviceSpeechRecognizer(context)

The lesson: "on-device" is a promise to users, not a preference. Where on-device recognition isn't available (every phone below Android 12, and some above it), CricCuts has no voice, only typed search. A quiet fallback to createSpeechRecognizer would break the promise without anyone noticing. Voice search never records, stores or uploads what you say.

Speech out: a phone that reads to you

Text-to-speech is older and on almost every phone, but it has its own traps. CricCuts uses the phone's own voice for three things:

Voices differ by phone and by language. Ask before you read: LANG_MISSING_DATA means the engine knows the language but the phone hasn't downloaded it. CricCuts says so before reading anything, and offers Get voice, which opens the engine's one-time download. Check every installed engine, not only the default one, since another may already have the voice:

when (tts.isLanguageAvailable(locale)) {
    TextToSpeech.LANG_MISSING_DATA ->   // known, not downloaded
        offerGetVoice(Intent(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA).setPackage(enginePackage))
    TextToSpeech.LANG_NOT_SUPPORTED -> tryTheNextEngine()
    else -> read()
}

Two smaller lessons. UtteranceProgressListener.onRangeStart tells you which words are being spoken, which is how you highlight the line being read. And a reader that keeps going with the screen off needs a foreground service and a MediaSession, so the lock screen and headphones can pause it. The lessons in Hindi, Marathi, Tamil, Kannada and Telugu sit beside the English, and Read aloud reads both. Those translations are drafts, and corrections are welcome.

Art drawn in Kotlin

No illustration files sit behind CricCuts' backdrop scenes. Every scene is a painting drawn by code, on your phone, that moves through your clip, and in many of them the moment you hit the ball sets something off. More than 30 ship in version 1.4.

Bengaluru Nights, a backdrop scene drawn in code, a frame from the app. Grey marks where your footage plays.
Bengaluru Nights, a frame from the app. Grey marks where your footage plays.

Most of it is drawn with Android's plain Canvas API, frame by frame, and Media3 lays each frame over the video as an overlay when the reel is exported. The few effects that bend the video itself, like a colour split, are OpenGL shaders. Home's four looks (Floodlights, Daylight, Scoreboard and Super Over) and the Science Lab's simulators of spin, swing and power hitting are drawn with Compose's Canvas too. What it taught me:

Interactive courses, built in Compose

The Academy is the other half of the app. It has courses on the science of spin, swing and power hitting, on training, food, the body and the mind, on the Laws and umpiring, and on history. A Code Lab teaches algorithms (steps, loops, conditions, searching, sorting, bugs) by thinking like a scorer, without a computer. None of it is a web view. Every lesson is native Compose, so it can use the phone: simulators you drag and play with, the Pocket Lab's sensor experiments, the LBW game, a quick check at the end of each lesson, and practice mock tests in the style of JEE Main at College level (practice only, never official).

Letting agents in: a link for every page, and 15 shortcuts

Assistants and AI agents mostly can't tap through your app yet, but they can open a link. So every page of CricCuts has one: criccuts.com/go/ plus one word, like /go/laws, /go/pace or /go/dls. They're verified Android App Links, so on a phone with CricCuts the link opens that page of the app. Anywhere else, it opens a web page with an "Open in CricCuts" button. Search works the same way: /go/search?q=yorkers.

<capability android:name="actions.intent.OPEN_APP_FEATURE">
    <intent android:action="android.intent.action.VIEW"
            android:targetPackage="com.criccuts"
            android:targetClass="com.criccuts.MainActivity">
        <url-template android:value="https://criccuts.com/go/{feature}" />
        <parameter android:name="feature" android:key="feature" />
    </intent>
</capability>

What I'd tell anyone doing the same:

Next: App Functions

Android's own answer for agents is AppFunctions. An app declares typed functions with the Jetpack androidx.appfunctions library, the library generates a schema that Android indexes, and an assistant holding the EXECUTE_APP_FUNCTIONS permission can find and call them. It needs Android 16 or later. As of Google's documentation in May 2026, Gemini's support is a private preview with trusted testers.

The plan for CricCuts is small and deliberate:

// A sketch, not shipped: the library is in alpha and its API may change.
class CricCutsFunctions {
    /** Opens one page of CricCuts, such as "laws" or "pace". */
    @AppFunction
    suspend fun openSection(appFunctionContext: AppFunctionContext, page: String): Boolean =
        AppLinks.resolve(page)?.let { open(it); true } ?: false
}

Twelve lessons I'd pass on

  1. Read sensors only while a screen needs them, and smooth them with hysteresis before you act.
  2. Never change what someone is reading without asking.
  3. Ask the theme for a role, never a colour, and remember that Compose's default text colour is black.
  4. To read many frames, decode in order with MediaCodec; don't seek for each one. And know where the keyframes are, because seeks and cuts land on them unless you say otherwise.
  5. Ask the phone, don't assume from the version: the vibrator for its primitives, the recogniser for on-device mode, the speech engine for the language.
  6. "On-device" is a promise. Remove a feature rather than fall back to a server.
  7. Test on the oldest and oddest phones you support. Android 8 and a tablet with no vibration motor found more bugs than any flagship did.
  8. Native libraries carry the risk: 16 KB pages and missing C functions. Audit every .so.
  9. A big composable can fail at class load with a VerifyError whose message is misleading. Compose keeps every parameter of a restartable composable alive to the end of the function, and too many run the verifier out of registers. Group the parameters into small holder classes.
  10. Create app-wide Compose state on the main thread, before setContent. When an analytics call off the main thread was the first to touch the chosen look, its state was created after the first composition's snapshot, and about one cold start in four crashed.
  11. Guard every range you build from media metadata. A shot that ran past a video's real end made an empty range, and coerceIn() threw.
  12. Give every page a link. It's the cheapest way into assistants today, and the foundation App Functions will build on.

Questions

Do Android apps need a permission to read the light sensor or the accelerometer?

No. The light sensor, the accelerometer, the gravity sensor and the gyroscope need no runtime permission. The camera, the microphone and location do. From Android 12, an app that wants motion sensors faster than 200 readings a second must also declare the HIGH_SAMPLING_RATE_SENSORS permission. Either way, read a sensor only while the screen that uses it is showing.

What's the fastest way to read many frames from a video on Android?

Decode them in order. MediaMetadataRetriever.getFrameAtTime seeks back to a keyframe and decodes forward again for every frame you ask for, which took about a third of a second a frame on our footage. A MediaExtractor feeding one MediaCodec decoder reads a whole stretch of video in a single pass. Open a content:// video through an AssetFileDescriptor, and turn each frame by the track's rotation before you use it.

Can Android speech recognition work offline, on the phone?

Yes, from Android 12. SpeechRecognizer.createOnDeviceSpeechRecognizer runs on the phone, and isOnDeviceRecognitionAvailable says whether this phone can, which also depends on the language being downloaded. The ordinary recogniser may send audio to a server, so an app that promises nothing leaves the phone should turn voice off where on-device recognition is missing, rather than fall back.

How can an AI assistant open a page inside my Android app?

Today, with verified Android App Links: give each page its own https link, and an assistant or agent that opens the link lands on that page. Static shortcuts with App Actions capabilities list the most important pages for launchers and assistants. Next comes AppFunctions, on Android 16 and later, where an assistant calls typed functions your app declares. Gemini support for it is still a preview for selected testers.

See it on your own phone

CricCuts is free on Google Play, for Android phones. Tilt Home, try the Pocket Lab, ask it for the Laws.

Comments

Thoughts, questions, corrections — all welcome. No account needed.