# 2. Android Architecture

### **Android Applications Layer:**

The **Android Applications Layer** is the topmost layer of the Android architecture. It includes all the applications that run on the device, providing the interface and functionality that users interact with directly. These applications rely on the services and frameworks provided by the underlying layers.

#### **Types of Applications:**

1. **Pre-installed Applications (System Apps):**
   * These are apps that come bundled with the device by the manufacturer or vendor.
   * Typically essential for basic device functionality (e.g., Phone, Messages, Settings).
   * **Storage Location:** Found in the `/system/app` or `/system/priv-app` directories.
   * **Characteristics:**
     * Cannot be uninstalled by the user (without rooting).
     * Often granted elevated permissions by default, such as accessing system resources.
2. **Third-Party Applications (User-installed Apps):**
   * Apps installed by the user from external sources, such as the **Google Play Store**, **APK files**, or using **ADB commands**.
   * **Storage Location:** Found in the `/data/app` directory.
   * **Characteristics:**
     * Installed by the user based on their needs (e.g., social media, games).
     * Subject to the Android security model, including permission checks.

***

### **Application Framework:**

The **Application Framework** layer in Android provides a structured environment for app developers. It consists of APIs, classes, and precompiled code essential for building Android applications. This layer acts as the **bridge between applications and the Android runtime environment (Dalvik/ART)** while also facilitating seamless communication between applications and hardware resources.

#### **Key Functions of the Application Framework:**

1. **API and Class Library:**
   * Provides developers with ready-to-use APIs and classes to simplify app development.
   * Includes functions for UI design, data handling, hardware access, and more.
2. **Glue Between Applications and Dalvik/ART:**
   * Acts as an intermediary, enabling apps to interact with the Android runtime environment (Dalvik or ART) efficiently.
3. **Hardware and System Access:**
   * Facilitates communication between applications and hardware components like GPS, camera, sensors, and Bluetooth.
   * Abstracts the complexity of hardware interactions, allowing developers to focus on app logic.

#### **Key Components of the Application Framework:**

1. **Activity Manager:**
   * Manages the lifecycle of applications and activities.
   * Handles app switching, resource allocation, and process control.
2. **Resource Manager:**
   * Provides access to non-code resources such as strings, layouts, images, and themes.
   * Ensures efficient memory usage and supports localization.
3. **Notification Manager:**
   * Enables apps to create and display notifications in the status bar or as pop-ups.
   * Supports features like action buttons, priorities, and notification channels.
4. **Package Manager:**
   * Handles the installation, updating, and removal of apps.
   * Provides metadata about installed apps, such as permissions, version, and package name.
5. **Content Providers:**
   * Facilitates data sharing between applications.
   * Allows apps to query or modify shared data, such as contacts or media files.
6. **Location Manager:**
   * Manages location-based services, enabling apps to access GPS or network-based location data.
7. **View System:**
   * The foundation for building user interfaces, managing UI components like buttons, text fields, and menus.

***

### **Application Runtime (Dalvik VM - ART):**

The **Application Runtime** layer is where Android applications are executed. It consists of two main components: **Dalvik Virtual Machine (DVM)** / **Android Runtime (ART)**, which are responsible for running and managing the execution of compiled Android applications. The runtime provides the environment where all the code runs and interacts with system resources.

#### **Compilation Process:**

1. **Java Code to Dalvik Executable (.dex):**
   * When Android applications are developed in Java, the source code is compiled into an intermediate format.
   * The **Java code** is compiled into **bytecode**, which is then converted into **Dalvik Executable (DEX)** files, with the extension `.dex`.
   * These `.dex` files are optimized for mobile devices, offering a compact format suitable for low-memory and resource-constrained environments.
2. **Dalvik Virtual Machine (DVM):**
   * The **Dalvik VM** is an interpreter that reads and executes `.dex` files. It was used in earlier versions of Android (prior to Android 5.0).
   * It uses a **Just-In-Time (JIT)** compiler to translate Dalvik bytecode into machine code on the fly.
   * While the Dalvik VM offered good performance for its time, it was eventually replaced by **ART** in newer versions of Android.
3. **Android Runtime (ART):**
   * **ART** replaced Dalvik VM starting from Android 5.0 (Lollipop) to improve performance and efficiency.
   * ART uses **Ahead-Of-Time (AOT)** compilation, which compiles the application's code into native machine code before it is executed.
   * AOT compilation improves the app's startup time and runtime performance, reducing the need for runtime interpretation.
   * ART also includes features like **garbage collection** and **memory management**, contributing to better memory efficiency and smoother app performance.

#### **Key Components of the Application Runtime Layer:**

1. **Java Libraries:**
   * Android applications are developed in Java (or Kotlin, which is interoperable with Java). The Java libraries provide essential functions for app development, such as file handling, data processing, networking, and more.
   * These libraries are part of the Android SDK and interact with the Android API to provide the necessary functionalities for apps.
2. **Android Libraries:**
   * In addition to Java libraries, Android includes **specific libraries** built to interact with the Android framework and APIs. These libraries are optimized for Android devices, offering specialized functionality for tasks like:
     * **User Interface (UI) Design:** Libraries for creating and managing UI components such as buttons, text fields, and layouts.
     * **Multimedia:** Libraries for handling images, audio, and video.
     * **Sensors and Hardware Access:** Libraries for interacting with the device's hardware sensors, such as GPS, accelerometer, and camera.
     * **Security and Encryption:** Libraries that provide access to cryptographic functions, key storage, and secure communication protocols.

***

### **Platform Libraries (User-space Native Code):**

The **Platform Libraries** layer in Android consists of **native code** written in **C**, **C++**. These libraries are designed to provide low-level system functionalities, crucial for managing hardware resources and enabling advanced features in Android applications. They are compiled into **shared object files** (.so), which are dynamically loaded at runtime, similar to dynamic link libraries (**.dll**) in other operating systems.

These libraries are vital for optimizing app performance and enabling specific operations that require close interaction with hardware or specialized algorithms. They also offer system-level services and functions that can be imported and used by Android applications.

#### **Shared Object (.so) Files:**

* In Android, the platform libraries are typically compiled into **shared object files** (.so). These files contain precompiled native code, and their purpose is to provide reusable functionality across different applications or system processes.
* Shared object files can be dynamically loaded into an application at runtime using mechanisms such as the **Java Native Interface (JNI)**, which allows Java code to interact with native code written in languages like C or C++.
* These shared libraries are often packaged inside APK files (specifically in the `/lib/` directory), and they are loaded into memory when the application starts or when needed.

#### **Key Components of Platform Libraries:**

1. **System Services:**
   * The **system services** provided by platform libraries include various background processes that are essential for the operation of the Android system. These services typically run with elevated privileges and provide core functionality for network management, device interaction, and more.
   * **Examples of system services:**
     * **`dhcpd`**: The **Dynamic Host Configuration Protocol Daemon** manages IP address allocation for devices on a network, enabling communication and networking.
     * **Audio services**: Handling audio playback, recording, and hardware control.
     * **Sensors services**: Managing access to device sensors, like accelerometers and gyroscopes.
     * **Bluetooth and Wi-Fi services**: Handling communication over Bluetooth and wireless networks.
2. **Libraries:**
   * Platform libraries also include general-purpose libraries that provide core functionality for various operations, including rendering, cryptography, and network communication.
   * **Examples of libraries:**
     * **WebKit**: A **web rendering engine** used for displaying web content. WebKit is used by Android’s **WebView** component to display webpages within apps.
     * **OpenSSL**: A widely-used **cryptographic library** that provides essential encryption and decryption algorithms. OpenSSL is used for implementing secure communications, such as SSL/TLS protocols, ensuring that data is securely transmitted over networks.
     * **libc**: The standard C library, which provides basic functionality like memory management, file I/O, and string manipulation.
     * **SQLite**: An embedded database engine used in Android apps to handle local data storage.
     * **Zlib**: A library for data compression and decompression, often used in Android to handle file and data compression tasks.
3. **Native Code Libraries:**
   * Many performance-critical tasks in Android apps are offloaded to native code. This is especially common in applications that require intensive computational power, such as games or media processing apps.
   * **Examples of native code libraries** include **OpenGL ES** for 3D rendering, **FFmpeg** for multimedia processing, and **TensorFlow Lite** for machine learning tasks.

***

### **Linux Kernel:**

The **Linux Kernel** is the core of the Android operating system. It provides the fundamental system services and acts as an intermediary between the application layer and the underlying hardware. The kernel is responsible for managing hardware resources, ensuring secure execution of applications, and enabling communication between software and hardware components.

Android's kernel is based on the Linux kernel but includes several modifications to optimize it for mobile devices, such as enhanced power management, security features, and support for specific hardware components.

#### **Key Responsibilities of the Linux Kernel in Android:**

1. **Hardware Abstraction:** The Linux Kernel interacts directly with the hardware and provides an abstraction layer that allows higher-level software, such as Android applications, to access hardware components without needing to deal with low-level hardware details. This abstraction makes the hardware resources available through standardized interfaces, so developers don't need to write device-specific code.
2. **Device Drivers:**

   The kernel includes **device drivers** that handle communication with hardware components like:

   * **Bluetooth**: Allows applications to communicate with Bluetooth devices for tasks like file transfers, streaming audio, or pairing with other devices.
   * **Camera**: Handles the integration with the device's camera hardware, enabling applications to capture images and videos.
   * **Audio**: Manages audio input and output, allowing applications to play sound, record audio, or interact with other audio devices like Bluetooth speakers and headphones.
   * **Sensors**: Coordinates the data from various sensors such as accelerometers, gyroscopes, and proximity sensors.
   * **Touchscreen**: Controls the input from the touchscreen, processing gestures and touch events.
3. **Memory and Process Management:** The Linux kernel ensures that memory and processing resources are allocated properly between different applications, services, and hardware tasks. It uses sophisticated techniques like virtual memory, process scheduling, and resource isolation to ensure system stability and responsiveness.
4. **Security and Access Control:**

   Android’s Linux kernel plays a crucial role in system security. It implements mechanisms like:

   * **SELinux (Security-Enhanced Linux)**: Provides mandatory access control (MAC) to restrict the actions of processes and limit their access to system resources.
   * **App Sandbox**: Every Android application runs in its own isolated process, and the kernel ensures that these applications cannot interfere with each other or access sensitive data from other apps or system processes.
5. **Power Management:** The kernel also manages the power consumption of the device, implementing policies that help extend battery life by controlling hardware components and optimizing system performance.
