12

I want to inject a class in Service. Lets have a look at the code below:

class DeviceUtil @Inject constructor() {
   ...
}

@AndroidEntryPoint
class LocationUpdateService : Service() {

    @Inject
    lateinit var deviceUtil: DeviceUtil

    ...
}

@Inject lateinit var deviceUtil: DeviceUtil is working fine in Activity but not working in Service.

Its giving the error: kotlin.UninitializedPropertyAccessException: lateinit property deviceUtil has not been initialized

Amir Raza
  • 2,320
  • 1
  • 23
  • 32
  • 8
    So, I mistakenly forget to call `super.onCreate()` in onCreate method, by adding this solved my problem. – Amir Raza Feb 04 '21 at 10:43
  • in my case it is still not solved by just adding super.onCreate() , now it is telling me my injected useCase cannot be provided without an @Provides-annotated method (i am binding it in my usecase module),though it is working fine on my viewmodel (injected through constructor) – joghm Apr 05 '21 at 18:50
  • I didn't get your problem, can you please share any snapshot of your implementation? However, I think you need to use @Provides or use constructor injection for your specific usecase class. – Amir Raza Apr 05 '21 at 19:19
  • Turns out i am scoping the usecase module to activityRetainedComponent whilst injecting that usecase into the Service (annoted with AndroidentryyPoint) ,for me i just changed the scope of the usecase module and repository module to ApplicationComponent, this works fine for me – joghm Apr 05 '21 at 20:51

1 Answers1

1

For those dummies like me. As said by OP in the comments, a full example on how you can inject object in your service like so:

import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

import com.yourapp.services.UserService

@AndroidEntryPoint
class MyService: Service() {
    @Inject lateinit var userService: UserService

    override fun onCreate() {
        super.onCreate()

        userService.getUserList()
                .subscribe { userList -> Log.d("tag", "users: $userList") }
    }

    override fun onBind(intent: Intent?): IBinder? {
        return object: Binder() {
            // ...
        }
    }
}

As for the service you're injecting make sure it has the @Inject annotation in its constructor like so:

class UserService @Inject() constructor() {
  // ...
}
Miko Chu
  • 1,087
  • 14
  • 22