Service vs Intent Service in Android

Upasana | May 05, 2019 | 1 min read | 31 views


Service is a class of android SDK, And Intent Service is a subclass of Service class.

We are going to talk about the differences between Service and Intent Service.

Let’s be on Service first

Service is a base class for all services. The service class runs in the application’s main thread. So, it can reduce application performance. You can create a service in your application by extending Service class. In service, you have to override the onBind() function. If you return null to onBind() function, it will take a default binder for your service. You can run your tasks inside onStartCommand() function body. After performing all tasks you have to terminate service by calling stopSelf() function.

Let’s code it

MyService.kt
class MyService: Service() {

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

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        // Write your statements here
        return super.onStartCommand(intent, flags, startId)
    }
}

Now, Let’s be on Intent Service

Intent service is a subclass of Service class. Intent service runs on the application’s background thread. You have to override onHandleIntent() function. You can write your statements inside onHandleIntent() function or onStartCommand() function. Intent service will get automatically terminated when all tasks get finished, So you don’t need to call any function to terminate the Service.

MyIntentService.kt
class MyIntentService: IntentService("MyIntentService") {

    override fun onHandleIntent(intent: Intent?) {
        // Write your statements here
    }
}

Top articles in this category:
  1. Retrofit Basic Authentication in Android
  2. Retrofit OAuth2 Bearer Token Authentication OkHttp Android
  3. FirebaseInstanceIdService is deprecated now
  4. Firebase Cloud Messaging in Android App using Command Pattern
  5. iOS interview experience fresher
  6. iOS interview questions for 0-3 years experience
  7. Kotlin Coroutines with Retrofit

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.