IT272 Mobile Application Development

Mobile Application DevelopmentUnit 39 min read

Activities, Intents, Lifecycle & Task Management in Android

Unit 3 of Mobile Application Development covers Android’s core components—Activities, Intents, and the Activity Lifecycle—explaining how they enable navigation, communication, and state management in apps, with real-world examples from eSewa, Pathao, and Ncell.

Core Concepts: Activities, Intents, and Lifecycle

1. Activities: The Building Blocks of Android Apps

An Activity is a single, focused task that the user interacts with (e.g., a login screen, a chat window, or a settings menu). Every Android app has at least one Activity, which represents a window on the screen.

Key Characteristics:

  • Each Activity manages its own UI (User Interface) and state.
  • Activities are independent but can communicate via Intents.
  • The system maintains a stack of Activities (back stack), allowing users to navigate backward.

Visual: Activity Stack

flowchart TD
    A["Activity A\n(Home Screen)"] -->|"User clicks 'Profile'"| B["Activity B\n(Profile Screen)"]
    B -->|"User clicks 'Settings'"| C["Activity C\n(Settings Screen)"]
    C -->|"User presses Back"| B
    B -->|"User presses Back"| A

Real-World Example:

  • eSewa App: When you tap "Pay Bill," a new Activity opens for bill selection. Pressing back returns you to the home screen, demonstrating the Activity stack.

2. Intents: Messaging Between Components

An Intent is a message used to request an action from another component (Activity, Service, Broadcast Receiver). There are two types:

Type Description Example
Explicit Targets a specific component (e.g., MainActivity.class). Opening a profile screen from a button click.
Implicit Declares a general action (e.g., ACTION_VIEW) without specifying the target. Opening a URL in a browser or dialing a phone number.

How Intents Work:

  1. Sender creates an Intent with an action, data, and extras.
  2. Android OS matches the Intent to the best component (via Intent Filters in the manifest).
  3. Receiver (e.g., another Activity) processes the Intent.

Example: Starting an Activity with an Intent

// Explicit Intent to launch ProfileActivity
Intent intent = new Intent(this, ProfileActivity.class);
startActivity(intent);

Trace of startActivity():

Step Code Execution State After Execution
1 Intent intent = new Intent(...) Intent object created with target class.
2 startActivity(intent) New Activity (ProfileActivity) pushed onto the stack.

Real-World Example:

  • Pathao Rider App: When a rider accepts an order, an Intent launches the Navigation Activity, passing the pickup/drop location as extras.

3. Activity Lifecycle: Managing States

Activities go through 7 lifecycle states (methods) to handle configuration changes (e.g., screen rotation, app going to background). The lifecycle is predictable and repeatable.

stateDiagram-v2
    [*] --> Active: onCreate()
    Active --> Paused: onPause()
    Paused --> Stopped: onStop()
    Stopped --> Destroyed: onDestroy()
    Stopped --> Active: onRestart()
    Paused --> Active: onResume()
    Active --> Stopped: onStop()
    Stopped --> Paused: onRestart()
    Paused --> Active: onResume()

Key Methods:

Method Trigger Purpose
onCreate() Activity is first created. Initialize UI, bind data, load resources.
onStart() Activity becomes visible. Prepare for user interaction.
onResume() Activity is in foreground. Handle user input (e.g., button clicks).
onPause() Activity loses focus (e.g., dialog). Save transient state (e.g., scroll position).
onStop() Activity is no longer visible. Release resources (e.g., stop animations).
onDestroy() Activity is being killed. Clean up (e.g., close database connections).

Worked Example: Handling Screen Rotation

@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    savedInstanceState.putString("username", usernameEditText.getText().toString());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    usernameEditText.setText(savedInstanceState.getString("username"));
}

State After Rotation:

flowchart LR
    A["Before Rotation\n(username: \"john\")"] -->|"onPause()"| B["onSaveInstanceState()\nSaves \"john\""]
    B -->|"System destroys Activity"| C["onDestroy()"]
    C -->|"onCreate()"| D["onRestoreInstanceState()\nRestores \"john\""]
    D --> E["After Rotation\n(username: \"john\")"]

Real-World Example:

  • Ncell Recharge App: When you rotate the screen during a recharge, the app saves your selected number and amount in onSaveInstanceState() to avoid losing data.

4. Task and Back Stack Management

  • Task: A collection of Activities grouped as a single unit (e.g., all Activities in a chat app).
  • Back Stack: The order in which Activities were opened (LIFO). Pressing Back pops the top Activity.

Controlling the Back Stack:

// Launch Activity and clear the back stack (no back button)
Intent intent = new Intent(this, HomeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

State After FLAG_ACTIVITY_CLEAR_TASK:

flowchart TD
    A["Activity A"] --> B["Activity B"] --> C["Activity C"]
    C -->|"intent with CLEAR_TASK"| D["Only Activity C remains\n(Back stack empty)"]

Real-World Example:

  • Khalti App: After successful payment, the app launches a confirmation screen and clears the back stack so users can’t navigate back to the payment form.

5. Best Practices and Common Pitfalls

Do Don’t Why?
Use onSaveInstanceState() for critical data. Rely on onPause() for saving data. onPause() may not always be called (e.g., app killed by OS).
Declare Intents in the manifest for implicit ones. Use implicit Intents without filters. Risk of crashes if no component handles the Intent.
Handle configuration changes (e.g., rotation) gracefully. Ignore lifecycle callbacks. Leads to data loss or UI glitches.
Use FLAG_ACTIVITY_SINGLE_TOP for duplicate Activities. Launch duplicate Activities. Causes memory leaks and confusion.

In the Real World

  1. eSewa (Payment App)

    • Intent Use: When you click "Pay Bill," an explicit Intent launches the BillSelectionActivity, passing the selected service (electricity, phone) as extras.
    • Lifecycle: The app saves your last selected bill type in onSaveInstanceState() to restore it after rotation.
  2. Pathao (Ride-Hailing App)

    • Activity Stack: Rider → Order Details → Navigation (pushed sequentially; pressing back returns to Order Details).
    • Intent: The NavigationActivity receives the pickup/drop coordinates via an Intent bundle.
  3. Ncell Recharge App

    • Back Stack: After recharge, the app uses FLAG_ACTIVITY_CLEAR_TASK to prevent users from reattempting the same recharge.
    • Lifecycle: The app pauses animations in onStop() to save battery.

Exam Tip

  1. Define Key Terms Precisely:
    • "An Activity is a single-screen entity with its own lifecycle, while an Intent is a messaging object to trigger actions."
  2. Draw Lifecycle Diagrams:
    • Always sketch the 7-state lifecycle and label transitions (e.g., onPause() → onStop()).
  3. Code Snippets:
    • Memorize:
      • Starting an Activity with an Intent.
      • Saving/restoring state in onSaveInstanceState().
      • Flags like FLAG_ACTIVITY_CLEAR_TASK.
  4. Real-World Scenarios:
    • Expect questions like: "How does the eSewa app handle screen rotation during payment?" → Answer: onSaveInstanceState() saves the selected bill.
  5. Common Mistakes:
    • Negative Mark: Forgetting to call super.onSaveInstanceState().
    • Partial Credit: Describing Intents without mentioning explicit vs. implicit.

Visual Summary: Activity Lifecycle with Data Flow

flowchart TD
    A["onCreate()\nInitialize UI"] --> B["onStart()\nPrepare for visibility"]
    B --> C["onResume()\nHandle user input"]
    C --> D["onPause()\nSave transient data"]
    D --> E["onStop()\nRelease resources"]
    E --> F["onDestroy()\nClean up"]
    F -->|"User returns"| G["onRestart()\nRestore state"]
    G --> B
    C -->|"Rotation"| H["onSaveInstanceState()\nSave critical data"]
    H --> E

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

Discussion

Loading…