如何使用 Hilt 将 SharedPreferences 注入后台服务

How to inject SharedPreferences to Background service using Hilt

我正在尝试将 SharedPrefernces 注入 Timer 前台服务 class。我在服务 class.

上使用 @EntryPoint 注释

ApplicationModule class

@Module
@InstallIn(SingletonComponent::class)
class ApplicationModule() {

@Singleton
@Provides
fun provideSharedPreferences(@ApplicationContext appContext: Context): SharedPreferences {
      return PreferenceManager.getDefaultSharedPreferences(appContext)
  }
}

Timer service class

@EntryPoint
class Timer : Service() {

    @Inject
    lateinit var preferences: SharedPreferences
    ...
    }

当我 运行 这段代码时,我得到这个错误: @EntryPoint com.beu.coroutineskotlin.Timer must also be annotated with @InstallIn [Hilt] Processing did not complete. See error above for details.warning: File for type 'com.beu.coroutineskotlin.App_HiltComponents' created in the last round will not be subject to annotation processing.

我还没有试过服务。但是,我认为您必须使用 @AndroidEntryPoint 而不是 @EntryPoint@EntryPoint 用于创建这样的自定义入口点 https://dagger.dev/hilt/entry-points.html