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.

expandable notification

Approach

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.

activity_main.xml

filter_none

edit
close

play_arrow

link
brightness_4
code

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="click"
        android:layout_centerInParent="true"/>
  
</RelativeLayout>

chevron_right


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.

MainActivity.kt

filter_none

edit
close

play_arrow

link
brightness_4
code

package com.example.expandable_notification_bigtext
  
import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationManagerCompat
  
class MainActivity : AppCompatActivity() {
  
    // Assigning variables to Notification Manager, Channel and Builder
    lateinit var notifManager : NotificationManager
    lateinit var notifChannel : NotificationChannel
    lateinit var notifBuilder : Notification.Builder
      
    // Evaluating ChannelID and Description for the Custom Notification
    private val description = "Some Description"
    private val channelID = "Some Channel ID"
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // Declaring the button which onclick generates a notification
        val btn = findViewById<Button>(R.id.btn)
  
        // Notification Service for the Manager
        notifManager = getSystemService(Context.NOTIFICATION_SERVICE) 
        as NotificationManager
  
        // Notifications are in the form of Intents
        val someintent = Intent(this,LauncherActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(this,0,someintent,
        PendingIntent.FLAG_UPDATE_CURRENT)
  
        // Idea is to click the button and the notification appears
        btn.setOnClickListener {
          
        // Declaring a message (string) to be displayed 
        // in the notification
        val message = "Some random text for testing purpose" +
                      "Some day you will be" +
                         "reading this" +
                      "and by the time, it'll be too late" +
                      "to confess everything."
          
            // If Min. API level of the phone is 26, then notification could be 
            // made asthetic
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                notifChannel = NotificationChannel(channelID,description,
                NotificationManager.IMPORTANCE_HIGH)
                notifChannel.enableLights(true)
                notifChannel.lightColor = Color.RED
                notifChannel.enableVibration(true)
  
                notifManager.createNotificationChannel(notifChannel)
  
                notifBuilder = Notification.Builder(this,channelID)
                        .setContentTitle("Some Title")
                        .setContentText("Some Content Text")
                        .setSmallIcon(R.mipmap.ic_launcher_round)
                          
                        // Command to Insert a message in the Notification
                        .setStyle(Notification.BigTextStyle()// <-- Look here
                        .bigText(message))// <---- Look here
                          
                          
                        .setContentIntent(pendingIntent)
            }
            // Else the Android device would give out default UI attributes
            else{
                notifBuilder = Notification.Builder(this)
                        .setContentTitle("Some Title")
                        .setContentText("Some Content Text")
                        .setContentIntent(pendingIntent)
            }
              
            // Everything is done now and the Manager is to be notified about 
            // the Builder which built a Notification for the application
            notifManager.notify(1234,notifBuilder.build())
        }
    }
}

chevron_right


Note: If you have previously searched for the code for expandable notifications, then you must have seen this particular line of code:

“.setStyle(NotificationCompat.BigTextStyle().bigText(message)”

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”.

Output: Run on Emulator




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.