IT272 Mobile Application Development

Mobile Application DevelopmentUnit 214 min read

Android Architecture & Dev Environment: SDK, Emulator, ADB, Gradle

Unit 2 of Mobile Application Development covers Android’s layered architecture (Linux kernel to apps), the Android Studio toolchain (SDK Manager, AVD Manager, Gradle), and essential command-line tools (ADB, Fastboot). Learn how to set up projects, debug with Logcat, and automate builds—with real-world examples from eSe

Android’s Layered Architecture

Android is built on a modular, layered architecture that separates concerns into distinct layers. Each layer provides services to the layer above while relying on the layer below. Below is the official Android architecture (as of Android 12):

classDiagram
    class LinuxKernel {
        +Hardware Abstraction
        +Memory Management
        +Device Drivers
        +Security (SELinux)
    }
    class HardwareAbstractionLayer {
        +Hardware-specific Code
        +Power Management
        +Camera/GPU Drivers
    }
    class AndroidRuntime {
        +Core Libraries (Java/Kotlin)
        +ART (Android Runtime)
        +Core Java APIs
    }
    class NativeLibraries {
        +C/C++ Libraries (OpenGL, SQLite, WebKit)
        +Media Codecs
    }
    class AndroidFramework {
        +Activity Manager
        +Content Providers
        +View System
        +Location Manager
    }
    class SystemApps {
        +Pre-installed Apps (Phone, Messages, Settings)
        +Google Apps (Play Store, GMS)
    }
    class JavaAPIFramework {
        +Android SDK (APIs for apps)
        +Support Libraries
    }
    class Applications {
        +Third-party Apps (e.g., eSewa, Pathao)
    }
    LinuxKernel --> HardwareAbstractionLayer : Uses
    HardwareAbstractionLayer --> AndroidRuntime : Provides
    AndroidRuntime --> NativeLibraries : Links
    NativeLibraries --> AndroidFramework : Uses
    AndroidFramework --> SystemApps : Hosts
    AndroidFramework --> JavaAPIFramework : Exposes
    JavaAPIFramework --> Applications : Enables

Key Layers Explained:

  1. Linux Kernel

    • Provides low-level hardware control (process management, memory, drivers).
    • Includes SELinux for security enforcement.
    • Example: When you swipe to unlock your phone, the kernel handles touch input and screen wake-up.
  2. Hardware Abstraction Layer (HAL)

    • Abstracts hardware-specific code (e.g., camera drivers, sensors).
    • Example: The HAL ensures your app can access the camera on any Android device, even if the hardware differs.
  3. Android Runtime (ART)

    • Replaces Dalvik with Ahead-of-Time (AOT) compilation for faster app launches.
    • Manages memory and garbage collection.
    • Example: When you open WhatsApp, ART compiles its bytecode to machine code for instant startup.
  4. Native Libraries

    • Prebuilt libraries for C/C++ (e.g., libsqlite.so, libwebcore.so).
    • Example: YouTube uses these for video decoding.
  5. Android Framework

    • Core services like Activity Manager, Content Providers, and Notification Manager.
    • Example: When you receive a call, the PhoneManager service handles the incoming call UI.
  6. Java API Framework

    • The Android SDK you use in Android Studio (e.g., android.app, android.widget).
    • Example: Toast.makeText() relies on this layer to show pop-up messages.
  7. Applications

    • Third-party apps (e.g., eSewa, Pathao) run on top of the framework.

In the Real World

  1. eSewa (Nepal’s Digital Wallet)

    • Uses the Android Framework’s ContentProvider to securely access user payment data.
    • Relies on ART for fast transaction processing (e.g., electricity bill payments).
    • Example: When you scan a QR code to pay, the CameraManager (HAL) captures the image, and the app processes it using Java/Kotlin APIs.
  2. Pathao (Ride-Hailing App)

    • Uses Location Manager (Android Framework) to track driver and rider locations in real time.
    • Leverages Native Libraries for map rendering (via Google Maps SDK).
    • Example: When you request a ride, the app calculates the shortest route using algorithms in the Java API Framework.
  3. NTC (Nepal Telecom) Apps

    • Uses Android’s BroadcastReceiver to handle incoming SMS notifications (e.g., bill alerts).
    • Relies on SELinux (Linux Kernel) to prevent unauthorized access to telecom data.

Android Studio and Development Environment

Android Studio is the official IDE for Android development, built on IntelliJ IDEA. It integrates tools like:

  • SDK Manager: Downloads Android SDK components (API levels, build tools, emulator system images).
  • AVD Manager: Creates and manages Android Virtual Devices (AVDs) for testing.
  • Gradle: Build automation tool (handles dependencies, builds, and signing).
  • Logcat: Debugging tool to view app logs.
  • ADB (Android Debug Bridge): Command-line tool for device communication.

Setting Up a Project

  1. Create a New Project

    • Select Empty Activity template.
    • Configure:
      • Package name (e.g., com.example.esewaclone)
      • Language (Java/Kotlin)
      • Minimum SDK (e.g., API 21 for wider compatibility).
  2. Project Structure

java/com/example/esewaclone/layout/values/res/main/src/build.gradleAndroidManifest.xmlgradlewapp/Project Root
Typical Android project structure (e.g., eSewa Clone)
  1. Key Files
    • AndroidManifest.xml: Declares app components (activities, permissions, hardware features).
      <manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.esewaclone">
          <uses-permission android:name="android.permission.INTERNET" />
          <application>
              <activity android:name=".MainActivity">
                  <intent-filter>
                      <action android:name="android.intent.action.MAIN" />
                      <category android:name="android.intent.category.LAUNCHER" />
                  </intent-filter>
              </activity>
          </application>
      </manifest>
      
    • build.gradle (Module-level): Configures dependencies and build settings.
      dependencies {
          implementation 'androidx.appcompat:appcompat:1.6.1'
          implementation 'com.google.android.material:material:1.9.0'
          implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
      }
      
    • gradlew: Runs Gradle commands (e.g., ./gradlew build).

SDK Manager and API Levels

The SDK Manager lets you download:

  • Platforms: Android API levels (e.g., Android 12 = API 31).
  • Build Tools: Compiler tools (e.g., 34.0.0).
  • Emulator System Images: Virtual device images (x86, ARM).
  • Google APIs: For testing Google Play Services (e.g., Maps, Location).

API Level Comparison

API Level Android Version Release Year % Market Share (2023)
33 Android 13 2022 ~15%
32 Android 12 2021 ~30%
31 Android 12L 2021 ~20%
30 Android 11 2020 ~15%
29 Android 10 2019 ~10%

Why does this matter?

  • Backward Compatibility: Apps should target a minimum SDK (e.g., API 21) but test on higher APIs.
  • New Features: API 33+ supports Dynamic Module Federation (for progressive web apps).
  • Example: If you build an app for Nepal’s digital payment system, target API 26+ to cover most users.

AVD Manager and Emulators

The AVD Manager lets you create virtual devices for testing. Key settings:

  • Device: Pixel 5, Nexus S, etc.
  • API Level: e.g., Android 12 (API 31).
  • Target: x86 or ARM image.
  • Skin: Resolution (e.g., 1080x2280 for foldables).
  • Front/Back Camera: Enable for camera app testing.
USB/NetworkDebug BridgeCommandsUI/LogsPhysical DeviceADB ServerEmulatorAndroid Studio
How ADB connects devices/emulators to Android Studio

Creating an AVD for eSewa Clone

  1. Open AVD Manager → Create Virtual Device.
  2. Select Pixel 5 → Next.
  3. Choose Android 12 (API 31) → Download if needed.
  4. Configure:
    • Front Camera: Enabled (for QR scanning).
    • Back Camera: Enabled (for receipt photos).
  5. Start the emulator with:
    emulator -avd Pixel_5_API_31 -no-snapshot
    

Pros of Emulators:

  • Test on devices you don’t own (e.g., foldables).
  • Debug without a physical device.

Cons:

  • Slower than real devices.
  • Some hardware features (e.g., sensors) may not work perfectly.

Gradle: Build Automation

Gradle is a build tool that:

  • Manages dependencies (e.g., Firebase, Retrofit).
  • Handles build variants (debug/release).
  • Signs and optimizes the APK/AAB.

Key Gradle Commands

Command Description
./gradlew build Compiles and builds the app.
./gradlew installDebug Installs the debug APK on a connected device.
./gradlew clean Deletes build files (for a fresh build).
./gradlew assembleRelease Generates a signed release APK.

Example: Adding Firebase to build.gradle

dependencies {
    implementation platform('com.google.firebase:firebase-bom:32.2.3')
    implementation 'com.google.firebase:firebase-analytics-ktx'
    implementation 'com.google.firebase:firebase-auth-ktx'
}

Why Firebase?

  • Used by eSewa for authentication and analytics.
  • Used by Pathao for ride tracking and user data.

ADB and Fastboot: Command-Line Tools

ADB (Android Debug Bridge)

ADB lets you control devices from the command line. Common commands:

Command Description
adb devices Lists connected devices.
adb install app.apk Installs an APK.
adb logcat Views app logs (debugging).
adb shell Opens a shell on the device.
adb pull /sdcard/file.txt Copies a file from the device to your PC.

Example: Debugging a Pathao App Crash

  1. Run the app on an emulator.
  2. Trigger the crash (e.g., by entering invalid ride details).
  3. Open a new terminal and run:
    adb logcat | grep "Pathao"
    
    • This filters logs for your app’s errors.

Fastboot

Fastboot is used for low-level device operations (e.g., flashing ROMs, unlocking bootloaders).

fastboot devices          # List connected devices
fastboot flash boot boot.img  # Flash a boot image
fastboot reboot           # Reboot the device

When to Use Fastboot?

  • Unlocking a Nepal Telecom device for development.
  • Installing custom ROMs (e.g., LineageOS).

Logcat: Debugging Tool

Logcat displays system and app logs in real time. Key log levels:

  • V (Verbose): Detailed debug info.
  • D (Debug): Debug messages.
  • I (Info): General info.
  • W (Warning): Potential issues.
  • E (Error): Critical errors.
  • F (Fatal): App crashes.

Example: Filtering Logs for a Daraz App

  1. Open Logcat in Android Studio (View → Tool Windows → Logcat).
  2. Filter by your app’s tag (e.g., DarazApp):
    :DarazApp:V
    
  3. Look for errors like:
    E/DarazApp: Network timeout while fetching product details
    

Common Logcat Commands

Command Description
adb logcat -d > log.txt Save logs to a file.
adb logcat ActivityManager:I *:S Show only ActivityManager info.
`adb logcat grep "error"`

Exam Tip

  1. Architecture Layers

    • Memorize the 7 layers (Linux Kernel → Applications).
    • Know which layer handles security (SELinux), hardware abstraction (HAL), and app execution (ART).
    • Exam Question: "Which layer provides the CameraManager API?" → Android Framework.
  2. Android Studio Setup

    • Be able to describe the project structure (e.g., src/main/java, res/layout).
    • Know how to add dependencies in build.gradle (e.g., Firebase, Retrofit).
    • Exam Question: "Where do you declare app permissions?" → AndroidManifest.xml.
  3. SDK and API Levels

    • Understand why you’d target API 26 but compile against API 33.
    • Know the market share of major API levels (e.g., API 31 = Android 12).
    • Exam Question: "What’s the minimum SDK for an app supporting 80% of Nepal’s users?" → API 26 (Android 8.0).
  4. ADB and Logcat

    • Practice common ADB commands (adb install, adb logcat).
    • Know how to filter logs for debugging.
    • Exam Question: "How would you debug a crash in a Daraz app?" → Use adb logcat | grep "Daraz".
  5. Gradle and Build Variants

    • Differentiate between debug and release builds.
    • Know how to sign an APK for publishing.
    • Exam Question: "Which Gradle command generates a signed APK?" → ./gradlew assembleRelease.

Worked Example: Debugging a Traffic Route App (Like Pathao)

Scenario: You’re building a Kathmandu traffic route app that crashes when calculating the shortest path. Let’s debug it.

Step 1: Reproduce the Crash

  1. Open the app on an AVD (Pixel 5, API 31).
  2. Enter Thamel to Kantipath as start/end points.
  3. Tap Calculate Route → App crashes.

Step 2: Check Logcat

Run:

adb logcat | grep "TrafficRouteApp"

Output:

E/TrafficRouteApp: java.lang.NullPointerException: Attempt to invoke virtual method 'double com.example.model.Location.getLatitude()' on a null object reference

Issue: The Location object is null when calculating the route.

Step 3: Fix the Code

In RouteCalculator.kt:

fun calculateRoute(start: Location?, end: Location?): String {
    if (start == null || end == null) {
        return "Error: Start or end location is missing!"
    }
    // Rest of the logic...
}

Step 4: Test Again

  1. Rebuild the app:
    ./gradlew installDebug
    
  2. Retry the route calculation → No crash!

Summary Checklist

Before the exam, ensure you can:

  1. Draw the Android architecture layers and label each.
  2. List 5 tools in Android Studio (SDK Manager, AVD Manager, Gradle, Logcat, ADB).
  3. Explain the difference between debug and release builds.
  4. Write 3 ADB commands for debugging.
  5. Describe how Firebase integrates with build.gradle.
  6. Explain why API levels matter for app compatibility.

Based on the TU BITM syllabus for Mobile Application Development (IT272), unit 2.

Discussion

Loading…