Android from the foundation · Puzzle 8 of 16

What's inside the APK

Phones have different CPUs, but you ship one APK, one file for every phone. So the APK can't hold code for just one kind of CPU, and something on the phone has to run it.

The problem

You upload one APK (the single file your app is packaged into) to the store, and it runs on phones with very different CPUs. But a CPU only runs instructions (the tiny steps a program is made of) written for that kind of CPU. So what's in the APK, and who makes it run?

See it

The APK holds DEX; it travels into two phones with different CPUs; ART inside each app's process reads it one instruction at a time phone A phone B CPU ACPU B APK DEX DEX DEX CPU can't read DEXCPU can't read DEX ARTART one by oneone by one
  1. On your computer, your Kotlin compiles to DEX: instructions written for Android, not for any one CPU. That's what's inside your APK.

    Step 1 of 4
  2. The same APK goes to phones with different CPUs. Each kind of CPU understands only its own set of instructions, its machine code. Predict: so who runs the DEX?

    Step 2 of 4
  3. ART, the Android Runtime. It lives inside each app's process, on every phone.

    Step 3 of 4
  4. The simplest thing ART can do is interpreting: reading the DEX one instruction at a time. It always works, but it's slow.

    Step 4 of 4

The building block

Each kind of CPU has its own language: machine code. Your APK doesn't contain it. Your Kotlin compiles to DEX, compact instructions written for Android, not for any one CPU.

On the phone, ART, the Android Runtime (the part that runs your code), works inside your app's process and makes the DEX run. The simplest way it does that is interpreting: reading one DEX instruction at a time and doing what it says. That always works, but it's slow.

The analogy

You write your recipes in one common language, so any kitchen can use them. In every house lives a translator, ART, who reads them to the cook word by word.

Check yourself

You ship the same APK to two phones with different CPUs. Why does it run on both?

Not quite. Nobody rebuilds it: ART on the phone runs the same DEX.

Not quite. Then it would only run on the CPUs it was built for. DEX isn't for any CPU.

Right. DEX isn't tied to a CPU; ART on each phone runs it.

Is there one ART for all the apps on the phone?

Not quite. ART lives inside each app's process, like a translator in every house.

Right. Each process has its own ART.

What's the difference between DEX and machine code?

Right. DEX needs ART; machine code needs nothing.

Not quite. DEX has to be run by ART; machine code runs on the CPU directly.

Sources

What you now know

Your Kotlin compiles to DEX, which no CPU runs directly. ART, inside your app's process, runs it: at first by reading it one instruction at a time.