How I built Pebble: a Jetpack Compose cat you can pet, feed, wash and call to your bed from a second phone, using Canvas animations and Android NSD, with no server.♦You hand someone your phone and say, “Go on, feed the cat.” They don’t touch your screen. They open an app on their phone, tap a fish, and on yours a little grey kitten leans into a bowl and starts chomping.
Can two phones do that with nothing in between? No backend, no login, no pairing dialog?
That’s Pebble. Pebble is a small grey kitten who lives on one phone. A second phone becomes her remote. From the remote you can:
- Pet her, tickle her, make her jump
- Give her a shower, some food, or a brush
- Call her to your room, where she walks out of her door, comes in through yours, and hops onto your bed
- Ask her to groom on your bed: she licks her paw and washes her face
There’s no server, no account, and no Bluetooth pairing. The two phones find each other on the Wi-Fi and talk directly.
♦Remote on the left, Pebble on the right. Every tap travels over the Wi-Fi and plays on her phone within a few milliseconds.There are two halves to this, and I’ll go through both:
- Drawing and animating Pebble with Compose Canvas: one data class, one draw function, seven actions
- Connecting two phones with Android’s Network Service Discovery (NSD)
- Sending Pebble between phones without ever showing two cats
- Lessons from testing that changed the design
All the code is Kotlin and Jetpack Compose.
The Big Picture♦Two phones, two jobs. Pebble’s phone owns the cat. The remote asks, but never decides.If you take one idea from this article, take the one in that caption: Pebble’s phone is the single source of truth. It owns her stats (food, clean, happy) and, more importantly, where she is. The remote sends requests like “feed her” or “come here”, then draws whatever the cat’s phone reports back.
Almost every design choice below comes back to that.
Part 1: Drawing PebbleEverything Is Drawn in CodePebble has no image assets. She’s ovals, triangles, arcs and a few paths drawn on a Compose Canvas. That sounds like a constraint, but it's what makes her animatable: every ear, eye and paw is a number I can change per frame.
The trick that keeps this manageable is separating what Pebble is doing from how she’s drawn.
One Data Class for Body Languagedata class CatPose(
val lift: Float = 0f, // how far off the ground (jumping)
val squashX: Float = 1f, // squash and stretch
val squashY: Float = 1f,
val sway: Float = 0f, // side-to-side wiggle
val headTilt: Float = 0f,
val headDip: Float = 0f, // head lowered, e.g. eating
val eyes: Eyes = Eyes.OPEN, // OPEN, CLOSED, HAPPY, WIDE, LAUGH
val mouth: Mouth = Mouth.SMILE,
val earDroop: Float = 0f,
val tail: Float = 0f, // degrees
val pawLift: Float = 0f,
val wet: Float = 0f, // 0 = fluffy, 1 = soaked
val blush: Float = 0.35f,
val lookX: Float = 0f,
val groomPaw: Float = 0f, // grooming: raised paw...
val groomX: Float = 0f, // ...and where it is on the face
val groomY: Float = 0f,
)
CatPose is one frame of body language, and nothing more. It knows nothing about Canvas, time or networking.
♦Animations only produce data. One function turns the data into pixels.Every frame goes through the same pipeline:
- catPose() takes the clock, the current action and its progress, and returns a CatPose.
- drawEffectsBehind() draws props that sit behind her: the food bowl, the shower water.
- drawCat(pose) draws Pebble herself.
- drawEffectsFront() draws things in front: the petting hand, the feather, hearts, sparkles.
This split is why a new action is just one more when branch. The drawing code never changes. When I added grooming late in the project, drawCat only needed to learn how to draw a raised paw.
Idle Life: Breathing, Blinking, a TailA cat that stands perfectly still looks like a sticker. Before any action plays, catPose() builds an idle pose from a free-running clock:
val breathe = sin(clock * 2.1f) * 0.018f
val blink = (clock % 4.3f) < 0.13f
val idle = CatPose(
squashY = 1f + breathe,
squashX = 1f - breathe * 0.5f,
tail = sin(clock * 1.6f) * 14f,
eyes = if (blink) Eyes.CLOSED else Eyes.OPEN,
mouth = if (hungry) Mouth.FLAT else Mouth.SMILE,
earDroop = if (hungry) 0.35f else 0f,
headTilt = sin(clock * 0.7f) * 3f,
lookX = sin(clock * 0.45f) * 0.6f,
)
Each line is tiny, but together they make her feel alive:
- Breathing is a 1.8% vertical squash. When she gets taller, she also gets slightly narrower (squashX moves the opposite way), so her volume stays roughly constant. That's the oldest rule in animation, and it's why the motion reads as soft.
- Blinking happens for 0.13 seconds every 4.3 seconds. Regular enough to notice, not so regular it feels mechanical.
- The tail, head and eyes all use different, unrelated speeds (1.6, 0.7 and 0.45). Because the rhythms never line up, she never repeats an obvious loop.
- Mood shows up in the idle pose. A hungry Pebble has a flat mouth and droopy ears, and a little thought bubble with a fish appears above her.
Every action then starts from idle.copy(...) and overrides only what it needs, so she keeps breathing and blinking through most actions.
The Animation Recipe: One Progress ValueEvery action has a duration and a progress value p that runs from 0 to 1:
val p = ((now - actionStart).toFloat() / action.durationMs).coerceIn(0f, 1f)
Two small helpers split that progress into phases:
private fun seg(p: Float, from: Float, to: Float) = ((p - from) / (to - from)).coerceIn(0f, 1f)
private fun ease(x: Float) = (1 - cos(x.coerceIn(0f, 1f) * PI.toFloat())) / 2f
seg(p, 0.22f, 0.72f) answers "how far through the middle part of this action are we?", from 0 to 1. ease turns a straight line into a smooth start and stop. With these two functions, every action becomes a short list of phases.
Take the jump.
♦One progress value, three phases. Squash and stretch do most of the work.CatAction.JUMP -> {
val crouch = seg(p, 0f, 0.22f)
val air = seg(p, 0.22f, 0.72f)
val land = seg(p, 0.72f, 1f)
val lift = if (p in 0.22f..0.72f) sin(air * PI.toFloat()) * 130f else 0f
val (sx, sy) = when {
p < 0.22f -> (1f + 0.18f * ease(crouch)) to (1f - 0.2f * ease(crouch))
p < 0.72f -> (0.9f + 0.1f * air) to (1.14f - 0.14f * air)
else -> {
val k = sin(land * PI.toFloat()) * (1f - land)
(1f + 0.22f * k) to (1f - 0.24f * k)
}
}
idle.copy(lift = lift, squashX = sx, squashY = sy, /* eyes, ears, tail… */)
}Walk through it:
The crouch (anticipation). Before she jumps, she gets wider and shorter. Without this, the jump looks like she’s been lifted by a string.
The air. sin(air * π) goes up and back down in one smooth arc, so the height needs no physics. She's stretched tall at take-off and gradually returns to normal shape.
The landing. sin(land * π) * (1 - land) is a quick squash that fades out, so she bounces once and settles. Dust puffs appear at take-off and landing in drawEffectsFront.
Her eyes go wide in the air and her ears flick back. Leave those two out and she looks like she’s being lifted on a string.
Seven Actions♦Every action is a when branch in catPose() plus a few props in the effects functions.Each action has one idea at its core:
- Pet. A hand strokes back and forth above her head (sin(t * 4.2f)). Her eyes close into happy arcs, her ears flatten, and hearts float up with staggered phases so they never move in lockstep.
- Tickle. Everything speeds up: her body wiggles at sin(t * 32f), her paws kick, her eyes become > <, and "he he" pops up. A feather wiggles at her side.
- Jump. Anticipation, stretch, squash, as above.
- Shower. Two phases. For the first 72%, water streams down from a shower head, bubbles build up around her outline, her fur darkens and spikes up (wet goes from 0 to 1), and her ears droop. Then she shakes: a fast, fading side-to-side sway, with droplets flying out radially.
- Food. A bowl slides in from the left, her head dips (headDip), and she chomps in rhythm: the mouth alternates between NOM and SMILE with sin(t * 13f). The kibble count in the bowl goes down as p goes up, and the bowl slides away at the end.
- Clean. A brush sweeps over her in arcs, leaving sparkles behind, and a burst of sparkles marks the finish.
- Groom. Covered in Part 3.
Here’s the shower’s two-phase pose, because it shows how much a single wet value can carry:
CatAction.SHOWER -> {
val washing = p < 0.72f
val shake = seg(p, 0.72f, 1f)
val wet = if (washing) ease(seg(p, 0f, 0.3f)) else 1f - 0.85f * shake
idle.copy(
wet = wet,
eyes = if (washing) Eyes.CLOSED else Eyes.LAUGH,
earDroop = if (washing) 0.9f else 0.2f,
sway = if (!washing) sin(t * 46f) * 12f * (1f - shake) else 0f,
)
}Inside drawCat, wet blends her fur colour towards a darker grey with lerp(Fur, FurWet, pose.wet), and draws little spikes of wet fur on her head. One number, two visual effects, and it dries smoothly as she shakes.
Part 2: Two Phones, No ServerWhy NSDThe obvious way to connect two phones is a backend. But Pebble and her remote are usually in the same room, on the same Wi-Fi. Sending every “pet the cat” through a server on the internet would add delay, cost and an account system, for two devices a few metres apart.
Android has a built-in alternative: Network Service Discovery (NSD). It’s Android’s API for DNS-SD over multicast DNS, the same mechanism your laptop uses to find a printer. A device announces a service on the local network; other devices discover it, resolve it to an IP address and port, and then connect with a normal socket.
♦Only the remote discovers. Pebble’s phone only announces and listens.Step 1: Pebble’s Phone Announces Herselfprivate fun register(port: Int) {
val info = NsdServiceInfo().apply {
serviceName = "$catName at ${deviceName()}" // "Pebble at Pixel 7"
serviceType = PET_SERVICE_TYPE // "_petpal._tcp"
setPort(port)
setAttribute("v", PROTOCOL.toString()) // TXT record: protocol version
setAttribute("cat", catName) // TXT record: the cat's name
}
val listener = object : NsdManager.RegistrationListener {
override fun onServiceRegistered(info: NsdServiceInfo) {
_announcedAs.value = info.serviceName // may differ from what we asked for
}
// …failure callbacks
}
registration = listener
nsd.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)
}Three details here matter:
Open the socket first. You can’t announce a port you don’t have, so PetHome opens a ServerSocket on a background thread and registers once it knows the port.
The name you get back can differ. If another phone on the network already uses “Pebble at Pixel 7”, Android renames yours. The real name only arrives in onServiceRegistered, so that's what the screen shows.
The TXT record carries metadata. Pebble’s phone attaches a protocol version and the cat’s name. The remote can show “Pebble” in its list before it has even connected, and refuses to connect to a cat running an incompatible build.
Step 2: The Remote Discovers and Resolvesoverride fun onServiceFound(info: NsdServiceInfo) {
// serviceType comes back with a trailing dot: "_petpal._tcp."
if (info.serviceType.startsWith(PET_SERVICE_TYPE)) resolve(info)
}That trailing dot is an easy trap: you ask for "_petpal._tcp", and Android reports "_petpal._tcp.". A strict == silently drops every cat. Use startsWith.
Resolving turns the name into an address, and the API depends on the Android version:
private fun resolve(info: NsdServiceInfo) {
if (Build.VERSION.SDK_INT >= 34) {
val callback = object : NsdManager.ServiceInfoCallback {
override fun onServiceUpdated(resolved: NsdServiceInfo) {
resolved.hostAddresses.firstOrNull()?.let { onResolved(resolved, it) }
}
// …other callbacks
}
infoCallbacks += callback
nsd.registerServiceInfoCallback(info, onMain, callback)
} else {
// Before Android 14, only one resolve can run at a time. Queue the rest.
main.post { resolveQueue.addLast(info); resolveNextLegacy() }
}
}- Android 14 and newer use registerServiceInfoCallback. It's a subscription: it updates if the cat's phone changes networks, and you unregister it when the screen closes.
- Older versions use the deprecated resolveService, which fails with FAILURE_ALREADY_ACTIVE if you start a second resolve before the first finishes. Two cats on the network, two resolves at once, and one silently never appears. A small queue fixes it.
♦One app, two roles. The remote searches the Wi-Fi, connects, and shows live stats. Pebble’s phone shows its own address for typing in by hand.Step 3: One Socket, Two Kinds of MessagesOnce resolved, the remote opens a plain TCP socket. From here, NSD’s job is done.
Every message is one JSON object on one line. A small LineSocket class gives each connection a reader thread and a writer thread with an outbox queue, so the UI never blocks on the network.
The two directions are deliberately different:
Remote to cat: commands, only when you tap.
fun act(action: CatAction) = send(JSONObject().put("type", "action").put("name", action.name))
fun summon() = send(JSONObject().put("type", "summon"))
fun sendHome() = send(JSONObject().put("type", "send_home"))Cat to remote: the whole state, every 150 ms.
LaunchedEffect(home) {
while (isActive) {
home.broadcast(brain.status("Pebble"))
delay(150)
}
}Why stream the whole state instead of sending events like “food went up”? Because a status message is self-contained. A remote that connects late, or misses a message, is correct again 150 ms later. There’s no history to replay and nothing to get out of sync. At a few hundred bytes, seven times a second, it costs nothing on a local network.
On my emulators, the round trip between the two phones was 1 to 3 ms.
Part 3: Sending Pebble to Your BedThe Rule: One Phone Decides Where Pebble Is“Come here” is the most fun feature, and the easiest one to get wrong. If both phones could decide where Pebble is, a badly timed message could leave her in both rooms, or in neither.
So the cat’s phone holds a tiny state machine, and nobody else can change it:
♦fun summon(from: String, now: Long) {
if (where != Where.HOME) return
action = null
visitor = from
setWhere(Where.LEAVING, now)
}
fun tick(now: Long, dtMs: Long) {
// …stats slowly drain…
if (where == Where.LEAVING && now - whereSince > LEAVE_MS) setWhere(Where.AWAY, now)
if (where == Where.RETURNING && now - whereSince > LEAVE_MS) {
setWhere(Where.HOME, now)
arrivedAt = now
}
}summon does nothing unless she's at home. Tap "Call Pebble" twice, or from two remotes at once, and only the first request does anything.
Two Screens, One WalkThe walk itself is shared between the phones:
♦She leaves on one phone, then arrives on the other. Each phone animates its own half.
Here’s the whole trip in motion, including the grooming from later in this part:
♦“Come groom on my bed”, a tickle, then “Send Pebble home”. Where she is only ever changes on her own phone.- LEAVING plays on Pebble’s phone: her door opens, she trots to it, fades into the doorway, and the door closes behind her.
- AWAY plays on the remote: your door opens, she trots in, jumps onto your bed and settles.
Each phone times its half on its own clock, starting from the moment it sees the state change. The remote doesn’t need to know what time it is on the cat’s phone:
var lastWhere by remember { mutableStateOf(s.where) }
var whereChangedAt by remember { mutableLongStateOf(-10_000L) }
if (s.where != lastWhere) {
lastWhere = s.where
whereChangedAt = now
}A few milliseconds of network delay just means her entrance starts a few milliseconds later. Nobody can see that, so I didn’t need clock synchronisation at all.
The walking itself is a layer on top of any pose. A small extension function adds a trotting bounce, faces her in the walking direction and lifts her tail:
fun CatPose.walking(stage: Stage, t: Float): CatPose {
if (stage.trot <= 0f && stage.hop <= 0f) return copy(lookX = stage.dir * 0.4f)
val step = abs(sin(t * 11f))
return copy(
lift = stage.hop + step * 9f * stage.trot,
squashY = squashY - sin(t * 22f) * 0.04f * stage.trot,
lookX = stage.dir,
pawLift = step * 0.45f * stage.trot,
eyes = if (stage.hop > 0f) Eyes.WIDE else eyes,
)
}While She’s on Your BedWhen Pebble is AWAY, the remote plays the animations locally, the moment you tap. The command still goes to her phone, which keeps score (food, clean, happy), but you don’t wait for a round trip to see her react.
♦On your bed, actions play on the remote. “Send Pebble home” walks her back.Groom on My BedThe last command combines everything: “Come groom on my bed”. If Pebble is at home, the remote summons her, waits until she has arrived and settled, then starts grooming:
var groomWhenSettled by remember { mutableStateOf(false) }
if (groomWhenSettled && s.where == Where.AWAY && now - whereChangedAt > ENTER_MS) {
groomWhenSettled = false
remote.act(CatAction.GROOM)
playHere(CatAction.GROOM)
}The grooming itself is the most “cat” animation in the project. She raises a front paw, licks it with her eyes closed, then wipes it over her cheek and ear:
♦Lick the paw, then wash the face. Real cats do it in that order too.CatAction.GROOM -> {
val raise = ease(seg(p, 0f, 0.1f)) * (1f - ease(seg(p, 0.9f, 1f)))
val licking = p < 0.55f
val lick = sin(t * 14f)
idle.copy(
groomPaw = raise,
groomX = if (licking) 0.1f else 0.25f + sin(t * 5f) * 0.55f,
groomY = if (licking) lick * 0.08f else 0.5f + cos(t * 5f) * 0.35f,
eyes = if (licking) Eyes.CLOSED else Eyes.HAPPY,
mouth = if (licking && lick > -0.3f) Mouth.LICK else Mouth.SMILE,
headTilt = if (licking) -8f + lick * 3f else sin(t * 5f) * 9f,
)
}The paw’s position is just two numbers, groomX and groomY. While licking, the paw bobs slightly in front of her mouth. While washing, sin and cos at the same speed move it in a small loop over her face. This was the action that needed a change to drawCat: a raised paw, drawn after the head so it sits in front of her face.
Part 4: What Testing ChangedI ran Pebble on two emulators side by side, and a few things didn’t survive contact with reality.
Queued actions felt brokenMy first version queued actions: tap Pet, then Jump, and the jump waited until the pet animation finished. In testing, a couple of quick taps meant the cat was still being petted while three more commands waited in line. From the remote, it looked like the buttons didn’t work.
The fix was one line of thinking: the newest request wins, straight away.
when (where) {
// The newest request wins straight away: a remote tap should never wait in line.
Where.HOME -> if (now - arrivedAt > ENTER_MS) start(a, now) else { queue.clear(); queue.addLast(a) }
Where.AWAY -> reward(a) // the remote plays the animation; we keep the score
else -> {}
}Animations are built to be interrupted: each one starts from the idle pose, so cutting one short never leaves her stuck mid-pose.
Too much detail in the wrong placesMy first Pebble was too big for the room, and a dirty cat got brown dirt spots all over her fur. On a phone screen, she looked messy rather than cute. I shrank her by about a third and dropped the dirt spots entirely: the Clean bar already tells you she needs a shower.
Then I went the other way with the rooms. Flat colours made them feel empty, so they got soft gradients, a plant, a framed picture, a rug under her cushion and a sunbeam from the window. The difference from the first version is where the detail goes: everything in the room is pale and still, so Pebble is the only thing that moves and the only thing with strong colour. The stat bars changed too: each one now shows its number, so you can tell how she’s doing at a glance.
Buttons should feel physicalThe remote’s buttons shrink when pressed, using a spring with low damping so they bounce back:
val pressed by source.collectIsPressedAsState()
val scale by animateFloatAsState(
if (pressed) 0.88f else 1f,
spring(dampingRatio = 0.4f, stiffness = Spring.StiffnessMedium),
label = "press",
)
On a remote control, buttons that give a little under your thumb make the whole app feel more direct.
GotchasEmulators can’t discover each other. Each Android emulator sits behind its own virtual router, so multicast from one never reaches another. NSD works inside one emulator, but two emulators never see each other. That’s why the remote has a manual address field. To test two emulators, redirect a host port into the cat’s emulator:
adb -s emulator-5554 emu redir add tcp:47831:47830
Then type 10.0.2.2:47831 into the remote (10.0.2.2 is your computer, as seen from an emulator). I prefer emu redir over adb forward because it lives in the emulator, so it survives adb restarts, which Android Studio does more often than you'd think.
Some networks block multicast. Guest Wi-Fi, hotels and many offices isolate devices from each other, so NSD finds nothing. The manual address on Pebble’s screen is the fallback.
Stop everything when the screen closes. Discovery uses battery, and a registered service keeps announcing. Both PetHome and PetRemote are started and stopped from a DisposableEffect, so leaving the screen always cleans up:
val home = remember { PetHome(context.applicationContext, "Pebble") }
DisposableEffect(home) {
home.start()
onDispose { home.stop() }
}Permissions are minimal. The app only needs INTERNET: no location, no Bluetooth, no nearby-devices permission. Newer Android versions are adding a local network permission for apps that target the latest SDK, so check the Android docs before you raise your target SDK.
Wrapping UpPebble is a toy, but the patterns carry over to real apps:
- Separate pose from drawing. One data class describes a frame; one function draws it. New behaviour is new data, not new drawing code.
- Build every animation from one progress value. seg() and ease() turn p into phases, and anticipation, squash and stretch do the rest.
- Give each piece of state one owner. Pebble’s phone owns where she is, so two phones can never disagree.
- Stream state, not events, when the state is small. Late joiners and dropped messages fix themselves.
- Let new input interrupt. Nobody wants to wait for an animation to finish before their tap counts.
- NSD is enough for “same Wi-Fi” apps. Announce, discover, resolve, then it’s just a socket.
Thanks to Kyriakos Georgiopoulos, whose writing on phones that talk without a server got me curious about NSD in the first place. This whole design is also inspired by Kyriakos’s article. You can checkout there page from here kgeorgiopoulos.com/code/
You can write back to me at karishma.agr1996@gmail.com if you’d like me to improve something in my upcoming articles. Your feedback is valuable.
Also, follow me on Medium and Linkedin
Your claps are appreciated to help others find this article 😃 .
♦♦A Cat on One Phone, a Remote on Another was originally published in Code Like A Girl on Medium, where people are continuing the conversation by highlighting and responding to this story.