How does an application run on Android OS?

·

2 min read

Android APK is a file format(typically zip) containing the app's source code and resources.

Generally, Java/Kotlin code will be compiled into java bytecode. So we need a Virtual Machine to run the bytecode.

Android has an optimized runtime environment (like a virtual machine) to execute the compiled app instead of a Java VM. So android doesn't accept java byte code. It needs a different format based on the runtime.

  • Dalvik VM

  • Android Runtime (ART)

Let's see about them.

Dalvik VM

Dalvik VM is an optimized virtual machine for android to run android applications. It executes the .dex files.

Android APK contains the compiled app code in DEX format. You can check that by unpacking your apk and seeing the list of .dex files in it.

Your app code conversion happens in the following way.

.java / .kt (source) ---> .class (bytecode) ---> .dex ---> Dalvik VM ---> machine code

  • Dalvik uses JIT (Just In Time) compilation for translating the dex code into machine code to execute.

  • Whenever your app runs, Dalvik will JIT compile the part of the code which will run instead of the complete code.

  • Since Dalvik VM interprets the DEX every time the app runs, it gives a lower performance than native code execution. (like why python is slower than C++).

  • It's deprecated in Android 5.0

Android Runtime (ART)

ART is introduced to solve the performance issue of Dalvik VM. It enables android applications to run natively.

There is no change in the APK. ART is also using the DEX format under the hood.

  • ART uses Ahead-of-time compilation (AOT) to compile apps into an ART-specific file format called oat at the time of app installation.

  • ART uses the dex2oat tool to compile the oat files for an app.

  • oat file is an executable file format which contains the AOT compiled code of the app. Technically, it's an ELF file.

  • After that, the app code will be executed from the compiled oat file directly.

Your app code conversion happens in the following way

.java/kt (source) ---> .class (bytecode) ---> .dex ---> .oat ---> ART (execution)

  • It has a better performance than Dalvik since it runs the code natively.

  • It is the default runtime in Android 5.0+.

Difference between Dalvik and ART

image source: Wikipedia

A lot to learn in Android Runtime. A deep dive guide for another day.

Thanks for Reading ❤️

Did you find this article valuable?

Support Android with Dhina17 by becoming a sponsor. Any amount is appreciated!