Background/ Started Service

Started Service

1. What is a Started Service?

A Started Service is a service that starts when another component calls:

startService(intent)

It keeps running until we stop it using:

stopSelf()

or

stopService(intent)

Simple Meaning

Started Service = Start work and run independently


2. When Should We Use Started Service?

Use Started Service when:

RequirementUse Started Service?
One-time workYes
Activity does not need direct communicationYes
Short background taskYes
Long visible taskPrefer Foreground Service
Reliable retry workPrefer WorkManager

Example

User clicks upload button.

User clicks Upload
        ↓
Activity starts UploadService
        ↓
UploadService uploads file
        ↓
Upload completed
        ↓
Service stops itself


3. Started Service Lifecycle

startService()
      ↓
onCreate()
      ↓
onStartCommand()
      ↓
Service Running
      ↓
stopSelf() / stopService()
      ↓
onDestroy()

Lifecycle Methods

| Method             | Meaning                             |
| ------------------ | ----------------------------------- |
| `onCreate()`       | Called once when service is created |
| `onStartCommand()` | Called when service is started      |
| `stopSelf()`       | Service stops itself                |
| `onDestroy()`      | Called before service is destroyed  |
| `onBind()`         | Returns `null` for Started Service  |


4. How Started Service Works Internally

Activity
   ↓ startService(intent) 
Android System
   ↓ Creates Service object
Service.onCreate()
    ↓
Service.onStartCommand()
    ↓
Task starts
    ↓
Task finishes
    ↓
stopSelf()
    ↓
onDestroy()

Important point:

If startService() is called multiple times,
onStartCommand() can be called multiple times.


5. Started Service Pseudocode

WHEN user clicks Upload button:

    Create Intent for UploadService
    Add file path inside Intent
    Start UploadService

IN UploadService:

    Receive file path
    Start upload on background thread
    When upload completes:
        Stop service


5. Started Service Code Example

UploadService.kt

class UploadService : Service() {

    override fun onCreate() {
        super.onCreate()
        Log.d("UploadService", "Service created")
    }

    override fun onStartCommand(
        intent: Intent?,
        flags: Int,
        startId: Int
    ): Int {

        val filePath = intent?.getStringExtra("file_path")

        Thread {
            uploadFile(filePath)

            // Stop service after upload is complete
            stopSelf(startId)
        }.start()

        return START_NOT_STICKY
    }

    private fun uploadFile(filePath: String?) {
        Log.d("UploadService", "Uploading file: $filePath")

        // Simulating upload task
        Thread.sleep(3000)

        Log.d("UploadService", "Upload complete")
    }

    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("UploadService", "Service destroyed")
    }
}

AndroidManifest.xml

<service
    android:name=".UploadService"
    android:exported="false" />

Start Service from Activity

val intent = Intent(this, UploadService::class.java)
intent.putExtra("file_path", "/storage/video.mp4")
startService(intent)
## 11. `onStartCommand()` Return Values

Inside Started Service, this line is very important:

return START_NOT_STICKY

Android asks:

If system kills this service, should I restart it later?

Common Return Types

Return TypeMeaningBest Use Case
START_NOT_STICKYDo not restart automaticallyOne-time upload
START_STICKYRestart service, but intent may be nullMusic player, tracking
START_REDELIVER_INTENTRestart service and redeliver old intentImportant file upload

Example 1: START_NOT_STICKY

return START_NOT_STICKY

Use case:

Upload file once.
If system kills service, do not restart automatically.

Example 2: START_STICKY

return START_STICKY

Use case:

Music player service.
If service is killed, restart because music should continue.

Example 3: START_REDELIVER_INTENT

return START_REDELIVER_INTENT

Use case:

Important report upload.
If service is killed, restart with the same file path intent.


6. Benefits of Started Service

BenefitExplanation
Simple to useEasy to start using startService()
Good for one-way workActivity does not need direct communication
Can run independentlyWork can continue even if Activity is closed
Useful for short tasksGood for one-time background operations


7. Drawbacks of Started Service

DrawbackExplanation
Runs on main thread by defaultHeavy work must be moved to background thread
No direct communicationActivity cannot directly call service methods
Can be killed by systemAndroid may stop it under memory pressure
Background restrictionsModern Android limits background services
Manual stopping requiredMust call stopSelf() or stopService()