🤖 Unit 1 • Android Mobile Engineering

Introduction to Android: Architecture, Ecosystem & Gradle

A comprehensive foundational masterclass in modern Android OS engineering: The Linux kernel foundation, Hardware Abstraction Layer (HAL), Android Runtime (ART) vs. Dalvik DEX bytecode, the Java API Framework, the 4 fundamental Application Components (Activity, Service, BroadcastReceiver, ContentProvider), API level economics, Android Studio tooling, physical and virtual AVD testing, and Gradle build lifecycle dependency management.

Curriculum: Mobile Software Engineering (Android Track)
Unit: 01 of 15
Prerequisite: Core Java / Kotlin Foundations
Target: Android 14/15 (API Level 34/35)
01

What is Android? History, Features & Ecosystem

📱 Defining the Android Platform

Android is an open-source, Linux-based software stack engineered for mobile touchscreen devices (smartphones, tablets, smart TVs, foldables, and automotive cockpits). Developed collaboratively under the Open Handset Alliance (OHA) and spearheaded by Google, Android consists of:

  • Android Open Source Project (AOSP): The foundational, open-source codebase licensed under the Apache 2.0 license, providing the OS kernel, hardware libraries, runtime, and basic framework.
  • Google Mobile Services (GMS): Google's proprietary suite of cloud-connected applications and cloud APIs (Google Play Store, Play Services, Location Services, Google Maps, and Firebase Cloud Messaging).
📜 Historical Milestones & Core Architectural Features

Founded in 2003 by Andy Rubin, Rich Miner, Nick Sears, and Chris White, Android Inc. initially intended to build an advanced operating system for digital cameras. Recognizing the smartphone revolution, Google acquired Android in 2005. The first commercial device, the HTC Dream (T-Mobile G1), debuted in September 2008 running Android 1.0.

Key Feature Architectural Mechanism Engineering Benefit
Process Sandboxing Linux user ID (UID) isolation per application Malicious apps cannot inspect memory or storage of sibling apps without permissions
Preemptive Multitasking Linux process scheduling + Android LMK (Low Memory Killer) Smooth background service execution without starving foreground user interactions
Hardware Abstraction (HAL) Standard C/C++ driver interfaces Android runs across diverse silicon (Qualcomm Snapdragon, MediaTek, Samsung Exynos, Tensor)
Inter-Process Communication Binder IPC Linux driver High-throughput, shared-memory message passing between isolated application components
02

The 5-Layer Android Architecture Stack

🏛️ The 5-Layer Software Stack

Android is engineered as a layered software architecture, strictly decoupling hardware drivers from high-level application user interfaces:

  1. Linux Kernel (Foundation): Hardened version of the Linux LTS kernel. Manages physical memory, preemptive process threads, hardware driver modules (Display, Camera, Bluetooth, Wi-Fi, Audio), security permissions, and power consumption (Wakelocks).
  2. Hardware Abstraction Layer (HAL): Consists of modular C/C++ interface bridges (e.g., Camera HAL, Audio HAL, Sensors HAL). Exposes high-level hardware device capabilities to the Java framework without exposing device-specific kernel implementation code.
  3. Native C/C++ Libraries & Android Runtime (ART):
    • Native Libraries: High-performance libraries including WebKit/Blink (browser engine), OpenGL ES/Vulkan (3D graphics rendering), SQLite (embedded relational database), and FreeType (font rendering).
    • Android Runtime (ART): The execution engine replacing the legacy Dalvik VM in Android 5.0. Executes DEX bytecode using hybrid Ahead-of-Time (AOT) and Just-in-Time (JIT) compilation with profile-guided optimization.
  4. Java API Framework: The high-level toolkit written in Java/Kotlin exposed to developers: Activity Manager (app lifecycle), Window Manager (surfaces), Content Providers (data sharing), View System (UI buttons/lists), Notification Manager, and Resource Manager.
  5. System & User Applications: The top tier containing pre-installed core apps (Phone, Contacts, Settings) and third-party user applications downloaded from app repositories.
Visual Architecture: The Android 5-Layer Software Stack
5. Applications Tier
Home • Contacts • Browser • Your Custom App (DevAscent App)
▼ High-level API calls ▼
4. Java API Framework
Activity Manager • Window Manager • Content Providers • View System • Notification Manager
▼ JNI & IPC Bridges ▼
3a. Android Runtime (ART)
DEX Execution • AOT + JIT Compilation • Garbage Collector
3b. Native C/C++ Libraries
OpenGL ES / Vulkan • WebKit • SQLite • Media Framework • Libc
▼ Driver Interfaces ▼
2. Hardware Abstraction Layer (HAL)
Camera HAL • Audio HAL • Bluetooth HAL • Sensors HAL • Fingerprint HAL
▼ Kernel Syscalls ▼
1. Linux Kernel (LTS)
Display Driver • Binder IPC • Power Management • Memory Paging • USB / Wi-Fi
03

Android Versions, Code Names & API Levels

🔢 The Triad of Version Configuration

In Android development, operating system versions are identified by three parameters: the Marketing Version (e.g., Android 14), the internal Dessert Code Name (e.g., Upside Down Cake), and the integer API Level (e.g., 34).

Android Version Dessert Code Name API Level Architectural Innovations
Android 5.0 / 5.1 Lollipop API 21 / 22 Introduction of ART runtime replacing Dalvik; Material Design v1
Android 6.0 Marshmallow API 23 Runtime Permissions Model (dynamic user approval), Doze mode power savings
Android 8.0 / 8.1 Oreo API 26 / 27 Project Treble (modularized OS updates), Notification Channels, Background execution limits
Android 10.0 Quince Tart (Q) API 29 Scoped Storage (privacy filesystem sandbox), System-wide Dark Theme, Gesture Nav
Android 12.0 Snow Cone (S) API 31 / 32 Material You (Dynamic color theming), Privacy Dashboard, App Splash Screens API
Android 14.0 Upside Down Cake API 34 Ultra HDR, Selected Photo Access, Non-linear font scaling (200%), Credential Manager
⚙️ minSdkVersion vs. targetSdkVersion vs. compileSdkVersion
  • compileSdkVersion: The version of the Android SDK used to compile your application bytecode. Enables access to newest API classes. Has zero impact on runtime behavior.
  • minSdkVersion: The minimum operating system level required to install and run your app. Google Play blocks installations on devices below this threshold.
  • targetSdkVersion: The API level against which your app was actively tested and verified. Informs the Android OS runtime that your app complies with modern security behaviors (e.g., scoped storage, notification permissions) rather than running in legacy compatibility mode.
04

The 4 Core Android Application Components

🧩 Essential Building Blocks of an Android App

Unlike desktop programs that have a single entry point (main()), an Android application has multiple discrete entry points managed by the operating system through four component types:

1️⃣ Activity (UI Presentation)

Represents a single focused screen with a user interface.

  • Inherits from ComponentActivity or AppCompatActivity.
  • Renders UI via XML layouts (setContentView(R.layout.activity_main)) or Jetpack Compose.
  • Governed strictly by the Activity Lifecycle (onCreate, onStart, onResume, onPause, onStop, onDestroy).
2️⃣ Service (Background Processing)

Executes long-running operations in the background without providing a UI.

  • Foreground Service: Shows a persistent status bar notification (e.g., music playback, GPS navigation tracking).
  • Background Service: Handled in modern Android via WorkManager for deferred, battery-friendly batch tasks.
3️⃣ Broadcast Receiver (Event Listener)

A component that listens for and responds to system-wide broadcast announcements or app-specific events.

  • Examples: Battery low (ACTION_BATTERY_LOW), device booted (BOOT_COMPLETED), network connectivity change.
  • Does not display a UI; typically triggers a status notification or wakes up a WorkManager task.
4️⃣ Content Provider (Data Sharing)

Manages access to a central structured repository of data, enabling secure inter-application data sharing.

  • Encapsulates database access via standard URI syntax: content://contacts/people.
  • Used to query system contacts, gallery media files, and cross-application database records.
05

Android Studio, Project Structure & Testing Devices

🛠️ Android Studio Overview & Key Subsystems

Android Studio is the official Integrated Development Environment (IDE) for Android development, built upon JetBrains IntelliJ IDEA:

  • SDK Manager: Downloads and manages Android SDK platforms, build-tools, platform-tools (ADB), and system images.
  • AVD Manager (Device Manager): Creates and manages Android Virtual Devices (Emulators) running hardware-accelerated QEMU virtualization.
  • Logcat: High-throughput system and application log stream viewer, indispensable for inspecting crash stack traces and debug output (Log.d(), Log.e()).
  • Physical Device Testing: Requires enabling Developer Options (tapping "Build Number" 7 times) and activating USB Debugging. Android Debug Bridge (adb) communicates with the physical handset over USB or Wireless Wi-Fi pairing.
📁 Anatomy of an Android Project Hierarchy

Switching from the simplified "Android View" to the raw "Project View" reveals the filesystem layout:

Project Root Filesystem View
MyApp/
├── app/                              # Application Module
│   ├── manifests/
│   │   └── AndroidManifest.xml       # App identity, permissions, and component declarations
│   ├── java/ (or kotlin/)
│   │   ├── com.devascent.myapp/      # Source code (Activities, ViewModels, Repositories)
│   │   └── (androidTest & test)     # Instrumented & Unit test suites
│   ├── res/                          # Application Resources
│   │   ├── layout/                   # XML UI layout definitions (activity_main.xml)
│   │   ├── drawable/                 # Vector assets (SVG/XML) and bitmaps (PNG)
│   │   ├── mipmap/                   # App launcher icons across screen densities (mdpi, hdpi, xhdpi...)
│   │   └── values/                   # strings.xml, colors.xml, themes.xml
│   └── build.gradle.kts (Module)     # App dependencies, plugins, and compile SDK settings
├── gradle/                           # Gradle Wrapper executable binaries (gradle-wrapper.jar)
├── build.gradle.kts (Project)        # Top-level build config common to all sub-modules
└── settings.gradle.kts               # Module inclusion and repository locations (Google, MavenCentral)
06

Gradle Build System & Dependency Management

🐘 How Gradle Powers Android Compilation

Android Studio utilizes Gradle, an advanced build automation engine that uses Kotlin DSL (.gradle.kts) or Groovy DSL to compile, package, and sign Android binaries (APKs and Android App Bundles - AABs):

  • settings.gradle.kts: Declares dependency resolution repositories (google(), mavenCentral()) and enumerates active modules (include(":app")).
  • Project-level build.gradle.kts: Configures plugins applied across all modules.
  • Module-level build.gradle.kts: The primary workhorse defining application ID, SDK targets, ProGuard minification rules, and third-party dependencies.
app/build.gradle.kts — Production Module Build Configuration
plugins {
    alias(libs.plugins.android.application)
    alias(libs.plugins.kotlin.android)
}

android {
    namespace = "com.devascent.academy"
    compileSdk = 34 // Android 14 SDK

    defaultConfig {
        applicationId = "com.devascent.academy"
        minSdk = 24        // Android 7.0 (Covers >96% of global active devices)
        targetSdk = 34     // Optimized and tested against Android 14 APIs
        versionCode = 1
        versionName = "1.0.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            isMinifyEnabled = true // Enables R8 code shrinking and obfuscation
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
}

dependencies {
    // Core AndroidX & UI Toolkits
    implementation("androidx.core:core-ktx:1.12.0")
    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("com.google.android.material:material:1.11.0")
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")

    // Unit Testing Frameworks
    testImplementation("junit:junit:4.13.2")
    androidTestImplementation("androidx.test.ext:junit:1.1.5")
}
07

Unit 1 Practical Capstone: Hello Android Architecture Blueprint

🚀 Complete Foundation Project: Manifest, Layout & Activity

This complete, verified baseline application demonstrates:
1. AndroidManifest.xml declaring application identity, permissions, and the launch activity.
2. activity_main.xml layout defining a modern Material Design card with action controls.
3. MainActivity.java demonstrating lifecycle initialization and event listener binding.

app/src/main/AndroidManifest.xml — Application Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.devascent.academy">

    <!-- Optional Hardware / Network Permissions -->
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Material3.DayNight">

        <!-- Primary Launcher Activity -->
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
MainActivity.java — Lifecycle & Interaction Controller
package com.devascent.academy;

import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "DevAscent_Main";
    private int telemetryCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Inflate the XML layout into the View hierarchy
        setContentView(R.layout.activity_main);

        Log.d(TAG, "onCreate: Activity successfully instantiated on ART Runtime");

        // Bind UI elements via resource IDs
        TextView statusText = findViewById(R.id.tv_status);
        Button triggerBtn = findViewById(R.id.btn_trigger);

        triggerBtn.setOnClickListener(v -> {
            telemetryCount++;
            String message = "Android Telemetry Ping #" + telemetryCount;
            statusText.setText(message);
            Toast.makeText(MainActivity.this, "Dispatched: " + message, Toast.LENGTH_SHORT).show();
            Log.i(TAG, "User Clicked Action Button: count=" + telemetryCount);
        });
    }
}
Logcat Diagnostics Output (ADB Shell / Android Studio Logcat)
$ adb logcat -s DevAscent_Main:V --------- beginning of main 10-15 20:15:02.124 14820 14820 D DevAscent_Main: onCreate: Activity successfully instantiated on ART Runtime 10-15 20:15:08.450 14820 14820 I DevAscent_Main: User Clicked Action Button: count=1 10-15 20:15:10.892 14820 14820 I DevAscent_Main: User Clicked Action Button: count=2 10-15 20:15:12.105 14820 14820 I DevAscent_Main: User Clicked Action Button: count=3
08

University Exam & Technical Interview Viva Preparation Guide

Q1. What is the difference between Dalvik VM and the Android Runtime (ART)?
Dalvik Virtual Machine (used in Android 4.4 and earlier) used Just-in-Time (JIT) compilation, compiling DEX bytecode into native machine instructions on-the-fly every time an application was launched, leading to CPU overhead and battery drain. Android Runtime (ART) (introduced in Android 5.0) introduced Ahead-of-Time (AOT) compilation, compiling the application during installation directly into ELF native binaries. Modern ART uses a hybrid profile-guided approach combining AOT, JIT, and cloud baseline profiles for optimal app startup speed and lower memory footprints.
Q2. Name the four core Android Application Components and their primary purposes.
(1) Activity: Represents a single screen with a user interface where users interact with the app.
(2) Service: Executes background tasks without providing a user interface (e.g., audio playback, file downloads).
(3) Broadcast Receiver: Listens for system-wide announcements or intent broadcasts (e.g., battery low, boot completed).
(4) Content Provider: Manages and encapsulates shared structured data across multiple applications using standard URIs.
Q3. What is the role of AndroidManifest.xml? What happens if an Activity is not declared in it?
The AndroidManifest.xml file is the root configuration file read by the Android OS prior to executing any application code. It declares the application's unique package ID, required hardware/network permissions, minimum hardware features, and registers all four application components. If an Activity is instantiated or launched via an Intent without being registered in the manifest, the Android OS throws an ActivityNotFoundException and crashes the app.
Q4. What is the difference between compileSdkVersion, minSdkVersion, and targetSdkVersion?
compileSdkVersion defines the Android SDK version against which the compiler compiles your code. minSdkVersion specifies the lowest Android OS API level required to install and run the app. targetSdkVersion indicates the specific API level against which the app has been verified and tested; it tells the OS runtime not to enable backward-compatibility compatibility shims and to enforce modern OS security/privacy behaviors.
Q5. What is the role of the Linux Kernel in Android? Does Android have a standard GNU/Linux userland?
The Linux Kernel provides low-level hardware abstraction, CPU process scheduling, memory paging, network protocol stacks, and device drivers (display, camera, Bluetooth). However, Android does not possess a standard GNU/Linux userland: it lacks GNU C library (glibc), X11 windowing, and standard desktop utilities. Instead, it utilizes Google's lightweight Bionic C library, the Binder IPC driver, and the Android Runtime (ART).
Q6. What is ADB (Android Debug Bridge) and how is it used during development?
Android Debug Bridge (ADB) is a versatile client-server command-line tool that facilitates communication between a development workstation and an Android device (virtual emulator or connected physical phone). It consists of three parts: a client running on the workstation, an adb server background process, and an adb daemon (adbd) running on the Android device. It enables commands such as installing APKs (adb install), viewing live logs (adb logcat), opening an interactive shell (adb shell), and transferring files (adb push / pull).
Q7. What is the purpose of Gradle in Android development?
Gradle is an advanced, domain-specific build automation tool that orchestrates the entire compilation lifecycle. It fetches remote third-party libraries from repositories (Maven Central, Google Maven), processes XML resources and vector assets via aapt2, compiles Java/Kotlin code into bytecode, converts bytecode into Dalvik Executable (.dex) format using the D8/R8 compiler, shrinks unused code, and packages the results into signed APK or AAB bundles ready for distribution.
Q8. How does Android enforce security sandboxing between installed applications?
At installation time, the Android OS assigns every application a unique Linux User ID (UID) and distinct group ID (GID). Each application runs in its own private, isolated Linux process with its own virtual memory space. The underlying Linux kernel file-permission system strictly prevents an application with UID `10045` from reading, writing, or executing files belonging to another app with UID `10046`, unless explicit Content Provider access or shared user credentials are provided.