Open In App

Create an Expandable Notification Containing a Picture in Android

Last Updated : 01 Sep, 2020
Improve
Improve
Like Article
Like
Save
Share
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 a picture.

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 a picture.

activity_main.xml




<?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>


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.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.widget.Button
import 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”.

Output: Run on Emulator



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads