【发布时间】:2020-05-04 12:21:24
【问题描述】:
我需要在应用关闭时创建通知,我尝试执行以下方法:
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)
调用 onCreate 的主要活动 sendBroadcast(Intent(this,NotificationsStartReceiver::class.java))
应用:
class News : Application(), Configuration.Provider {
override fun getWorkManagerConfiguration() =
Configuration.Builder()
.setMinimumLoggingLevel(android.util.Log.INFO)
.build()
}
我在 Manifest 中创建了接收者和提供者:
<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!
【问题讨论】:
标签: android android-notifications android-workmanager