Я пытаюсь внедрить передний план и уведомление с репозиторием с использованием рукояти, но и услуга, и уведомление, похоже, не имеют доступа к репозиторию. Я не получаю никаких ошибок, но я вижу, что ни поиск объекта, ни обновление в базе данных не выполняются. Что я делаю не так? < /P>
@AndroidEntryPoint
class StopwatchService: Service() {
@Inject
lateinit var notificationManager: NotificationManager
@Inject
lateinit var notificationBuilder: NotificationCompat.Builder
@Inject
lateinit var activityRepository: IActivitiesRepository
private val job = SupervisorJob()
private val scope = CoroutineScope(Dispatchers.IO + job)
private suspend fun cancelStopwatch() {
val endTime = Time(
LocalDateTime.now().hour,
LocalDateTime.now().minute
)
val recordedActivity = activityRepository.getRecordedActivity().first()
if (recordedActivity != null) {
recordedActivity.endTime = endTime
activityRepository.updateActivity(recordedActivity)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Thread(Runnable {
when (intent?.getStringExtra(STOPWATCH_STATE)) {
StopwatchState.Started.name -> {
setStopButton()
startForegroundService()
startStopwatch { hours, minutes, seconds ->
updateNotification(hours = hours, minutes = minutes, seconds = seconds)
}
}
StopwatchState.Stopped.name -> {
stopStopwatch()
scope.launch {
cancelStopwatch()
}
stopForegroundService()
}
}
intent?.action.let {
when (it) {
ACTION_SERVICE_START -> {
setStopButton()
startForegroundService()
startStopwatch { hours, minutes, seconds ->
updateNotification(hours = hours, minutes = minutes, seconds = seconds)
}
}
ACTION_SERVICE_STOP -> {
stopStopwatch()
scope.launch {
cancelStopwatch()
}
stopForegroundService()
}
}
}
}).start()
return super.onStartCommand(intent, flags, startId)
}
}
< /code>
@Module
@InstallIn(ServiceComponent::class)
// Updates and modifies the notification along the stopwatch
object NotificationModule {
@ServiceScoped
@Provides
fun provideNotificationBuilder(@ApplicationContext context: Context): NotificationCompat.Builder {
val job = SupervisorJob()
val scope = CoroutineScope(Dispatchers.IO + job)
var activitiesRepository = RepositoryActivities(OfflineDatabase.getDatabase(context).activityDao())
var recordedActivity: Activity? = null
scope.launch {
recordedActivity = activitiesRepository.getRecordedActivity().first()
}
return NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setContentTitle(recordedActivity?.title ?: "Activity")
// Default text of the notification
.setContentText("00:00:00")
.setOngoing(true)
.addAction(0, "Stop", ServiceHelper.stopPendingIntent(context))
.setContentIntent(ServiceHelper.clickPendingIntent(context))
}
}
< /code>
@Module
@InstallIn(ServiceComponent::class)
object RepositoryModule {
@ServiceScoped
@Provides
fun provideActivityRepository(@ApplicationContext context: Context): IActivitiesRepository {
return RepositoryActivities(OfflineDatabase.getDatabase(context).activityDao())
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... -a-service
Как правильно ввести и использовать хранилище в сервисе? ⇐ Android
Форум для тех, кто программирует под Android
-
Anonymous
1755799956
Anonymous
Я пытаюсь внедрить передний план и уведомление с репозиторием с использованием рукояти, но и услуга, и уведомление, похоже, не имеют доступа к репозиторию. Я не получаю никаких ошибок, но я вижу, что ни поиск объекта, ни обновление в базе данных не выполняются. Что я делаю не так? < /P>
@AndroidEntryPoint
class StopwatchService: Service() {
@Inject
lateinit var notificationManager: NotificationManager
@Inject
lateinit var notificationBuilder: NotificationCompat.Builder
@Inject
lateinit var activityRepository: IActivitiesRepository
private val job = SupervisorJob()
private val scope = CoroutineScope(Dispatchers.IO + job)
private suspend fun cancelStopwatch() {
val endTime = Time(
LocalDateTime.now().hour,
LocalDateTime.now().minute
)
val recordedActivity = activityRepository.getRecordedActivity().first()
if (recordedActivity != null) {
recordedActivity.endTime = endTime
activityRepository.updateActivity(recordedActivity)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Thread(Runnable {
when (intent?.getStringExtra(STOPWATCH_STATE)) {
StopwatchState.Started.name -> {
setStopButton()
startForegroundService()
startStopwatch { hours, minutes, seconds ->
updateNotification(hours = hours, minutes = minutes, seconds = seconds)
}
}
StopwatchState.Stopped.name -> {
stopStopwatch()
scope.launch {
cancelStopwatch()
}
stopForegroundService()
}
}
intent?.action.let {
when (it) {
ACTION_SERVICE_START -> {
setStopButton()
startForegroundService()
startStopwatch { hours, minutes, seconds ->
updateNotification(hours = hours, minutes = minutes, seconds = seconds)
}
}
ACTION_SERVICE_STOP -> {
stopStopwatch()
scope.launch {
cancelStopwatch()
}
stopForegroundService()
}
}
}
}).start()
return super.onStartCommand(intent, flags, startId)
}
}
< /code>
@Module
@InstallIn(ServiceComponent::class)
// Updates and modifies the notification along the stopwatch
object NotificationModule {
@ServiceScoped
@Provides
fun provideNotificationBuilder(@ApplicationContext context: Context): NotificationCompat.Builder {
val job = SupervisorJob()
val scope = CoroutineScope(Dispatchers.IO + job)
var activitiesRepository = RepositoryActivities(OfflineDatabase.getDatabase(context).activityDao())
var recordedActivity: Activity? = null
scope.launch {
recordedActivity = activitiesRepository.getRecordedActivity().first()
}
return NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setContentTitle(recordedActivity?.title ?: "Activity")
// Default text of the notification
.setContentText("00:00:00")
.setOngoing(true)
.addAction(0, "Stop", ServiceHelper.stopPendingIntent(context))
.setContentIntent(ServiceHelper.clickPendingIntent(context))
}
}
< /code>
@Module
@InstallIn(ServiceComponent::class)
object RepositoryModule {
@ServiceScoped
@Provides
fun provideActivityRepository(@ApplicationContext context: Context): IActivitiesRepository {
return RepositoryActivities(OfflineDatabase.getDatabase(context).activityDao())
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79742650/how-to-properly-inject-and-use-a-repository-in-a-service[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия