How exactly to use Notification.Builder
Asked Answered
S

11

105

I found that I am using a deprecated method for noficitations (notification.setLatestEventInfo())

It says to use Notification.Builder.

  • How do I use it?

When I try to create a new instance, it tells me:

Notification.Builder cannot be resolved to a type
Suzansuzann answered 17/6, 2011 at 21:8 Comment(2)
I noticed that this works from API Level 11 (Android 3.0).Oneill
Please check upadated answer belowFascism
P
86

This is in API 11, so if you are developing for anything earlier than 3.0 you should continue to use the old API.

Update: the NotificationCompat.Builder class has been added to the Support Package so we can use this to support API level v4 and up:

http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html

Preach answered 17/6, 2011 at 21:35 Comment(2)
Thanks. I wonder why it doesn't mention that on the function pages themselvesSuzansuzann
Yeah: the deprecation warning is a bit premature in my opinion, but what do I know.Preach
G
152

Notification.Builder API 11 or NotificationCompat.Builder API 1

This is a usage example.

Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
        YOUR_PI_REQ_CODE, notificationIntent,
        PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) ctx
        .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);

builder.setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.some_img)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
            .setTicker(res.getString(R.string.your_ticker))
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle(res.getString(R.string.your_notif_title))
            .setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();

nm.notify(YOUR_NOTIF_ID, n);
Gasiform answered 15/1, 2012 at 12:35 Comment(12)
I see there is a technique to do this in the v4 support package: NotificationCompat.BuilderCariotta
I think someone should tell Google that they have serious typos in the Notification.Builder docs page. I was doing what they were saying but it wasn't making any sense. I come here and see it is different. I really appreciate your answer as it made me a aware of the mistake thats on the doc.Tipstaff
The documentation says builder.getNotification() is deprecated. It says you should use builder.build().Leisurely
Fixed the references to the different api versions. And took out the fluff and fixed the deprecated stuff.Haemoid
NotificationBuilder.build() requires API Level 16 or higher. Anything between API Level 11 & 15 you should use NotificationBuilder.getNotification().Rasp
@CamilleSévigny Should we use NotificationBuilder.getNotification() instead of NotificationBuilder.build() even with supportPackage?Jarnagin
@Mr.Hyde Had to do that. No idea why that isn't documented.Shawnna
it's important to note that if you don't call setSmallIcon() before calling build() on the noficationBuilder that it will not work.Sore
@MrTristan: As written in the documentation, setSmallIcon(), setContentTitle() and setContentText() are the minimum requirements.Vicinage
@MarcoW: not everyone reads the docs, a lot of lazy people just read highly voted answers like this one :-)Sore
Google's docs are where Microsoft's .Net docs were 8 years ago. Microsoft made huge improvements to their docs when they added a link at the bottom of each page for feedback. Google doesn't give an opportunity for feedback on their doc's.Boardinghouse
how to set tags? notification.flags in targetsdk <6.0Impetuous
P
86

This is in API 11, so if you are developing for anything earlier than 3.0 you should continue to use the old API.

Update: the NotificationCompat.Builder class has been added to the Support Package so we can use this to support API level v4 and up:

http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html

Preach answered 17/6, 2011 at 21:35 Comment(2)
Thanks. I wonder why it doesn't mention that on the function pages themselvesSuzansuzann
Yeah: the deprecation warning is a bit premature in my opinion, but what do I know.Preach
S
70

in addition to the selected answer here is some sample code for the NotificationCompat.Builder class from Source Tricks :

// Add app running notification  

    private void addNotification() {



    NotificationCompat.Builder builder =  
            new NotificationCompat.Builder(this)  
            .setSmallIcon(R.drawable.ic_launcher)  
            .setContentTitle("Notifications Example")  
            .setContentText("This is a test notification");  

    Intent notificationIntent = new Intent(this, MainActivity.class);  
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
            PendingIntent.FLAG_UPDATE_CURRENT);  
    builder.setContentIntent(contentIntent);  

    // Add as notification  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.notify(FM_NOTIFICATION_ID, builder.build());  
}  

// Remove notification  
private void removeNotification() {  
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
    manager.cancel(FM_NOTIFICATION_ID);  
}  
Shape answered 4/1, 2013 at 4:9 Comment(3)
First code using the new Compat builder that has actually worked. Well done!Shakedown
Worked well for me too. Two notes: 1) you'll need to make a 32x32 icon for the "ic_launcher". White drawing on transparent background 2) you'll need to define some random number for int FM_NOTIFICATION_ID = [yourFavoriteRandom];Olszewski
thank you so much, My problem was: when i clicked on notification 2nd time, previous fragment was open , and this line " PendingIntent.FLAG_UPDATE_CURRENT " solved my problem, and made my dayBollinger
S
4

Notification Builder is strictly for Android API Level 11 and above (Android 3.0 and up).

Hence, if you are not targeting Honeycomb tablets, you should not be using the Notification Builder but rather follow older notification creation methods like the following example.

Sick answered 18/6, 2011 at 1:5 Comment(1)
You can use the Compatability Library, so you can use it on API 4 or higher.Laurin
F
3

UPDATE android-N (march-2016)

Please visit Notifications Updates link for more details.

  • Direct Reply
  • Bundled Notifications
  • Custom Views

Android N also allows you to bundle similar notifications to appear as a single notification. To make this possible, Android N uses the existing NotificationCompat.Builder.setGroup() method. Users can expand each of the notifications, and perform actions such as reply and dismiss on each of the notifications, individually from the notification shade.

This is a pre-existing sample which shows a simple service that sends notifications using NotificationCompat. Each unread conversation from a user is sent as a distinct notification.

This sample has been updated to take advantage of new notification features available in Android N.

sample code.

Fascism answered 10/3, 2016 at 10:12 Comment(1)
hi there, can you tell how to have this method work Android 6.0 when we are using downloader_library. I am on Eclipse SDK - 25.1.7 || ADT 23.0.X sadly || Google APK Expansion Library and Licensing Library both 1.0Sihun
P
2

I was having a problem building notifications (only developing for Android 4.0+). This link showed me exactly what I was doing wrong and says the following:

Required notification contents

A Notification object must contain the following:

A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()

Basically I was missing one of these. Just as a basis for troubleshooting with this, make sure you have all of these at the very least. Hopefully this will save someone else a headache.

Pertinacious answered 1/9, 2014 at 2:37 Comment(1)
So if you think: "i'll find an icon later", you won't get any notify-love. Thanks for this one ;)Phallicism
R
2

It works even in API 8 you can use this code:

 Notification n = 
   new Notification(R.drawable.yourownpicturehere, getString(R.string.noticeMe), 
System.currentTimeMillis());

PendingIntent i=PendingIntent.getActivity(this, 0,
             new Intent(this, NotifyActivity.class),
                               0);
n.setLatestEventInfo(getApplicationContext(), getString(R.string.title), getString(R.string.message), i);
n.number=++count;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.flags |= Notification.DEFAULT_SOUND;
n.flags |= Notification.DEFAULT_VIBRATE;
n.ledARGB = 0xff0000ff;
n.flags |= Notification.FLAG_SHOW_LIGHTS;

// Now invoke the Notification Service
String notifService = Context.NOTIFICATION_SERVICE;
NotificationManager mgr = 
   (NotificationManager) getSystemService(notifService);
mgr.notify(NOTIFICATION_ID, n);

Or I suggest to follow an excellent tutorial about this

Respite answered 22/6, 2015 at 13:56 Comment(0)
S
2

I have used

Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Firebase Push Notification")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0, notificationBuilder.build());
Sorites answered 24/9, 2016 at 12:45 Comment(0)
F
1

In case it helps anyone... I was having a lot of trouble with setting up notifications using the support package when testing against newer an older API's. I was able to get them to work on the newer device but would get an error testing on the old device. What finally got it working for me was to delete all the imports related to the notification functions. In particular the NotificationCompat and the TaskStackBuilder. It seems that while setting up my code in the beginning the imports where added from the newer build and not from the support package. Then when I wanted to implement these items later in eclipse, I wasn't prompted to import them again. Hope that makes sense, and that it helps someone else out :)

Fleta answered 27/4, 2013 at 5:47 Comment(0)
S
0
          // This is a working Notification
       private static final int NotificID=01;
   b= (Button) findViewById(R.id.btn);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Notification notification=new       Notification.Builder(MainActivity.this)
                    .setContentTitle("Notification Title")
                    .setContentText("Notification Description")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .build();
            NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
            notification.flags |=Notification.FLAG_AUTO_CANCEL;
            notificationManager.notify(NotificID,notification);


        }
    });
}
Stoned answered 21/1, 2016 at 6:50 Comment(0)
T
0

Self-contained example

Same technique as in this answer but:

  • self-contained: copy paste and it will compile and run
  • with a button for you to generated as many notifications as you like and play with intent and notification IDs

Source:

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Main extends Activity {
    private int i;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Button button = new Button(this);
        button.setText("click me");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Notification notification = new Notification.Builder(Main.this)
                        /* Make app open when you click on the notification. */
                        .setContentIntent(PendingIntent.getActivity(
                                Main.this,
                                Main.this.i,
                                new Intent(Main.this, Main.class),
                                PendingIntent.FLAG_CANCEL_CURRENT))
                        .setContentTitle("title")
                        .setAutoCancel(true)
                        .setContentText(String.format("id = %d", Main.this.i))
                        // Starting on Android 5, only the alpha channel of the image matters.
                        // https://mcmap.net/q/88556/-notification-bar-icon-turns-white-in-android-5-lollipop
                        // `android.R.drawable` resources all seem suitable.
                        .setSmallIcon(android.R.drawable.star_on)
                        // Color of the background on which the alpha image wil drawn white.
                        .setColor(Color.RED)
                        .build();
                final NotificationManager notificationManager =
                        (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(Main.this.i, notification);
                // If the same ID were used twice, the second notification would replace the first one. 
                //notificationManager.notify(0, notification);
                Main.this.i++;
            }
        });
        this.setContentView(button);
    }
}

Tested in Android 22.

Talley answered 8/2, 2016 at 20:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.