具有前台服务的 Android worker 不显示通知

标签 android android-notifications android-workmanager

我正在关注 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)
}

最佳答案

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

关于具有前台服务的 Android worker 不显示通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67615961/

相关文章:

android - 在 Chrome 自定义选项卡中检测到内存泄漏

Android - 签名 APK - Gradle 执行失败

android解析,如何找到其他用户名?

android - 当我在 android 5.0 中生成通知时,通知状态图标变为白色

android - 如何使用 pendingIntent Kotlin 从 Activity 传递到 BroadcastReceiver()

Android 工作管理器 : How to enqueue Jobs once a month

android - NetworkOnMainThreadException 是否对协程中的网络调用有效?

java - 无法启用奥利奥通知的闪烁灯并禁用通知声音

java - AlarmManager 在 Oreo 中安排长时间任务的替代方案是什么?

android - 在 Android 中为定期工作管理器设置初始延迟