0% found this document useful (0 votes)
4 views6 pages

Android Question

Uploaded by

parthakunt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

Android Question

Uploaded by

parthakunt
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Android Services - Complete Overview

Services only: architecture, Started, Bound, Foreground, IntentService, internals, examples,


interview points

How to use this PDF before interview

Read the definition first, then remember the real-world example. In interview, always answer in this order: what it is -> how
it works internally -> when to use -> when not to use.

1 1. Why Service is required in Android

A Service is required when some work should continue without depending on the visible screen. Activity is mainly for UI;
Service is for background execution. A Service does not create UI, but it runs inside the app process and Android controls its
lifecycle. It is useful when the user leaves the screen but the task still matters, like music, navigation, file upload, or progress
tracking.

Need Why Service helps

Music playback Song should continue even if user locks phone or opens another app.

Location/navigation Location updates should continue while app is not visible.

Download/upload Long-running transfer should not depend only on Activity.

UI + background communication Activity can bind to service and read progress or control actions.

2 2. Android Service architecture - internal flow

startService() / bindService() system resources


Activity/UI Service Android OS

lifecycle managed by system

ActivityManager Service Manager App Process

Internally, when Activity calls startService() or bindService(), the request goes to Android framework. Android creates the
Service object inside the app process if it is not already created. Then Android calls lifecycle methods like onCreate(),
onStartCommand(), onBind(), and onDestroy(). The important point: Service still runs on the main thread by default, so
heavy work must be moved to a background thread, coroutine, executor, or foreground process pattern.

Android Services Interview Revision - Services only Page 1


3 3. Types of Android Services

Type Simple meaning Real example

Started Service Runs independently after startService(). Music playback, file upload.

Bound Service Client connects using bindService() and communicates. Download progress, media controller.

Foreground Service Long-running visible service with notification. Navigation, fitness tracking.

IntentService Old service with background queue, now deprecated. Old image upload queue.

Important base rule

A normal Service is not automatically a background thread. It is a background component, but lifecycle callbacks run on the
main thread. Never perform heavy blocking work directly inside onStartCommand() or onBind().

4 4. Started Service - how it works

Started Service is started using startService(). Once started, it can continue running even if the Activity that started it is
destroyed. Android calls onCreate() once, then onStartCommand() for each start request. It is useful when the service owns
the task and does not need continuous UI communication. The service must stop itself using stopSelf() or another component
must call stopService().

class MusicService : Service() {


onCreate()
override fun onStartCommand(
intent: Intent?, flags: Int, startId: Int
onStartCommand() ): Int {
// Start music playback here
return START_STICKY
Running }

override fun onBind(intent: Intent?): IBinder? = null


}
stopSelf()/stopService()

onDestroy()
Real-world usage Explanation

Music app User starts music, closes screen, but playback continues.

File upload Upload can continue even if user leaves the upload screen.

Tracking task Background tracking may continue until explicitly stopped.

Interview point

Use Started Service when the work is independent. Do not use it when the UI needs frequent live progress updates. For
live progress, Bound Service is better.

Android Services Interview Revision - Services only Page 2


5 5. Bound Service - how it works

Bound Service is used when Activity or Fragment wants to connect to a Service and communicate with it. The client calls
bindService(). Android calls onBind(), and the service returns an IBinder. Through that Binder, the client can call service
methods like getProgress(), pauseDownload(), or resumeDownload(). Bound Service usually lives as long as clients are
bound to it.

class DownloadService : Service() {


onCreate()
private val binder = LocalBinder()

onBind() inner class LocalBinder : Binder() {


fun getService(): DownloadService = this@DownloadSer
}
Running (Bound)
override fun onBind(intent: Intent?): IBinder = binder

fun getProgress(): Int = 70


onUnbind()
}

onDestroy()
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val binder = service as [Link]
val downloadService = [Link]()
val progress = [Link]()
}

override fun onServiceDisconnected(name: ComponentName?) {}


}

Real-world usage Explanation

Download manager UI shows download percentage from service.

Music controls Activity sends play, pause, next commands to service.

Streaming app UI communicates with service for buffering and status.

Bound Service memory trick

Bound Service is like client-server inside your app. Activity is the client. Service is the server. Binder is the connection
between them.

Android Services Interview Revision - Services only Page 3


6 6. Started Service vs Bound Service

Point Started Service Bound Service

How started startService() bindService()

Main purpose Independent background work Communication with Activity/Fragment

Lifecycle depends on stopSelf() or stopService() Bound clients

Communication Limited Strong two-way communication

Example Music playback started and continues Download progress shown in UI

Best interview phrase Fire and continue Connect and communicate

Which one should I choose?

If the task must continue even if UI disappears, choose Started Service. If UI needs live data/control from service, choose
Bound Service. Some real apps use both: start service for continuity and bind to it when UI is visible.

7 7. Foreground Service - how it works

Foreground Service is a Service that performs long-running work that the user should be aware of. It must show an ongoing
notification. Android uses this rule because background services can drain battery and users should know when important
continuous work is running. Foreground Service is less likely to be killed compared to normal background services, but it must
be used only for user-visible work.

class TrackingService : Service() {


override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = createTrackingNotification()
startForeground(1, notification)
startLocationTracking()
return START_STICKY
}

override fun onBind(intent: Intent?): IBinder? = null


}

Real-world usage Why foreground service

Google Maps navigation User must see navigation is active.

Spotify music Playback controls visible in notification.

Fitness tracking Steps, heart rate, GPS continue while screen is off.

Important

If you run a long-running visible task without proper foreground service notification, the app can crash or the system can
stop the work on newer Android versions.

Android Services Interview Revision - Services only Page 4


8 8. IntentService - deprecated but interview important

IntentService was created to simplify background work. It created a worker thread automatically, processed incoming intents
one by one, and stopped itself after finishing the queue. It was useful for old upload/download queues. Now it is deprecated
because modern Android prefers other APIs for reliable background work and lifecycle-aware execution.

class UploadIntentService : IntentService("UploadIntentService") {


override fun onHandleIntent(intent: Intent?) {
val path = intent?.getStringExtra("path")
uploadFile(path)
}
}

IntentService feature Meaning

Background thread onHandleIntent() ran on worker thread.

Queue behavior Multiple intents processed one by one.

Auto stop Stops after completing all requests.

Current status Deprecated, do not use in new apps.

9 9. Service internal lifecycle summary

Callback When called What to do

onCreate() First time service is created Initialize resources, player, tracker, binder.

onStartCommand() Each startService() request Start/continue independent work.

onBind() Client binds using bindService() Return Binder for communication.

onUnbind() All clients unbind Clean client-specific resources.

onDestroy() Service is stopped/destroyed Release resources, unregister listeners.

Threading note

Service lifecycle callbacks run on the main thread. If you do network, database, bitmap processing, file IO, or long loops
directly there, you can cause ANR. Move heavy work to a background thread/coroutine/executor.

Android Services Interview Revision - Services only Page 5


10 10. Best practices for Android Services

Practice Reason

Do not do heavy work on main thread Prevents ANR and UI freeze.

Stop service when work is done Avoid battery drain and memory leaks.

Use Foreground Service only for visible tasks Required by Android background rules.

Use Bound Service for UI communication Cleaner client-service design.

Release resources in onDestroy() Avoid leaks for player, receiver, location listener.

Handle configuration changes carefully Activity may recreate while service continues.

11 11. Real-world service design examples

Scenario Service choice Why

Music app Foreground + Started Service Playback continues and notification controls visible.

Download screen Bound Service Activity needs progress and controls.

Navigation app Foreground Service Location tracking is visible continuous work.

Fitness app Foreground Service Tracks user activity while screen is off.

Old image upload queue IntentService previously Sequential background queue, now deprecated.

12 12. Interview questions - services only

Question Answer direction

What is a Service? Background component without UI for long-running work.

Does Service run on background thread? No. Callbacks run on main thread by default.

Started vs Bound Service? Started is independent, Bound is for communication.

Why Foreground Service? For user-visible continuous work with notification.

Why IntentService deprecated? Old queue/thread model, not recommended for modern apps.

When is onStartCommand called? When startService() is called.

When is onBind called? When a client binds using bindService().

What is Binder? Object returned to client for service communication.

What is START_STICKY? Ask system to recreate service after kill when possible.

How to avoid ANR in Service? Move heavy work off main thread.

Final memory trick

Started Service = start and continue. Bound Service = connect and communicate. Foreground Service = visible
continuous work. IntentService = old sequential queue.

Android Services Interview Revision - Services only Page 6

You might also like