SoFunction
Updated on 2025-04-06

Service types and startup methods in Android

A summary of one sentence:

ServiceIt is an Android "background worker". It is divided into two types (front desk and backend), two startup methods (work by yourself and work with others), and different postures are used in different scenarios.

1. Two types of Service:

1. Front desk service (identity card must be displayed)

  • Features: One must be displayedResident Notification(Like the delivery guy is wearing work clothes), telling the user "I am working in the background" to avoid being killed by the system.

  • Applicable scenarios

    • Music playback (show playback notification).
    • File download (show progress bar).
    • Positioning tracking (such as navigation).
  • Code Example

val notification = buildNotification() // Create notificationstartForeground(1, notification) // Turn into a front desk service

2. Backend service (working secretly, but being easily caught)

  • Features: No notification, I worked silently, butAndroid 8.0 has strict restrictions(Long-term background operation will be restricted by the system).

  • Applicable scenarios

    • Temporary tasks (such as data synchronization).
    • Lightweight tasks (such as timed reminders).
  • Notice: In higher versions of Android, background services may not survive for a long time, so it is recommended to use them instead.WorkManagerorJobScheduler

2. Two ways to start the service:

1. Work independently (startService)

  • Features

    • passstartService()Start, the Service will run until it is called activelystopSelf()Or other component callsstopService()
    • life cycleonCreate() → onStartCommand()→ (In operation) →onDestroy()
  • Applicable scenarios

    • Tasks that require long-term running (such as playing music).
    • Independent tasks that do not depend on other components.
  • Code Example

// Start the serviceval intent = Intent(this, MyService::)
startService(intent)

// Stop servicestopService(intent)

2. Work with others (bindService)

  • Features

    • passbindService()Start, Service and components (such as Activity) are bound,Service may be destroyed after the binding is unblocked
    • life cycleonCreate() → onBind()→ (In operation) →onUnbind() → onDestroy()
    • Can be passedIBinderInterface implementation components and serviceTwo-way communication(For example, control the progress of music playback).
  • Applicable scenarios

    • Tasks that need to interact with the interface (such as controlling download progress).
    • Multiple components share the same Service.
  • Code Example

// Binding Serviceval connection = object : ServiceConnection {
    override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
        // Get the Service interface and interact    }
    override fun onServiceDisconnected(name: ComponentName?) {}
}
bindService(intent, connection, Context.BIND_AUTO_CREATE)

// Unbind serviceunbindService(connection)

3. Mixed mode (start + bind)

  • Features

    • FirststartService()Let the Service run for a long time, thenbindService()Entertainment.
    • Applicable scenarios: Music player (long-term play + interface control progress).
  • Destruction conditions: Must be called at the same timestopService()andunbindService()It will only be destroyed.

4. IntentService (outdated, but you should know)

  • Features

    • It comes with its own work thread, the tasks are executed in sequence, and they are automatically closed after work.
    • Android 8.0 is restricted, recommended to useWorkManagerorJobIntentService
  • Code Example

class MyIntentService : IntentService("MyIntentService") {
    override fun onHandleIntent(intent: Intent?) {
        // Execute time-consuming tasks on child thread    }
}

5. How to choose the startup method?

Scene Startup method type
Long-term tasks (such as music playback) startService() Front Desk Service
Temporary interaction (such as download control) bindService() Binding Service
Lightweight background tasks (such as data synchronization) WorkManager Backend service replacement

Summarize

  • Front Desk Service: Show notifications, suitable for user-perceived tasks.

  • Backend Service: Try to use as little as possible, with more restrictions on higher versions of Android.

  • Startup method

    • Work independently:usestartService(), remember to close.
    • Work together:usebindService(), remember to solve the problem after binding.
  • Prompt

    • "Let's use the front desk for a long time to show off your cards, bind temporary cooperation, do not have a hard bar in the higher version, WorkManager is more stable"

The above is the detailed content of the Service Types and Startup Methods in Android. For more information about Android Service Types and Startup, please follow my other related articles!