这个例子是基于Notification.Builder类来实现的,最低限度的,一个Builder对象应该包括以下:
- 一个小icon
- 一个标题 title
- 一个文本
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
定义一个Notification的行为(action)
虽然 行为 是可选的,但是你至少应该添加一个行为,也就是可以让 用户通过店家 Notification 直接跳转到一个你app的activity的行为。
这个行为,由 包含一个Intent的 pendingIntent 定义。
如何构造你的pendingIntent,由你想要的打开的activity的类型有关,有时候你只是打开其中的一个片段,那么你必须创建一个新的back stack,但是有时候你是打开一个全新的activity,那么就不需要创建一个backstack了,如下代码:
Intent resultIntent = new Intent(this, ResultActivity.class);
...
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
添加一个点击事件
PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);
发布一个Notification
- 获取一个 NotificationManager 的实例
- 使用 notify() 方法来发布,指明 发布Id
- 用 build() 方法来创建一个 Notification 对象
NotificationCompat.Builder mBuilder;
...
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
创建一个Notification的最简单方式
NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("hello notification")
.setContentText("how are you?");
Intent resultIntent = new Intent(this,MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this,0,resultIntent,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
int Id = 001;
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(Id,mBuilder.build());