Create an Expandable Notification Containing a Picture in Android - GeeksforGeeks

01 Sep, 2020
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 a picture.
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 a picture.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    xmlns:app="http://schemas.android.com/apk/res-auto"    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>
Step 3: Modify the 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
package com.example.expandablenotification  import android.app.*import android.content.Contextimport android.content.Intentimport android.graphics.BitmapFactoryimport android.graphics.Colorimport android.os.Buildimport android.os.Bundleimport android.widget.Buttonimport androidx.appcompat.app.AppCompatActivity  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 {            // This is how an Image to be displayed in our Notification            // is decoded and stored in a variable. I've added a picture            // named "download.jpeg" in the "Drawables".            val myBitmap = BitmapFactory.decodeResource(resources,                                                         R.drawable.download)              // 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 Image in the Notification                    .setStyle(                        Notification.BigPictureStyle() // <---- Look here                            .bigPicture(myBitmap)                    ) // <---- 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())        }    }}
Note: If you have previously searched for the code for expandable notifications, then you must have seen this particular line of code:
 “.setStyle(NotificationCompat.BigPictureStyle().bigPicture(myBitmap)”
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”.
android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android Project folder Structure
Broadcast Receiver in Android With Example
Different Ways to Change the Project Name in Android Studio
Fix “SDK tools directory is missing” Error in Android Studio
How to Retrieve Data from the Firebase Realtime Database in Android?
Android UI Layouts
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Kotlin Hashmap
How to Change the Color of Status Bar in an Android App?