android embed newline in a notification

You do not need to use RemoteViews or a custom layout to show multiple lines, despite what others have said here! Multiline texts are possible, but only when the notification is expanded.

To do this, you can use NotificationCompat.BigTextStyle. And if you read the dev guides here then you'll notice that they mention this tip:

Tip: To add formatting in your text (bold, italic, line breaks, and so on), you can add styling with HTML markup.

So, in other words:

val title = "My Title"
val body = "Line 1<br>Line 2<br><i>Italic Line 3</i>"
val formattedBody = SpannableString(
   if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) Html.fromHtml(body)
   else Html.fromHtml(body, Html.FROM_HTML_MODE_LEGACY)
)

NotificationCompat.Builder(context, channelId)
   .setColor(ContextCompat.getColor(context, R.color.colorPrimary))
   .setContentTitle(title)
   .setContentText(formattedBody)
   .setStyle(NotificationCompat.BigTextStyle().bigText(formattedBody).setBigContentTitle(title))
   .setSmallIcon(R.drawable.ic_small_notification_icon)
   .build()

Things to note about how this works:

  1. The title can have no formatting (i.e. don't try to use HTML here)
  2. The body can have as much formatting as we want, but we must note that the line breaks won’t display when the notification is collapsed. All other HTML formatting works fine in both collapsed/expanded states. You can bold, italicize, etc. as much as you want (I think)

If you don't want to send HTML formatting in your push notification, then another option is to use markdown formatting of some sort and manually handle this before your notification building by using SpannableStringBuilder


As far as I know there is no way to do this other than creating a custom Notification layout. The Notification documentation has a step-by-step process on doing this and is quite thorough. Here is the link to that.

Creating the two lines as you require would just mean putting in an extra TextView in the layout XML. Then you would just set each TextView's text to your two lines of data, as the example shows.