Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android worker with foreground service does not show notifications

I'm following this documentation to create a long-time worker running a foreground service, but no notification is shown.

The worker run, i see the logs.

The code:

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)
}
like image 540
blow Avatar asked Oct 17 '25 02:10

blow


1 Answers

The problem is that the doWork function lasted too short, not long enough to see the notification.

like image 117
blow Avatar answered Oct 18 '25 16:10

blow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!