How to create a notification with NotificationCompat.Builder?
Asked Answered
I

9

61

I need to create a simple notification which will be shown in notification bar along with the sound and icon if possible? I also need it to be compatitible with Android 2.2, so i found that NotificationCompat.Builder works with all APIs above 4. If there's a better solution, feel free to mention it.

Islaen answered 16/12, 2012 at 14:15 Comment(0)
H
138

The NotificationCompat.Builder is the most easy way to create Notifications on all Android versions. You can even use features that are available with Android 4.1. If your app runs on devices with Android >=4.1 the new features will be used, if run on Android <4.1 the notification will be an simple old notification.

To create a simple Notification just do (see Android API Guide on Notifications):

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!")
    .setContentIntent(pendingIntent); //Required on Gingerbread and below

You have to set at least smallIcon, contentTitle and contentText. If you miss one the Notification will not show.

Beware: On Gingerbread and below you have to set the content intent, otherwise a IllegalArgumentException will be thrown.

To create an intent that does nothing, use:

final Intent emptyIntent = new Intent();
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, NOT_USED, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

You can add sound through the builder, i.e. a sound from the RingtoneManager:

mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))

The Notification is added to the bar through the NotificationManager:

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(mId, mBuilder.build());
Hoyden answered 16/12, 2012 at 14:36 Comment(9)
Will it automatically show in notification bar? And how do i add sound?Islaen
the problem is with this NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(mId, mBuilder.build());Islaen
It's an ID for the notification so that you can reference it later to dismiss or replace it.Hoyden
Please add the info from here : #20032749 in your answer - in short the way you give it it will crash pre-ICS - it needs the contentIntent. Let me know to remove the commentMindful
Thank you for You have to set at least smallIcon, contentTitle and contentText. If you miss one the Notification will not show. That line solved my headache. Didn't realize you HAD to set all of those.Reneta
There is a small icon inside the push notification but not status bar. Is there any way to hide it?Tellurize
I have a problem i set the icon have green colour but when notification appear it changes to white automatically.Liveryman
@HUSNAINSARWAR See this answer regarding your white icon: https://mcmap.net/q/88556/-notification-bar-icon-turns-white-in-android-5-lollipopHoyden
This will not work when you want to show it at android 8 and when the app is openedLuht
O
30

Working example:

    Intent intent = new Intent(ctx, HomeActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder b = new NotificationCompat.Builder(ctx);

    b.setAutoCancel(true)
     .setDefaults(Notification.DEFAULT_ALL)
     .setWhen(System.currentTimeMillis())         
     .setSmallIcon(R.drawable.ic_launcher)
     .setTicker("Hearty365")            
     .setContentTitle("Default notification")
     .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
     .setDefaults(Notification.DEFAULT_LIGHTS| Notification.DEFAULT_SOUND)
     .setContentIntent(contentIntent)
     .setContentInfo("Info");


    NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(1, b.build());
Organism answered 31/12, 2014 at 13:30 Comment(5)
Hi, I've tried this code but I don't have any references to NotificationCompat.Builder... is it something missing?Modlin
Check to make sure you included the android support-v4 compatibility library. You might also try to clean and rebuild your project.Cicely
I have a problem i set the icon have green colour but when notification appear it changes to white automatically.Liveryman
@HUSNAINSARWAR because that happens on the API >21 (Lollipop and above). To resolve that please specify an icon for setSmallIcon(R.id.your_icon_small) and set a main icon like this mBuilder.setLargeIcon(BitmapFactory .decodeResource(context.getResources(), R.drawable.icon)) for API >21.Hereto
This will not work when you want to show it at android 8 and when the app is openedLuht
W
11

Show Notificaton in android 8.0

@TargetApi(Build.VERSION_CODES.O)
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)

  public void show_Notification(){

    Intent intent=new Intent(getApplicationContext(),MainActivity.class);
    String CHANNEL_ID="MYCHANNEL";
    NotificationChannel notificationChannel=new NotificationChannel(CHANNEL_ID,"name",NotificationManager.IMPORTANCE_LOW);
    PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(),1,intent,0);
    Notification notification=new Notification.Builder(getApplicationContext(),CHANNEL_ID)
            .setContentText("Heading")
            .setContentTitle("subheading")
            .setContentIntent(pendingIntent)
            .addAction(android.R.drawable.sym_action_chat,"Title",pendingIntent)
            .setChannelId(CHANNEL_ID)
            .setSmallIcon(android.R.drawable.sym_action_chat)
            .build();

    NotificationManager notificationManager=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.createNotificationChannel(notificationChannel);
    notificationManager.notify(1,notification);


}
While answered 30/1, 2019 at 18:13 Comment(1)
In newer versions, .addAction gets PendingIntent as a single parameter, so we can build it in a different method.Timecard
H
8

I make this method and work fine. (tested in android 6.0.1)

public void notifyThis(String title, String message) {
    NotificationCompat.Builder b = new NotificationCompat.Builder(this.context);
    b.setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.favicon32)
            .setTicker("{your tiny message}")
            .setContentTitle(title)
            .setContentText(message)
            .setContentInfo("INFO");

    NotificationManager nm = (NotificationManager) this.context.getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(1, b.build());
}
Hair answered 8/2, 2017 at 20:33 Comment(1)
new NotificationCompat.Builder(ctx); is deprecatedSchwartz
N
2

Notification in depth

CODE

Intent intent = new Intent(this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,0);

NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.your_notification_icon)
                        .setContentTitle("Notification Title")
                        .setContentText("Notification ")
                        .setContentIntent(pendingIntent );

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, mBuilder.build());

Depth knowledge

Notification can be build using Notification. Builder or NotificationCompat.Builder classes.
But if you want backward compatibility you should use NotificationCompat.Builder class as it is part of v4 Support library as it takes care of heavy lifting for providing consistent look and functionalities of Notification for API 4 and above.

Core Notification Properties

A notification has 4 core properties (3 Basic display properties + 1 click action property)

  • Small icon
  • Title
  • Text
  • Button click event (Click event when you tap the notification )

Button click event is made optional on Android 3.0 and above. It means that you can build your notification using only display properties if your minSdk targets Android 3.0 or above. But if you want your notification to run on older devices than Android 3.0 then you must provide Click event otherwise you will see IllegalArgumentException.

Notification Display

Notification are displayed by calling notify() method of NotificationManger class

notify() parameters

There are two variants available for notify method

notify(String tag, int id, Notification notification)

or

notify(int id, Notification notification)

notify method takes an integer id to uniquely identify your notification. However, you can also provide an optional String tag for further identification of your notification in case of conflict.

This type of conflict is rare but say, you have created some library and other developers are using your library. Now they create their own notification and somehow your notification and other dev's notification id is same then you will face conflict.

Notification after API 11 (More control)

API 11 provides additional control on Notification behavior

  • Notification Dismissal
    By default, if a user taps on notification then it performs the assigned click event but it does not clear away the notification. If you want your notification to get cleared when then you should add this

    mBuilder.setAutoClear(true);

  • Prevent user from dismissing notification
    A user may also dismiss the notification by swiping it. You can disable this default behavior by adding this while building your notification

    mBuilder.setOngoing(true);

  • Positioning of notification
    You can set the relative priority to your notification by

    mBuilder.setOngoing(int pri);

If your app runs on lower API than 11 then your notification will work without above mentioned additional features. This is the advantage to choosing NotificationCompat.Builder over Notification.Builder

Notification after API 16 (More informative)

With the introduction of API 16, notifications were given so many new features
Notification can be so much more informative.
You can add a bigPicture to your logo. Say you get a message from a person now with the mBuilder.setLargeIcon(Bitmap bitmap) you can show that person's photo. So in the statusbar you will see the icon when you scroll you will see the person photo in place of the icon. There are other features too

  • Add a counter in the notification
  • Ticker message when you see the notification for the first time
  • Expandable notification
  • Multiline notification and so on
Nicholson answered 9/3, 2018 at 4:51 Comment(0)
P
1

You can try this code this works fine for me:

    NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this);

    Intent i = new Intent(noti.this, Xyz_activtiy.class);
    PendingIntent pendingIntent= PendingIntent.getActivity(this,0,i,0);

    mBuilder.setAutoCancel(true);
    mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
    mBuilder.setWhen(20000);
    mBuilder.setTicker("Ticker");
    mBuilder.setContentInfo("Info");
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setSmallIcon(R.drawable.home);
    mBuilder.setContentTitle("New notification title");
    mBuilder.setContentText("Notification text");
    mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

    NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(2,mBuilder.build());
Perishable answered 14/5, 2017 at 6:32 Comment(0)
N
1

simple way for make notifications

 NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher) //icon
            .setContentTitle("Test") //tittle
            .setAutoCancel(true)//swipe for delete
            .setContentText("Hello Hello"); //content
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(1, builder.build()
    );
Nessa answered 31/5, 2018 at 23:6 Comment(0)
G
1

Application Class here Code in below

public class App extends Application {
public static final String CHANNEL_1="CHANNEL1";
@Override
public void onCreate() {
    super.onCreate();
    createNotificationChannel();
}

private void createNotificationChannel() {
    NotificationChannel channel=new NotificationChannel(CHANNEL_1,"Channel 1", NotificationManager.IMPORTANCE_HIGH);
    channel.setDescription("This is Channel 1");

    NotificationManager  notificationManager=getSystemService(NotificationManager.class);
    notificationManager.createNotificationChannel(channel);
}

}

Create the Activity show Notification Below Code

 NotificationManagerCompat notificationManagerCompat;

    notificationManagerCompat = NotificationManagerCompat.from(this);

    binding.btnNotification.setOnClickListener(v -> {
        Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_1)
                .setSmallIcon(R.drawable.ic_black_24)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setContentText("Message")
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                .build();
        notificationManagerCompat.notify(1, notification);
    });
Gesso answered 6/9, 2022 at 6:2 Comment(0)
R
0

Use this code

            Intent intent = new Intent(getApplicationContext(), SomeActvity.class);
            PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                    (int) System.currentTimeMillis(), intent, 0);

            NotificationCompat.Builder mBuilder =
                    new NotificationCompat.Builder(getApplicationContext())
                            .setSmallIcon(R.drawable.your_notification_icon)
                            .setContentTitle("Notification title")
                            .setContentText("Notification message!")
                            .setContentIntent(pIntent);

            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, mBuilder.build());
Radmen answered 17/7, 2017 at 12:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.