Create an Expandable Notification Containing Some Text in Android
Notification is a type of message that is generated by any application present inside the mobile phone, suggesting to check the application and this could be anything from an update (Low priority notification) to something that’s not going right in the application (High priority notification). A basic notification consists of a title, a line of text, and one or more actions the user can perform in response. To provide even more information, one can also create large, expandable notifications by applying one of several notification templates as described in this article. Some daily life examples could be the notifications appended by Whatsapp, Gmail, SMS, etc in the notification drawer, where the user can expand it and can find some details about the message received such as sender name, subject and some part of the text in case of Gmail. In this article let’s create a notification inside an application that contains some text.
Step 1: Create a new project
To create a new project in android studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Modify activity_main.xml file
Inside the XML file just add a button, which on click would build an expandable notification. By expanding the notification from the notification drawer would display some text.
Step 3: Modify MainActivity file
Now, look at the code below which is in Kotlin. To start, build a notification with all the basic content as described in Create a Notification. Then, call setStyle() with a style object and supply information corresponding to each template, as shown below.
Note: If you have previously searched for the code for expandable notifications, then you must have seen this particular line of code:
As “NotificationCompat” is currently deprecated and your code would always crash whenever an attempt is made to build a notification (on button click in our case). Instead, just use “Notification”.