Search code examples
androidkotlindependency-injectionservicedagger-hilt

How to inject SharedPreferences to Background service using Hilt


I am trying to inject SharedPrefernces to Timer foreground service class. I use @EntryPoint annotation over service class.

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
    ...
    }

When I run this code, I get this error: @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.


Solution

  • I haven't tried on a service. however, i think you must use @AndroidEntryPoint and not @EntryPoint. @EntryPoint is used to create a custom entry point like this https://dagger.dev/hilt/entry-points.html