'Hilt injection in Android Services
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
Solution 1:[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() {
// ...
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |