繁体   English   中英

具有前台服务的 Android 工作人员不显示通知

[英]Android worker with foreground service does not show notifications

我正在按照此文档创建一个运行前台服务的长期工作人员,但未显示任何通知。

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

编码:

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 function 持续时间太短,不足以看到通知。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM