如何从服务Android Dagger-Hilt调用存储库



我在应用程序中使用Dagger-Hilt,并希望从AlarmService调用存储库方法getRandomWordForNotification((。我如何才能实现坚持MVVM模式的注释代码?

@AndroidEntryPoint
class AlarmService(name: String = "AlarmService"): IntentService(name) {
//private var word: Def? = null
override fun onHandleIntent(p0: Intent?) {
val i = Intent(applicationContext, ListFragment::class.java)
val pendingIntent = PendingIntent.getActivity(applicationContext, 0, i, 0)
//word = repository.getRandomRandomWordForNotification().value
val notification = NotificationCompat.Builder(this.applicationContext, "channelID")
.setSmallIcon(R.drawable.ic_add_notification)
.setContentTitle("Daily Reminder")
.setContentText(/*"${word!!.text} - ${word!!.tr[0].text}"*/"")
.setAutoCancel(true)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.build()
val notificationManager = NotificationManagerCompat.from(applicationContext)
notificationManager.notify(123, notification)
}
}
class DictionaryRepository @Inject constructor(
private val dictionaryDao: DictionaryDao,
private val dictionaryApi: DictionaryApi
) {
suspend fun getTranslation(text: String) = dictionaryApi.getTranslation(text=text)
suspend fun upsert(def: Def) = dictionaryDao.upsert(def)
fun getAllTranslations() = dictionaryDao.getAllTranslations()
fun getTranslationsSize() = dictionaryDao.getTranslationsSize()
fun getRandomTranslations() = dictionaryDao.getRandomTranslations()
fun getRandomRandomWordForNotification() = dictionaryDao.getRandomWordForNotification()
suspend fun deleteTranslation(def: Def) = dictionaryDao.deleteTranslation(def)
}

好的->

首先制作一个接口,例如:

interface RepositoryHandler {
fun getRandomNotification(notificationNumber: Int)
}

然后将其用作AlarmServie fox的参数示例:

@AndroidEntryPoint
class AlarmService(val repositoryHandler: RepositoryHandler,name: String = "AlarmService"): IntentService(name) {
//private var word: Def? = null
override fun onHandleIntent(p0: Intent?) {
//////////////////// use repositoryHandler.getRandomNotification(number of notifications)
}
}

然后

class DictionaryRepository @Inject constructor(
private val dictionaryDao: DictionaryDao,
private val dictionaryApi: DictionaryApi
):NotificatonHandler{
-------------------------
}

然后你应该在应用程序模块中提供DictionaryRepository

@Binds
@Singletone
fun bindDictionaryRepository(dictionaryRepository:DictionaryRepository): RepositoryHandler

然后在ViewModel中注入RepositoryHandler

如果有帮助,请投票回答

最新更新