📖 2413MJET306A • Unit IV • 4 Hrs

Unit IV - Worker Threads and Notification Mechanisms

Comprehensive University Exam Preparation Notes, Model Question Answers & Comparison Matrices

🔍
📑 Quick Jump Navigation

📌 Syllabus Topics Covered

4 Hrs Weightage

📖 Comprehensive Theoretical Notes

Exam-Oriented Theory

4.1 - 4.4 Multi-Threading, Worker Threads, Handlers, and AsyncTask

The Android Single-Thread Model (UI Thread):

Android applications execute UI rendering and touch handling on a single Main Thread (UI Thread). If the UI Thread is blocked for more than 5 seconds, the OS terminates the app with an Application Not Responding (ANR) dialog. All long-running operations (networking, database queries, file I/O) must run on Worker Threads.

Thread Communication Mechanisms:

  • runOnUiThread(Runnable action): Executes code on the UI thread from background threads.
  • Handler & Looper: A Handler enqueues Message and Runnable objects into the thread's MessageQueue processed by a Looper.
  • AsyncTask (4 Execution Steps):
    1. onPreExecute(): Runs on UI Thread before background task begins (show ProgressBar).
    2. doInBackground(Params...): Runs on Worker Thread; performs heavy computations. Calls publishProgress().
    3. onProgressUpdate(Progress...): Runs on UI Thread; updates progress bar.
    4. onPostExecute(Result): Runs on UI Thread after task finishes; displays final results.

4.5 & 4.6 Broadcast Receivers & Android Services

Broadcast Receiver: Listens for system events (android.intent.action.BOOT_COMPLETED). Implements onReceive(Context context, Intent intent).

Android Services: Background components without UI:

  • Started / Unbounded Service: Started via startService(intent). Runs indefinitely in the background until it calls stopSelf() or an activity calls stopService(). Lifecycle: onCreate() $\rightarrow$ onStartCommand() $\rightarrow$ onDestroy().
  • Bound Service: Bound via bindService(intent, connection, flags). Provides an IBinder interface for client-server RPC communication. Lifecycle: onCreate() $\rightarrow$ onBind() $\rightarrow$ onUnbind() $\rightarrow$ onDestroy().

4.7 - 4.9 Notifications, Alarms, and Telephony Services (SMS / Call)

Notifications (Android 8.0+ Oreo Requirements):

  • Requires a NotificationChannel (ID, Name, Importance).
  • Built using NotificationCompat.Builder: SmallIcon, ContentTitle, ContentText, Priority, and PendingIntent (opens activity on tap).
  • Posted via NotificationManagerCompat.from(context).notify(id, notification).

AlarmManager: Schedules operations at fixed times or intervals even if app is asleep (setExact(), setRepeating() with RTC_WAKEUP).

Phone Services:

  • Making Calls: Intent(Intent.ACTION_CALL, Uri.parse("tel:...")) (requires android.permission.CALL_PHONE).
  • Sending SMS: SmsManager.getDefault().sendTextMessage(phone, null, message, sentIntent, deliveryIntent) (requires android.permission.SEND_SMS).

🔑 Key Concepts & Examination Keywords

Quick Terminology
ANR (Application Not Responding)
System error dialog shown when the UI thread is blocked for over 5 seconds.
AsyncTask
Abstract helper class that facilitates executing background tasks and publishing results directly to the UI thread.
NotificationChannel
Mandatory category channel in Android 8.0+ grouping notifications with distinct user-configurable settings.
PendingIntent
A token granted to external applications (like NotificationManager) to execute an Intent with your application's permissions.

🎯 High-Yield Important Examination Questions

8–10 Descriptive Points Each

Q1. Explain the Android Single-Thread model, the causes of ANR errors, and the complete step-by-step lifecycle of AsyncTask.

10 MarksAsyncTask & ThreadingCore
📝 Detailed Examination Answer (10-Point Model):
  1. The Android Single-Thread Rule: Android UI toolkit is not thread-safe; all UI widgets MUST only be created, modified, and updated on the dedicated Main UI Thread.
  2. Application Not Responding (ANR) Trigger: If an intensive operation (HTTP download, database query) blocks the UI thread for >5 seconds, Android OS displays the fatal ANR dialog.
  3. Worker Thread Architecture: Background operations must be offloaded to worker threads (`new Thread(new Runnable())`) to keep the UI thread responsive at 60 FPS.
  4. Cross-Thread UI Update Restriction: Worker threads cannot directly modify UI views; doing so throws `CalledFromWrongThreadException`.
  5. AsyncTask Architecture (<Params, Progress, Result>): An abstract helper class encapsulating thread creation, background execution, and synchronized UI thread communication.
  6. Step 1: onPreExecute() Callback: Runs on the UI Thread before execution begins; used to initialize UI elements and display a spinning `ProgressBar`.
  7. Step 2: doInBackground(Params...): Runs on a dedicated Worker Thread; executes the heavy background processing and periodically calls `publishProgress()`.
  8. Step 3: onProgressUpdate(Progress...): Runs on the UI Thread; receives progress values dispatched by `publishProgress()` to update progress bars in real time.
  9. Step 4: onPostExecute(Result): Runs on the UI Thread after background processing finishes; receives final result data to dismiss progress dialog and update UI.
  10. AsyncTask Deprecation & Modern Replacements: AsyncTask was deprecated in API 30 due to memory leaks; replaced in modern Kotlin by Coroutines and in Java by `ExecutorService` with `Handler`.

Q2. Compare Started (Unbounded) Services and Bound Services. Explain their lifecycles, execution models, and IPC mechanisms.

10 MarksServicesBackground Processing
📝 Detailed Examination Answer (10-Point Model):
  1. Definition of Android Service: An application component that executes long-running background tasks without providing a graphical user interface.
  2. Started (Unbounded) Service Overview: Initiated when an activity calls `startService(intent)`; runs indefinitely until explicitly stopped even if the calling activity is destroyed.
  3. Started Service Lifecycle Callbacks: Lifecycle: `onCreate()` (called once) $\rightarrow$ `onStartCommand()` (called on every startService) $\rightarrow$ `onDestroy()`.
  4. Stopping a Started Service: Must be stopped internally by calling `stopSelf()` or externally from an activity calling `stopService(intent)` to prevent battery drain.
  5. Bound Service Overview: Initiated when a component calls `bindService(intent, conn, flags)`; acts as a server in a client-server architecture.
  6. Bound Service Lifecycle Callbacks: Lifecycle: `onCreate()` $\rightarrow$ `onBind()` (returns IBinder) $\rightarrow$ `onUnbind()` $\rightarrow$ `onDestroy()`.
  7. IBinder & Local Service Binding: For local intra-app binding, the service returns a custom `Binder` subclass exposing public methods directly to the bound activity.
  8. Messenger & AIDL for Cross-Process IPC: For cross-process remote communication, Bound Services utilize `Messenger` (handler-based) or AIDL (Android Interface Definition Language).
  9. Foreground Service Requirement: Long-running background tasks noticeable to users (music playback, GPS tracking) must run as Foreground Services with a persistent status bar notification.
  10. Service Threading Nuance: A standard Service runs on the MAIN UI thread by default; heavy work inside a service must still spawn worker threads or use `IntentService`.

Q3. Describe the implementation of Android Notifications (Channels, NotificationCompat, PendingIntents) and AlarmManager for scheduled tasks.

10 MarksNotifications & AlarmManager
📝 Detailed Examination Answer (10-Point Model):
  1. Notification Concept & Evolution: Notifications display messages outside your normal app UI in the system status bar and notification shade to inform users of timely events.
  2. Mandatory Notification Channels (Android 8.0+): Android 8.0+ requires grouping notifications into channels (`NotificationChannel(id, name, importance)`) registered with `NotificationManager`.
  3. Notification Importance Levels: Channels define importance: `IMPORTANCE_HIGH` (heads-up banner + sound), `IMPORTANCE_DEFAULT` (sound), `IMPORTANCE_LOW` (silent).
  4. NotificationCompat.Builder Construction: Constructed using: `.setSmallIcon()`, `.setContentTitle()`, `.setContentText()`, `.setAutoCancel(true)`, and `.setPriority()`.
  5. PendingIntent Integration: Wraps an explicit Intent that launches an Activity when the user taps the notification: `PendingIntent.getActivity(context, reqCode, intent, flags)`.
  6. Posting the Notification: Dispatched to system shade using `NotificationManagerCompat.from(context).notify(notificationId, builder.build())`.
  7. AlarmManager Architecture: A system service that triggers Intents at specified future clock times or repeating intervals even when the application is not running.
  8. Alarm Types (RTC vs Elapsed Realtime): `RTC_WAKEUP` triggers based on wall-clock time; `ELAPSED_REALTIME_WAKEUP` triggers based on time elapsed since device boot.
  9. Exact vs Inexact Alarms: `setExact()` guarantees precise triggering for alarms/timers; `setInexactRepeating()` batches alarms to conserve battery life (Doze Mode).
  10. Runtime Notification Permissions: Android 13+ (API 33) requires explicit user runtime permission: ``.

⚖️ Comprehensive Comparison & Difference Tables

8+ Comparison Criteria

📊 Started Service vs Bound Service

Comparison ParameterStarted (Unbounded) ServiceBound Service
Initiating MethodStarted via `startService(intent)`.Bound via `bindService(intent, connection, flags)`.
Lifecycle BindingIndependent of client activity; runs even if caller is destroyed.Tightly coupled to client lifecycle; destroyed when all clients unbind.
Stopping MechanismExplicit call to `stopSelf()` or `stopService()`.Automatically destroyed when the last bound client calls `unbindService()`.
Primary CallbackExecutes `onStartCommand(intent, flags, startId)`.Executes `onBind(intent)` returning an `IBinder` interface.
Client-Server InteractionOne-way fire-and-forget; does not return results to caller directly.Two-way client-server interaction via direct method calls or RPC.
Multiple ClientsCan be started multiple times, but runs as a single service instance.Multiple clients can bind concurrently to the same service.
Typical Use CasesPlaying background audio, uploading files, periodic syncing.Inter-process communication (IPC), local sensor streaming to UI.
Thread of ExecutionRuns on Main UI thread by default unless worker thread is spawned.Runs on Main UI thread by default.

📊 Service vs IntentService vs Thread

Comparison ParameterServiceIntentService (Legacy)Thread / Runnable
Android ComponentCore Android OS component declared in Manifest.Subclass of Service declared in Manifest.Standard Java language concurrency construct.
Execution ThreadRuns on the MAIN UI thread by default.Spawns its own dedicated background worker thread.Runs on its own standalone thread.
Task HandlingHandles concurrent tasks manually.Processes tasks sequentially one-by-one via work queue.Handles single task assigned to `run()` method.
Auto-TerminationMust be explicitly stopped via `stopSelf()`.Automatically stops itself after the work queue is empty.Terminates when `run()` method completes.
OS Lifecycle PriorityHigh priority; OS avoids killing active services.High priority while processing queued intents.Low priority; OS kills orphan threads if parent process is killed.
UI InteractionCannot directly touch UI; requires Handler / Broadcast.Cannot directly touch UI; sends broadcasts.Cannot touch UI; requires `runOnUiThread()`.
Configuration ChangesSurvives activity destruction and screen rotation.Survives activity destruction and screen rotation.Often leaks memory or dies when activity is recreated.
Modern ReplacementForeground Service / WorkManager.WorkManager / JobIntentService.Java Executors / Kotlin Coroutines.

⚡ Quick Pre-Exam Revision Summary

5-Minute Recap
💡 Core Takeaways & High-Yield Summary
  • UI Thread handles rendering; blocking it for >5s causes an ANR (Application Not Responding) crash.
  • Worker threads run background tasks; UI updates must route via `runOnUiThread()`, `Handler`, or `AsyncTask`.
  • AsyncTask 4 steps: `onPreExecute()` (UI) $\rightarrow$ `doInBackground()` (Worker) $\rightarrow$ `onProgressUpdate()` (UI) $\rightarrow$ `onPostExecute()` (UI).
  • Started Service runs independently (`startService`); Bound Service provides client-server RPC (`bindService`).
  • Android 8.0+ notifications require `NotificationChannel`, `NotificationCompat.Builder`, and `PendingIntent`.
  • AlarmManager schedules future tasks using `RTC_WAKEUP` or `ELAPSED_REALTIME_WAKEUP`.