Search code examples
androidkotlindagger

Can we do constructor injection in service class in android?


here is my Service class

class MyFirebaseMessagingService @Inject constructor(private val repository : Repository) :
    FirebaseMessagingService() {....}

class Repository @Inject constructor(private val apiService: ApiService) {}

and ApiService is Interface

The problem is on the first launch of app. This app is crashing with below message

java.lang.RuntimeException: Unable to instantiate service com.projects.driverapp.MyFirebaseMessagingService: java.lang.InstantiationException: java.lang.Class<com.projects.driverapp.MyFirebaseMessagingService> has no zero argument constructor

But after this crash, on second launch of app , this project works fine without crash, what is the root cause ?


Solution

  • Use @AndroidEntryPoint in your service class and Add field injection (@Inject)

    Example:

    @AndroidEntryPoint
    class YourServiceClass : Service() {
    
      @Inject lateinit var analyticsRepo: AnalyticsRepository // Replace your class
      ...
    }
    

    According to the documentation, it is recommended to annotate services with @AndroidEntryPoint. Typically, services should have a constructor with zero parameters so that they can be initiated using startService().