Android — How to set the background color for a notification in a foreground service

Cazimir Roman
2 min readSep 17, 2020

--

Recently i was struggling with setting the background color for a notification shown by a foreground service in Android.

Partially set background for my remote view notification

This is what my code looked like:

private fun createNotificationBuilder() {
this.notificationBuilder = NotificationCompat.Builder(this, MyApplication.FOREGROUND_SERVICE_CHANNEL)
.setContentTitle("MyForegroundService")
.setOnlyAlertOnce(true)
.setAutoCancel(false)
.setSmallIcon(R.drawable.ic_notification)
.setStyle(NotificationCompat.DecoratedCustomViewStyle())
.setCustomContentView(notificationView)
.setContentIntent(pendingIntent)
}

I thought that easy enough i would go to my custom remote notification view and change the background on the parent layout there:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="@color/notification_background"
android:layout_height="match_parent"
android:baselineAligned="false">

That did change something but the background color was not applies to the whole notification. I seemed that there was a huge padding applied somewhere else. Then i tried playing around with the styles provided by the NotificationCompat class that provides also media specific styles.

private fun createNotificationBuilder() {
this.notificationBuilder = NotificationCompat.Builder(this, MyApplication.FOREGROUND_SERVICE_CHANNEL)
.setContentTitle("MyForegroundService")
.setOnlyAlertOnce(true)
.setAutoCancel(false)
.setSmallIcon(R.drawable.ic_notification)
.setColor(resources.getColor(R.color.colorPrimary))
.setColorized(true)

.setStyle(androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle())
.setCustomContentView(notificationView)
.setContentIntent(pendingIntent)
}

Finally i figured out that in order to have the background set to the whole notification i have to chain the following method calls to the NotificationCompat.Builder:

  • call setColor -> the color to be used on the background
  • call setColorized -> the actual call to set the background color
  • set style to NotificationCompat.DecoratedMediaCustomViewStyle()

Problem solved:

I hope this short tutorial was usefull to you and I will see you in my next post.

Happy coding :)

--

--

Cazimir Roman
Cazimir Roman

Written by Cazimir Roman

A curious developer with a passion for learning and creating innovative solutions to complex problems.

Responses (3)