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
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Saariko
  • 1,703
  • 4
  • 26
  • 46

11 Answers11

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);
prolink007
  • 33,872
  • 24
  • 117
  • 185
Rabi
  • 2,593
  • 1
  • 23
  • 26
  • 13
    I see there is a technique to do this in the v4 support package: NotificationCompat.Builder – stanlick Apr 10 '12 at 10:05
  • 6
    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. – Andy Jul 07 '12 at 01:08
  • 5
    The documentation says `builder.getNotification()` is deprecated. It says you should use `builder.build()`. – mneri Jul 18 '12 at 12:40
  • Fixed the references to the different api versions. And took out the fluff and fixed the deprecated stuff. – prolink007 Aug 17 '12 at 16:18
  • 26
    NotificationBuilder.build() requires API Level 16 or higher. Anything between API Level 11 & 15 you should use NotificationBuilder.getNotification(). – Camille Sévigny Aug 28 '12 at 16:51
  • @CamilleSévigny Should we use NotificationBuilder.getNotification() instead of NotificationBuilder.build() even with supportPackage? – Dr.jacky Nov 05 '12 at 10:04
  • @Mr.Hyde Had to do that. No idea why that isn't documented. – Christian Brüggemann Feb 18 '13 at 18:37
  • 1
    it's important to note that if you don't call setSmallIcon() before calling build() on the noficationBuilder that it will not work. – MrTristan Jun 05 '13 at 03:55
  • 4
    @MrTristan: As written in the documentation, `setSmallIcon()`, `setContentTitle()` and `setContentText()` are the minimum requirements. – caw Jan 09 '14 at 01:13
  • 1
    @MarcoW: not everyone reads the docs, a lot of lazy people just read highly voted answers like this one :-) – MrTristan Jan 09 '14 at 15:01
  • 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. – Someone Somewhere May 02 '14 at 05:33
  • how to set tags? notification.flags in targetsdk <6.0 – zys Feb 27 '16 at 03:45
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

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Femi
  • 64,273
  • 8
  • 118
  • 148
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);  
}  
MAD
  • 165
  • 4
ANemati
  • 4,766
  • 3
  • 20
  • 13
  • 5
    First code using the new Compat builder that has actually worked. Well done! – James MV Mar 31 '13 at 14:02
  • 1
    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]; – MotoRidingMelon Dec 04 '15 at 13:09
  • 1
    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 day – Shruti Aug 25 '16 at 12:11
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.

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Ye Myat Min
  • 1,429
  • 2
  • 17
  • 29
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.

Jagat Dave
  • 1,643
  • 3
  • 23
  • 30
Amit Vaghela
  • 22,772
  • 22
  • 86
  • 142
  • 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.0 – mfaisalhyder Jun 20 '16 at 21:10
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.

Nlinscott
  • 786
  • 7
  • 11
  • So if you think: "i'll find an icon later", you won't get any notify-love. Thanks for this one ;) – Nanne Nov 12 '15 at 21:29
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

dondondon
  • 881
  • 8
  • 4
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());
Nilesh
  • 1,013
  • 14
  • 21
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 :)

snatr
  • 21
  • 1
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);


        }
    });
}
Manoj Perumarath
  • 9,337
  • 8
  • 56
  • 77
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://stackoverflow.com/a/35278871/895245
                        // `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.

Community
  • 1
  • 1
Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985