【问题标题】:Hilt injection in Android ServicesAndroid 服务中的 Hilt 注入
【发布时间】:2021-05-08 05:04:53
【问题描述】:

我想在Service 中注入一个类。让我们看看下面的代码:

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

@AndroidEntryPoint
class LocationUpdateService : Service() {

    @Inject
    lateinit var deviceUtil: DeviceUtil

    ...
}

@Inject lateinit var deviceUtil: DeviceUtil 在 Activity 中工作正常,但在 Service 中不工作。

它给出了错误: kotlin.UninitializedPropertyAccessException: lateinit property deviceUtil has not been initialized

【问题讨论】:

  • 所以,我错误地忘记在 onCreate 方法中调用super.onCreate(),通过添加这个解决了我的问题。
  • 在我的情况下,它仍然不能通过添加 super.onCreate() 来解决,现在它告诉我如果没有 @Provides-annotated 方法就无法提供我注入的 useCase(我将它绑定在我的用例模块),尽管它在我的视图模型上运行良好(通过构造函数注入)
  • 我没有得到你的问题,你能分享一下你的实施快照吗?但是,我认为您需要为特定的用例类使用 @Provides 或使用构造函数注入。
  • 原来我将用例模块的范围限定为activityRetainedComponent,同时将该用例注入服务(用AndroidentryyPoint注释),对我来说,我只是将用例模块和存储库模块的范围更改为ApplicationComponent,这行得通对我来说很好

标签: android dependency-injection dagger-2 dagger-hilt


【解决方案1】:

对于像我这样的傻瓜。正如 OP 在 cmets 中所说,关于如何在 service 中注入对象的完整示例如下:

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() {
            // ...
        }
    }
}

至于您要注入的服务,请确保它的构造函数中有 @Inject 注释,如下所示:

class UserService @Inject() constructor() {
  // ...
}

【讨论】:

  • 我试过了,但我仍然遇到同样的问题
  • 确保您的UserService 在构造函数中有@inject 注释,如下所示: ``` class UserService @Inject constructor() { } ``
猜你喜欢
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 2021-04-16
  • 1970-01-01
相关资源
最近更新 更多