[android] How exactly to use Notification.Builder

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

This question is related to android api notifications deprecated

The answer is


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);  
}  

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.


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.


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


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 :)


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.


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.


          // 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);


        }
    });
}

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());

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);

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to api

I am receiving warning in Facebook Application using PHP SDK Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file Failed to load resource: the server responded with a status of 404 (Not Found) css Call another rest api from my server in Spring-Boot How to send custom headers with requests in Swagger UI? This page didn't load Google Maps correctly. See the JavaScript console for technical details How can I send a Firebase Cloud Messaging notification without use the Firebase Console? Allow Access-Control-Allow-Origin header using HTML5 fetch API How to send an HTTP request with a header parameter? Laravel 5.1 API Enable Cors

Examples related to notifications

NotificationCompat.Builder deprecated in Android O No notification sound when sending notification from firebase in android Android Push Notifications: Icon not displaying in notification, white square shown instead How to display multiple notifications in android Actionbar notification count icon (badge) like Google has How to display count of notifications in app launcher icon Android notification is not showing How to create a notification with NotificationCompat.Builder? Open application after clicking on Notification How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

Examples related to deprecated

Html.fromHtml deprecated in Android N Is `shouldOverrideUrlLoading` really deprecated? What can I use instead? getResources().getColor() is deprecated ActionBarActivity is deprecated Deprecated: mysql_connect() Replacement for deprecated sizeWithFont: in iOS 7? jQuery 1.9 .live() is not a function The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead How to declare or mark a Java method as deprecated? Is the buildSessionFactory() Configuration method deprecated in Hibernate