Мне нужно создавать уведомления, когда приложение закрыто, я пытаюсь выполнить следующий метод:
NotificationWorker:
class NotificationWorker(context: Context, params: WorkerParameters) :
CoroutineWorker(context, params) {
private lateinit var notificationManager: NotificationManager
override suspend fun doWork(): Result {
initNotifications()
notificationManager.notify(0, createNotification())
return Result.success()
}
private fun initNotifications() {
notificationManager = getSystemService(
applicationContext,
NotificationManager::class.java
) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val importance = NotificationManager.IMPORTANCE_LOW
val channel =
NotificationChannel(NOTIFICATION_CHANNEL, NOTIFICATION_CHANNEL, importance)
notificationManager.createNotificationChannel(channel)
}
}
private fun createNotification(): Notification {
val builder = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
Notification.Builder(applicationContext) else
Notification.Builder(applicationContext, NOTIFICATION_CHANNEL)
builder.apply {
setContentTitle("Current time")
setContentText("${Calendar.getInstance()}")
setSmallIcon(R.drawable.ic_launcher_foreground)
}
return builder.build()
}
companion object {
private const val NOTIFICATION_CHANNEL = "syncended.news"
private fun getWorkerRequest(): PeriodicWorkRequest =
PeriodicWorkRequestBuilder<NotificationWorker>(15, TimeUnit.MINUTES).build()
fun enqueueSelf(context: Context) {
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
NotificationWorker::class.java.name,
ExistingPeriodicWorkPolicy.KEEP,
getWorkerRequest()
)
}
}
}
При получении вызова NotificationWorker.enqueueSelf(context)
Main вызов активности в onCreate sendBroadcast(Intent(this,NotificationsStartReceiver::class.java))
Приложение:
class News : Application(), Configuration.Provider {
override fun getWorkManagerConfiguration() =
Configuration.Builder()
.setMinimumLoggingLevel(android.util.Log.INFO)
.build()
}
Я создал приемник и провайдер в манифесте:
<provider
android:name="androidx.work.impl.WorkManagerInitializer"
android:authorities="${applicationId}.workmanager-init"
android:exported="false"
tools:node="remove" />
<receiver
android:name=".notifications.NotificationsStartReceiver"
android:process=":newsBgNotify" />
Когда приложение работает, все в порядке, но когда я закрыл приложение (в диспетчере задач), я получил следующее, и уведомления не показывались
2020-05-04 15:06:26.678 2046-2159/system_process W/InputDispatcher: channel '68c8279 ru.syncended.news/ru.syncended.news.main.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
2020-05-04 15:06:26.679 2046-2159/system_process E/InputDispatcher: channel '68c8279 ru.syncended.news/ru.syncended.news.main.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!