【问题标题】:Android worker with foreground service does not show notifications具有前台服务的 Android 工作者不显示通知
【发布时间】:2021-05-20 07:37:20
【问题描述】:

我正在关注this documentation 创建一个运行前台服务的长期工作人员,但没有显示任何通知。

工人跑了,我看到了日志。

代码:

override suspend fun doWork(): Result {
    Log.d(TAG, "Worker start")
    setForeground(createForegroundInfo("Hello from my notification"))
    Log.d(TAG, "Worker end")
    return Result.success()
}

private fun createForegroundInfo(progress: String): ForegroundInfo {
    val channelId = applicationContext.getString(R.string.notification_channel_id)
    val title = applicationContext.getString(R.string.notification_title)
    // This PendingIntent can be used to cancel the worker
    val intent = WorkManager.getInstance(applicationContext)
        .createCancelPendingIntent(getId())

    // Create a Notification channel if necessary
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createChannel()
    }

    val notification = NotificationCompat.Builder(applicationContext, channelId)
        .setContentTitle(title)
        .setTicker(title)
        .setContentText(progress)
        .setSmallIcon(R.drawable.ic_notifications_black_24dp)
        .setOngoing(true)
        .build()

    return ForegroundInfo(1, notification)
}

@RequiresApi(Build.VERSION_CODES.O)
private fun createChannel() {
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    val name = applicationContext.getString(R.string.notification_channel_name)
    val descriptionText = applicationContext.getString(R.string.notification_channel_description)
    val importance = NotificationManager.IMPORTANCE_DEFAULT
    val channelId = applicationContext.getString(R.string.notification_channel_id)
    val channel = NotificationChannel(channelId, name, importance).apply {
        description = descriptionText
    }
    // Register the channel with the system
    val notificationManager: NotificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    notificationManager.createNotificationChannel(channel)
}

【问题讨论】:

  • 要显示通知,请调用 NotificationManagerCompat.notify()-> developer.android.com/training/notify-user/…
  • 在 Worker 文档中没有提到使用管理器显示通知,我希望函数 setForeground 显示它。我引用文档:Calls setForegroundAsync(createForegroundInfo(myProgress)) periodically when it needs to update the ongoing Notification.

标签: android android-notifications android-workmanager


【解决方案1】:

问题是doWork 函数持续时间太短,不足以看到通知。

【讨论】:

    猜你喜欢
    • 2017-11-23
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 2017-11-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 2017-10-24
    相关资源
    最近更新 更多