Elective Mobile Application Development

Mobile Application DevelopmentUnit 29 min read

Mobile App Architecture, Frameworks & Design Patterns

Unit 2 of Mobile Application Development explores the layered architecture of mobile systems (OS, middleware, apps), compares native vs. cross-platform frameworks (Android Studio, Flutter, React Native), and teaches design patterns (MVC, MVVM) with real-world app examples and performance trade-offs.

Core Concepts

Mobile System Architecture Layers

Mobile systems follow a layered architecture similar to desktop computing but optimized for battery, memory, and connectivity constraints. The three primary layers are:

API callsSystem callsDirect accessAppMiddlewareOSHardware
Dependency graph showing call paths between layers
classDiagram
    class Application {
        +UI Components
        +Business Logic
        +Data Access
    }
    class Middleware {
        +APIs
        +SDKs
        +Security
        +Connectivity
    }
    class OS {
        +Kernel
        +Hardware Abstraction
        +Services (Bluetooth, GPS)
        +Power Management
    }
    OS <|-- Middleware
    Middleware <|-- Application

Key Components:

  • OS Layer (Android/iOS): Manages hardware, provides APIs (e.g., Camera, Location), and enforces security (sandboxing).
  • Middleware Layer: Includes frameworks (e.g., Firebase, Retrofit) and libraries (e.g., Room for databases).
  • Application Layer: Your app code, split into:
    • Presentation Layer (UI/UX)
    • Business Logic Layer (e.g., order processing in Pathao)
    • Data Layer (local storage, APIs).

Worked Example: eSewa Payment Flow

  1. User taps "Pay" → UI triggers PaymentService.
  2. PaymentService calls eSewa’s API (middleware) via Retrofit.
  3. OS handles network requests and encrypts data.
  4. Response updates UI (e.g., "Payment successful").

Development Frameworks: Native vs. Cross-Platform

Comparison Table

Framework Language Platforms Pros Cons Example Apps
Android Studio Kotlin/Java Android Full native performance, access to all APIs Fragmentation, slower development Google Maps, Pathao
Xcode (Swift) Swift iOS/macOS Best iOS integration, ARKit support Limited to Apple ecosystem WhatsApp, Apple Pay
Flutter Dart Android/iOS/Web Single codebase, hot reload Larger app size, some native APIs missing Alibaba, BMW App
React Native JavaScript Android/iOS/Web Familiar for web devs, large community Bridge overhead, slower than native Facebook, Shopify

Visual: Flutter’s Widget Tree

graph TD
    A["Root Widget"] --> B["MaterialApp"]
    B --> C["Scaffold"]
    C --> D["AppBar"]
    C --> E["Body"]
    E --> F["ListView"]
    F --> G["ListItem 1"]
    F --> H["ListItem 2"]
Flutter renders UI as a tree of widgets, updating only changed parts (efficient for animations).

Design Patterns for Mobile Apps

1. MVC (Model-View-Controller)

Use Case: Simple apps like a Khalti balance checker.

classDiagram
    class Model {
        +balance: Double
        +fetchBalance()
    }
    class View {
        +displayBalance()
    }
    class Controller {
        +updateView()
    }
    Model --> Controller : updates
    Controller --> View : renders

Trace: Fetching Balance

Step Action State After Step
1 User taps "Check Balance" View triggers Controller.fetch()
2 Controller calls Model.fetch() Model queries Khalti API
3 API returns balance = 5000 Model updates balance
4 Controller calls View.update() UI shows "Balance: NPR 5000"

Disadvantage: Tight coupling between View and Controller can cause bugs in complex apps (e.g., Daraz’s cart system).


2. MVVM (Model-View-ViewModel)

Use Case: Ncell’s recharge app (handles real-time updates).

classDiagram
    class Model {
        +rechargeStatus: String
    }
    class ViewModel {
        +rechargeStatus: ObservableField
        +onRechargeSuccess()
    }
    class View {
        +bind(ViewModel)
    }
    Model --> ViewModel : notifies
    ViewModel --> View : updates

Advantage: Decouples UI from business logic (ViewModel survives configuration changes, e.g., rotating screen).

Code Example (Kotlin + Android ViewModel):

class RechargeViewModel : ViewModel() {
    val status = MutableLiveData<String>()
    fun recharge(phone: String, amount: Int) {
        viewModelScope.launch {
            try {
                val result = RechargeRepository.recharge(phone, amount)
                status.postValue("Success: ${result.balance}")
            } catch (e: Exception) {
                status.postValue("Failed: ${e.message}")
            }
        }
    }
}

Trace: Recharge Flow

Step Action State After Step
1 User enters "98XXXX" and "50" View binds to RechargeViewModel
2 Taps "Recharge" ViewModel calls recharge()
3 Repository calls Ncell API API returns {"balance": 4500}
4 status.postValue() UI updates to "Success: NPR 4500"

3. Singleton Pattern

Use Case: NTC’s ticket booking system (shared across app instances).

classDiagram
    class TicketBookingSystem {
        +instance: TicketBookingSystem
        +getInstance()
        +bookTicket()
    }
    TicketBookingSystem o-- TicketBookingSystem : lazy initialization

Why? Ensures only one instance manages bookings (avoids duplicate transactions).

Disadvantage: Hard to test (global state). Use dependency injection in exams.


In the Real World

  1. Pathao’s Order Queue

    • Uses a priority queue (design pattern) to process rides/deliveries.
    • Nearest drivers get highest priority (optimized via Location API).
    • Visual: See the queue state after each driver assignment in the next figure.
    flowchart TD
        A["Order Queue"] -->|"enqueue"| B["Driver A\nDistance: 2km"]
        A -->|"enqueue"| C["Driver B\nDistance: 5km"]
        A -->|"enqueue"| D["Driver C\nDistance: 1km"]
        A -->|"dequeue"| D
        D -->|"assigned"| E["Order 123\nStatus: In Progress"]

    State after assignment: Driver C (closest) gets the order; UI updates both driver and customer apps.

  2. Khalti’s Security Layer

    • Uses MVVM + Repository Pattern to separate:
      • Model: API calls to Khalti’s servers.
      • ViewModel: Handles token validation.
      • View: Displays success/failure.
    • Why? Prevents UI from directly calling APIs (security best practice).
  3. Daraz’s Cart System

    • State Management: Uses LiveData (MVVM) to sync cart across app restarts.
    • Example: Adding an item updates CartViewModel, which persists to SharedPreferences and notifies all bound Views (product page, cart summary).

Wireless Connectivity in Mobile Apps

Mobile apps rely on HTTP/HTTPS, WebSockets, and background sync (e.g., Firebase). Key protocols:

Protocol Use Case Example
REST API Fetching data (e.g., NEPSE quotes) GET /stocks/NEPSE
WebSocket Real-time updates (e.g., Pathao ETA) ws://pathao.com/location-updates
Firebase Offline-first sync (e.g., eSewa) Firestore for transaction logs

Worked Example: Ncell’s Push Notification

  1. App registers for FCM (Firebase Cloud Messaging).
  2. Server sends: {"to": "device_token", "data": {"type": "recharge", "amount": 100}}.
  3. FCM delivers to app’s FirebaseMessagingService.
  4. Service updates NotificationViewModel, which shows an alert.
sequenceDiagram
    participant Server
    participant FCM
    participant App
    Server->>FCM: POST /send (recharge alert)
    FCM->>App: Push Notification
    App->>App: NotificationViewModel.update()
    App->>UI: Show "Recharge of NPR 100"

Exam Tip

  1. Diagrams Are Mandatory:

    • Draw layered architecture (OS → Middleware → App) for any question on mobile systems.
    • Show MVC/MVVM flowcharts with arrows for "explain how X works" questions.
    • Example: For "Design a Khalti app," sketch:
      • 3-layer architecture.
      • MVVM classes with LiveData arrows.
      • API call sequence (Retrofit → Khalti → Response).
  2. Compare Frameworks:

    • Always include a table (like above) when asked to choose between native/cross-platform.
    • Tip: Mention performance (native) vs. development speed (Flutter).
  3. Real-World Mapping:

    • Link design patterns to apps:
      • Singleton → NTC ticket booking.
      • Observer → Pathao driver location updates.
      • Repository → Daraz product catalog.
  4. Code Traces:

    • For algorithms (e.g., "How does Flutter render widgets?"), show:
      • Initial state (empty widget tree).
      • After build() (tree with MaterialApp).
      • After setState() (updated ListView).
  5. Common Pitfalls:

    • Memory Leaks: Forgetting to unregister BroadcastReceiver (e.g., for Ncell SMS updates).
    • Battery Drain: Using Location API in foreground only (not background).
    • Threading: Blocking UI thread with API calls (always use viewModelScope.launch).

Based on the TU BSc CSIT syllabus for Mobile Application Development, unit 2.

Discussion

Loading…