具体如何使用 Notification.Builder

我发现我正在使用一个不推荐的通知方法(notification.setLatestEventInfo ())

它说要使用 Notification.Builder。

  • 怎么用?

当我尝试创建一个新实例时,它会告诉我:

Notification.Builder cannot be resolved to a type
170644 次浏览

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

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.

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

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

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

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.

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

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




}
});
}

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.

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.

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