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
HandlerenqueuesMessageandRunnableobjects into the thread'sMessageQueueprocessed by aLooper. - AsyncTask (4 Execution Steps):
onPreExecute(): Runs on UI Thread before background task begins (show ProgressBar).doInBackground(Params...): Runs on Worker Thread; performs heavy computations. CallspublishProgress().onProgressUpdate(Progress...): Runs on UI Thread; updates progress bar.onPostExecute(Result): Runs on UI Thread after task finishes; displays final results.