Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester
Week 14 Theory – Threading; Publishing Android Applications
Week 14 – Threading and Publishing Android Applications · 90 min read · 28 MCQs to check yourself
Philipp Lackner – WorkManager (Android Basics)
Generate a signed APK or App Bundle (AAB) in Android Studio
Part A – Threading
1. Processes and the main (UI) thread
- When an app starts, Android creates a Linux process with a single thread of execution called the main thread (also UI thread).
- The main thread draws the UI (about 60–120 frames per second, i.e. every ~16 ms or less) and handles all user input and lifecycle callbacks.
- Rule 1 – Do not block the UI thread. Long work (network, database, large files, image processing, heavy loops) must run on background (worker) threads.
- Rule 2 – Do not touch the UI from a background thread. Android's UI toolkit is not thread-safe; updating a view from another thread throws CalledFromWrongThreadException ("Only the original thread that created a view hierarchy can touch its views").
ANR – Application Not Responding
If the main thread is blocked, the system shows the ANR dialog ("App isn't responding – Wait / Close app"):
| Situation | Timeout |
|---|---|
| No response to an input event (touch/key) | about 5 seconds |
BroadcastReceiver onReceive not finished |
about 10 s (foreground) |
| Service not finished starting | about 20 s |
| Also jank (stutter) appears when frames take longer than 16 ms. Android forbids network on the main thread (NetworkOnMainThreadException) and Room forbids database access there. |
Process priority (who gets killed when memory is low)
Foreground process (visible activity) → visible process → service process → cached/background process (killed first).
2. Threads, Handlers and Executors (classic tools)
Thread
new Thread(() -> {
String data = downloadReport(); // background thread
runOnUiThread(() -> tvResult.setText(data)); // back to the UI thread
}).start();
Other ways to post to the UI thread: view.post(() -> ...), new Handler(Looper.getMainLooper()).post(() -> ...).
Handler, Looper and MessageQueue
- A Looper runs a message loop for a thread; the main thread already has one.
- A MessageQueue holds messages/runnables.
- A Handler sends and processes messages/runnables on a specific Looper's thread – e.g.
postDelayed(runnable, 1000)for timers and delays.
ExecutorService / thread pools
ExecutorService executor = Executors.newFixedThreadPool(4);
Handler main = new Handler(Looper.getMainLooper());
executor.execute(() -> {
String data = downloadReport(); // background work
main.post(() -> tvResult.setText(data)); // update UI on the main thread
});
// shut it down when the screen closes: executor.shutdown();
Reuses a fixed number of threads instead of creating new ones every time.
AsyncTask (deprecated)
AsyncTask (doInBackground, onPostExecute) was the old helper; deprecated in Android 11 (API 30) because of leaks and lifecycle problems – replaced by Executors with ViewModel/LiveData (Java) or coroutines (Kotlin).
Thread safety
When several threads share data, use synchronisation (synchronized blocks, ReentrantLock), atomic variables or immutable data to avoid race conditions; deadlock occurs when threads wait for each other forever.
3. ViewModel, LiveData and background executors (the Java way)
In a Java app the recommended pattern is: do the work on a background executor, keep the result in a ViewModel, and let the screen observe it with LiveData. The ViewModel survives rotation, and LiveData only delivers updates to a screen that is visible.
| Concept | Meaning |
|---|---|
| ExecutorService | A pool of background threads – Executors.newFixedThreadPool(n) or newSingleThreadExecutor() |
execute(Runnable) |
Run a task with no result (fire-and-forget) |
submit(Callable) → Future |
Run a task that returns a result; future.get() waits for it – lets two tasks run in parallel |
| Handler(Looper.getMainLooper()) | Posts code back to the UI thread |
| ViewModel | Holds screen data; survives rotation; onCleared() is called when the screen is finished – stop work there |
| MutableLiveData / LiveData | Observable value; setValue() on the main thread, postValue() from a background thread |
observe(this, value -> …) |
The activity reacts to new values; lifecycle-aware, so no leaks |
// Java: a ViewModel runs work on an executor and publishes the result with LiveData
public class ReportViewModel extends ViewModel {
private final ExecutorService io = Executors.newFixedThreadPool(2);
public final MutableLiveData<String> state = new MutableLiveData<>("Loading…");
public void load(Repo repo) {
io.execute(() -> {
try {
Future<Integer> a = io.submit(repo::attendance); // two requests in parallel
Future<Integer> b = io.submit(repo::marks);
state.postValue("Attendance " + a.get() + "%, Marks " + b.get()); // postValue = safe from any thread
} catch (Exception e) {
state.postValue("Network error");
}
});
}
@Override protected void onCleared() { io.shutdown(); } // stop work when the screen is gone
}
// ReportActivity.java
ReportViewModel vm = new ViewModelProvider(this).get(ReportViewModel.class);
vm.state.observe(this, text -> tvResult.setText(text)); // runs on the UI thread
vm.load(new Repo());
For reference – Kotlin coroutines: Kotlin apps do the same job with coroutines (viewModelScope.launch, Dispatchers.IO). You only need to know the idea: lightweight, suspendable tasks that are cancelled automatically with their scope.
Comparison
| Tool | Status | Use it for |
|---|---|---|
| Thread + runOnUiThread | Basic, manual | Very small one-off tasks |
| Handler/Looper | Current | Delays and posting to the UI thread |
| ExecutorService + ViewModel + LiveData | Recommended for Java | Network and database work tied to a screen |
| AsyncTask | Deprecated (API 30) | Do not use |
| Coroutines + Flow | Recommended for Kotlin | (Kotlin projects) |
| WorkManager | Current | Guaranteed background work (next section) |
4. Background work: services and WorkManager
| Need | Use |
|---|---|
| Work while the screen is open | ExecutorService in a ViewModel + LiveData (Kotlin: coroutines) |
| Deferrable but guaranteed work, even after app exit or reboot (upload, sync, backup) | WorkManager (Jetpack) |
| Long task the user is aware of (music, navigation, ongoing call, file transfer) | Foreground service with an ongoing notification and a declared foregroundServiceType |
| Exact time alarm (alarm clock, calendar reminder) | AlarmManager (setExactAndAllowWhileIdle, needs special permission) |
| Respond to system events | BroadcastReceiver (short work only) |
public class UploadWorker extends Worker {
public UploadWorker(@NonNull Context ctx, @NonNull WorkerParameters params) { super(ctx, params); }
@NonNull @Override
public Result doWork() { // already runs on a background thread
try {
uploadPendingFeedback();
return Result.success();
} catch (Exception e) {
return Result.retry();
}
}
}
Constraints constraints = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED).build();
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(UploadWorker.class)
.setConstraints(constraints).build();
WorkManager.getInstance(context).enqueue(request);
// periodic: new PeriodicWorkRequest.Builder(SyncWorker.class, 15, TimeUnit.MINUTES) (minimum 15 min)
Services (Service class): started services run until stopped; bound services provide a client–server interface; since Android 8 background services are restricted – use foreground services or WorkManager. IntentService is deprecated.
Part B – Publishing Android applications
5. Preparing the app for release
- Remove debugging: delete unnecessary
Logcalls, setdebuggablefalse (automatic in release builds). - Choose a unique, permanent
applicationId(e.g.pk.edu.uni.campusfeedback) – it can never change after publishing. - Versioning in
build.gradle.kts:versionCode– integer, must increase with every upload (1, 2, 3…).versionName– user-visible string ("1.0.0").
- Target the required API level – Google Play requires new apps and updates to target Android 16 (API 36) from 31 August 2026 (Android 15 / API 35 in 2025).
- Shrink and optimise – enable R8 (
isMinifyEnabled = true,isShrinkResources = true) to remove unused code/resources and obfuscate names; keep rules inproguard-rules.pro. - Provide an app icon (adaptive icon), app name, localisation and a privacy policy URL if you collect any data.
- Test the release build on several devices/API levels.
android {
defaultConfig { applicationId = "pk.edu.uni.campusfeedback"; versionCode = 3; versionName = "1.2" }
buildTypes {
release {
isMinifyEnabled = true
isShrinkResources = true
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
}
}
}
6. Signing the app
- Every APK/AAB must be digitally signed with a certificate (private key). Android uses the signature to verify the author and to allow updates only from the same key.
- Debug key – created automatically by Android Studio (
debug.keystore), not accepted by Play. - Upload key / release key – you create a keystore file (
.jks) with a key alias and passwords (Build → Generate Signed App Bundle / APK → Create new). Back it up safely – losing it can mean you cannot update your app (Play App Signing allows an upload-key reset). - Play App Signing (required for new apps): Google stores the app signing key; you sign uploads with your upload key; Google re-signs the APKs it delivers.
- APK signature schemes v1 (JAR), v2, v3, v4 – handled automatically by
apksigner/Gradle.
7. APK vs Android App Bundle (AAB)
| APK (Android Package) | AAB (Android App Bundle, .aab) |
|---|---|
| Installable file containing code, resources, manifest, signature | Publishing format – not directly installable |
| One APK has resources for all devices (bigger) | Google Play generates optimised split APKs per device (language, density, CPU) → smaller downloads |
| Used for sideloading, testing, other stores | Required for new apps on Google Play (since August 2021) |
8. Publishing steps (overview – details in week 15)
Build a signed release AAB → create a Google Play Console account → create the app → complete the store listing and policy forms → upload to a testing track → (new personal accounts: closed test with 12 testers for 14 days) → release to production → monitor Android vitals, crashes and reviews.
Other distribution options: Samsung Galaxy Store, Huawei AppGallery, Amazon Appstore, your own website (APK download), enterprise distribution (managed Google Play) and sideloading for testing. From 2026 Google is introducing Android developer verification – apps installed on certified devices must come from verified developers (rolled out first in Brazil, Indonesia, Singapore and Thailand from 30 September 2026; globally from 2027), with a free limited-distribution account for students and hobbyists.
Short and long questions
1. What is an ANR? When does it occur?
Model answer
ANR (Application Not Responding) is the system dialog shown when the main thread is blocked: no response to an input event within about 5 seconds, a BroadcastReceiver not finishing in time (about 10 s), or a service not starting in time. It is avoided by moving heavy work to background threads.
2. What is the main thread? State the two threading rules of Android.
Model answer
The main (UI) thread is the single thread created for an app process that draws the UI, handles input and runs lifecycle callbacks. Rules: (1) never block the UI thread with long work – use background threads; (2) never access UI views from a background thread – switch back to the main thread to update them.
3. Describe the complete process of preparing, signing and publishing an Android application. Explain versioning, R8, keystores, Play App Signing, and the difference between APK and AAB.
Model answer
Preparation: remove logs and debug code; choose a permanent unique applicationId; set versionCode (integer that increases with every release) and versionName (user-facing, e.g. 1.2.0); set targetSdk to the level Google Play requires (API 36 from 31 August 2026); enable R8 with isMinifyEnabled and isShrinkResources and keep rules in proguard-rules.pro; prepare an adaptive icon, localised strings, and a privacy policy; test the release build on several devices and API levels.
Signing: Android installs only signed packages and accepts updates only with the same signing identity. Debug builds use an automatic debug key. For release, create a keystore (.jks) with a key alias and passwords via Build → Generate Signed App Bundle/APK and back it up. With Play App Signing (mandatory for new apps) Google keeps the app signing key and the developer signs uploads with an upload key, which can be reset if lost.
APK vs AAB: an APK is the installable package containing all code and resources for every device; an AAB is the publishing format from which Google Play generates optimised split APKs per device (screen density, language, CPU ABI), reducing download size. AAB is required for new apps on Google Play since August 2021; APKs are used for sideloading, testing and some other stores.
Publishing: create a Google Play Console developer account (one-time USD 25), create the app, complete store listing (title, descriptions, icon, screenshots, feature graphic), content rating, data safety, target audience and privacy policy, upload the signed AAB to a testing track (new personal accounts must run a closed test with at least 12 testers for 14 days), then roll out to production in stages and monitor crashes, ANRs, reviews and Android vitals. Alternatives: Samsung Galaxy Store, Huawei AppGallery, direct APK distribution – subject to Google's developer verification programme starting in 2026.
4. Differentiate between APK and AAB.
Model answer
An APK is the installable Android package with all code and resources for every device type, used for sideloading and testing. An AAB is a publishing format uploaded to Google Play, which generates optimised split APKs for each device configuration, giving smaller downloads; AAB is mandatory for new Play apps.
5. List the steps to prepare an Android app for release.
Model answer
Remove debug code and logs; set a permanent applicationId; set versionCode and versionName; target the required API level; enable R8 shrinking and resource shrinking; add icon, name, localisation and privacy policy; generate a signed release AAB/APK with a release/upload keystore; test the release build on several devices.
6. Write code to perform work in a background thread and update the UI.
Model answer
new Thread(() -> { String data = loadData(); runOnUiThread(() -> textView.setText(data)); }).start(); – the work runs on the new thread and runOnUiThread posts the UI update to the main thread (alternatively view.post(...) or new Handler(Looper.getMainLooper()).post(...)).
7. When should WorkManager be used instead of an executor or a foreground service?
Model answer
WorkManager is for deferrable work that must be guaranteed to complete even if the app exits or the device reboots, optionally under constraints (network, charging), such as uploading feedback or syncing data. Executors in a ViewModel (or coroutines in Kotlin) suit work tied to a visible screen, and foreground services suit long, user-visible tasks like music playback.
8. Explain threading in Android. Why must long tasks run in the background? Describe Threads, Handlers, AsyncTask, Executors and the ViewModel + LiveData pattern, with Java code, and explain how results are returned to the UI thread.
Model answer
Main thread: each app runs in a Linux process whose main (UI) thread draws frames (~16 ms each), processes input and runs lifecycle callbacks. Long operations on it cause jank and, after about 5 seconds without responding to input, an ANR dialog; network on it throws NetworkOnMainThreadException. The UI toolkit is not thread-safe, so views may only be touched from the main thread (CalledFromWrongThreadException otherwise).
Thread: new Thread(() -> { String d = work(); runOnUiThread(() -> tv.setText(d)); }).start(); – simple but manual and lifecycle-unaware.
Handler/Looper/MessageQueue: a Looper loops over a thread's MessageQueue; a Handler posts messages or runnables to it, e.g. new Handler(Looper.getMainLooper()).postDelayed(() -> { ... }, 1000); to update the UI later.
AsyncTask: doInBackground/onPostExecute helper, deprecated in API 30 due to leaks and lifecycle issues.
Executors: Executors.newFixedThreadPool(4).execute(() -> { ... }); reuses threads instead of creating new ones.
ViewModel + LiveData + ExecutorService (recommended in Java): the ViewModel starts the work on an executor (io.execute(...)), puts the result in MutableLiveData with postValue(), and the activity observes it with vm.data.observe(this, d -> tv.setText(d)). The ViewModel survives rotation, LiveData only updates an active screen, and onCleared() shuts the executor down – so no leaks. (Kotlin apps use coroutines with Dispatchers.IO for the same purpose.)
Longer work: WorkManager for guaranteed deferrable tasks with constraints; foreground services for ongoing user-visible tasks; AlarmManager for exact alarms.
9. Why was AsyncTask deprecated?
Model answer
It caused memory leaks by holding references to activities, behaved inconsistently across Android versions, ignored lifecycle changes such as rotation, and had complex cancellation; it was deprecated in API 30 in favour of java.util.concurrent executors (with ViewModel/LiveData) in Java and coroutines in Kotlin.
10. Write Java code that loads data on a background thread with an ExecutorService and shows it in a TextView.
Model answer
ExecutorService ex = Executors.newSingleThreadExecutor(); Handler main = new Handler(Looper.getMainLooper()); ex.execute(() -> { String d = loadData(); main.post(() -> tv.setText(d)); }); – loadData runs in the background and the Handler posts the UI update to the main thread.
11. What is the difference between setValue() and postValue() in LiveData?
Model answer
setValue() updates the value immediately and must be called on the main thread; postValue() can be called from any (background) thread and schedules the update on the main thread.
This lesson ends with a quiz of 28 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: Supabase Week Lab – Create a Supabase Backend and Read/Write It from Android with Retrofit · Next: Week 14 Lab 14 – Display a Location on Google Maps Using Coordinates
All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester