Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java
  • Android
  • Kotlin
  • Flutter
  • Dart
  • Android with Java
  • Android Studio
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
Create an Expandable Notification Containing Some Text in Android
Next article icon

Create an Expandable Notification Containing Some Text in Android

Last Updated : 04 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Step By Step Implementation

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:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout      xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:id="@+id/main"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:background="@color/white"     tools:context=".MainActivity">      <!-- Button for sending notification-->     <Button         android:id="@+id/button"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="30dp"         android:backgroundTint="@color/green"         android:text="Send Notification"         android:textSize="24sp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" />  </androidx.constraintlayout.widget.ConstraintLayout> 


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 File:

MainActivity.java
package com.gfg.expandable_notification;   import android.Manifest; import android.annotation.SuppressLint; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat;  public class MainActivity extends AppCompatActivity {      private Button button;     private static final String CHANNEL_ID = "i.apps.notifications";     private static final int NOTIFICATION_ID = 1234;     private static final String CHANNEL_NAME = "Test notification";     private static final int REQUEST_CODE_POST_NOTIFICATIONS = 101;      @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          button = findViewById(R.id.button);          // Create a notification channel (required for Android 8.0 and higher)         createNotificationChannel();          button.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                                // Request runtime permission for notifications on Android 13 and higher                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)                  {                     if (ActivityCompat.checkSelfPermission( MainActivity.this,                             Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED) {                                                	ActivityCompat.requestPermissions(MainActivity.this,                                 new String[]{Manifest.permission.POST_NOTIFICATIONS},                                 REQUEST_CODE_POST_NOTIFICATIONS                         );                                                return;                     }                 }                 sendNotification(); // Trigger the notification             }         });     }      /**      * Create a notification channel for devices running Android 8.0 or higher.      * A channel groups notifications with similar behavior.      */     private void createNotificationChannel() {         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {             NotificationChannel notificationChannel =                		new NotificationChannel(CHANNEL_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH);                        	// Turn on notification light           	notificationChannel.enableLights(true);              notificationChannel.setLightColor(Color.GREEN);                      	// Allow vibration for notifications             notificationChannel.enableVibration(true);               NotificationManager notificationManager =                			(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);             notificationManager.createNotificationChannel(notificationChannel);         }     }      /**      * Build and send a notification with a custom layout and action.      */     @SuppressLint("MissingPermission")     private void sendNotification() {         // Build the notification         NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)                 .setSmallIcon(R.drawable.gfg_logo) // Notification icon                 .setContentTitle("GeeksforGeeks") // Title displayed in the notification                 .setContentText("Expand to know more") // Text displayed in the notification                 .setAutoCancel(true) // Dismiss notification when tapped                 .setPriority(NotificationCompat.PRIORITY_DEFAULT) // Notification priority for better visibility                 .setStyle(new NotificationCompat.BigTextStyle()                         .bigText(getString(R.string.gfg_text)));          // Display the notification         NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);         notificationManager.notify(NOTIFICATION_ID, builder.build());     } } 
MainActivity.kt
package org.geeksforgeeks.demo  import android.Manifest import android.annotation.SuppressLint import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.pm.PackageManager import android.graphics.Color import android.os.Build import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat  class MainActivity : AppCompatActivity() {        	private lateinit var button: Button        override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          button = findViewById(R.id.button)          // Create a notification channel (required for Android 8.0 and higher)         createNotificationChannel()          button.setOnClickListener {             // Request runtime permission for notifications on Android 13 and higher             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {                 if (ActivityCompat.checkSelfPermission( this                     , Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED)                {                     ActivityCompat.requestPermissions(this,arrayOf(Manifest.permission.POST_NOTIFICATIONS), 101)                     return@setOnClickListener                 }             }             sendNotification() // Trigger the notification         }     }      /**      * Create a notification channel for devices running Android 8.0 or higher.      * A channel groups notifications with similar behavior.      */     private fun createNotificationChannel() {         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {             val notificationChannel = NotificationChannel(                 CHANNEL_ID,                 CHANNEL_NAME,                 NotificationManager.IMPORTANCE_HIGH             ).apply {               	// Turn on notification light                 enableLights(true)                                   lightColor = Color.GREEN                              	// Allow vibration for notifications                 enableVibration(true)              }              val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager             notificationManager.createNotificationChannel(notificationChannel)         }     }      /**      * Build and send a notification with a custom layout and action.      */     @SuppressLint("MissingPermission")     private fun sendNotification() {         // Build the notification         val builder = NotificationCompat.Builder(this, CHANNEL_ID)             .setSmallIcon(R.drawable.gfg_logo) // Notification icon             .setContentTitle("GeeksforGeeks") // Title displayed in the notification             .setContentText("Expand to know more") // Text displayed in the notification             .setAutoCancel(true) // Dismiss notification when tapped             .setPriority(NotificationCompat.PRIORITY_DEFAULT) // Notification priority for better visibility             .setStyle(                 NotificationCompat.BigTextStyle()                     .bigText(getString(R.string.gfg_text))             )          // Display the notification         with(NotificationManagerCompat.from(this)) {             notify(NOTIFICATION_ID, builder.build())         }     }      companion object {       	// Unique channel ID for notifications         const val CHANNEL_ID = "i.apps.notifications"              	// Unique identifier for the notification         const val NOTIFICATION_ID = 1234               	// Description for the notification channel         const val CHANNEL_NAME = "Test notification"       } } 

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:


Next Article
Create an Expandable Notification Containing Some Text in Android

A

aashaypawar
Improve
Article Tags :
  • Web Technologies
  • Kotlin
  • Android
  • Kotlin Android
  • Java-Android

Similar Reads

    Create an Expandable Notification Containing a Picture 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 bas
    5 min read
    Notifications in Android with Example
    Notification is a kind of message, alert, or status of an application (probably running in the background) that is visible or available in the Android's UI elements. This application could be running in the background but not in use by the user. The purpose of a notification is to notify the user ab
    7 min read
    How to Implement Notification Counter in Android?
    Notification Counter basically counts the notifications that you got through an application and shows on the top of your application icon so that you get to know you get new messages or any new update without opening your application or specific feature like the message button in Instagram. Notifica
    7 min read
    How to Enable Notification Runtime Permission in Android 13?
    Android 13 starts a new realm of new app permissions which are focussed on users' privacy and peace of mind, one of which is the permission to send notifications to the user. Notifications are an integral part of the Android Operating System, but when you have tons of apps installed, then receiving
    5 min read
    Create an Instagram/Twitter Heart Like Animation in Android
    In this article, let's learn how to create an Instagram/Twitter heart Like animation in android. Twitter's Like animation is quite good and attractive. Suppose one wants to make an app like Twitter, Instagram, or Facebook where users can like posts there one can use this view. One can also use Leoni
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences