上篇讲了Android7.0新特性介绍(一)——多窗口支持,这篇讲讲Notification新增的API。首先奉上官网介绍——通知。
注:本文引用v4 支持库中的 NotificationCompat.Builder 类。Android 3.0(API 级别 11)中已添加类 Notification.Builder。
您可以根据需要设置通知的优先级。优先级充当一个提示,提醒设备 UI 应该如何显示通知。 要设置通知的优先级,请调用 NotificationCompat.Builder.setPriority()
并传入一个 NotificationCompat
优先级常量。有五个优先级别,范围从 PRIORITY_MIN (-2)
到 PRIORITY_MAX (2)
;如果未设置,则优先级默认为 PRIORITY_DEFAULT (0)
。
以下代码段说明了一个指定某项 Activity 在用户点击通知时打开的简单通知。该代码将创建 TaskStackBuilder 对象并使用它来为操作创建 PendingIntent。启动 Activity 时保留导航部分对此模式做了更详尽的阐述:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificatiOnManager=
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
就这么简单。您的用户现已收到通知。
要使通知出现在展开视图中,请先创建一个带有所需普通视图选项的 NotificationCompat.Builder 对象。接下来,调用以扩展布局对象作为其参数的 Builder.setStyle()。
以下代码段演示了如何更改在前面的代码段中创建的通知,以便使用扩展布局:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Event tracker")
.setContentText("Events received")
NotificationCompat.InboxStyle inboxStyle =
new NotificationCompat.InboxStyle();
String[] events = new String[6];
// Sets a title for the Inbox in expanded layout
inboxStyle.setBigContentTitle("Event tracker details:");
...
// Moves events into the expanded layout
for (int i=0; i
inboxStyle.addLine(events[i]);
}
// Moves the expanded layout object into the notification object.
mBuilder.setStyle(inBoxStyle);
...
// Issue the notification here.
并非所有通知功能都可用于某特定版本,即便用于设置这些功能的方法位于支持库类 NotificationCompat.Builder 中也是如此。 例如,依赖于扩展通知的操作按钮仅会显示在 Android 4.1 及更高版本的系统中,这是因为扩展通知本身仅在 Android 4.1 及更高版本的系统中可用。
为了确保最佳兼容性,请使用 NotificationCompat 及其子类(特别是 NotificationCompat.Builder)创建通知。此外,在实现通知时,请遵循以下流程:
当您需要为同一类型的事件多次发出同一通知时,应避免创建全新的通知, 而是应考虑通过更改之前通知的某些值和/或为其添加某些值来更新通知。
例如,Gmail 通过增加未读消息计数并将每封电子邮件的摘要添加到通知,通知用户收到了新的电子邮件。 这称为“堆叠”通知;通知设计指南对此进行了更详尽的描述。
注:此 Gmail 功能需要“收件箱”扩展布局,该布局是自 Android 4.1 版本起可用的扩展通知功能的一部分。
要将通知设置为能够更新,请通过调用 NotificationManager.notify() 发出带有通知 ID 的通知。 要在发出之后更新此通知,请更新或创建 NotificationCompat.Builder 对象,从该对象构建 Notification 对象,并发出与之前所用 ID 相同的 Notification。如果之前的通知仍然可见,则系统会根据 Notification 对象的内容更新该通知。相反,如果之前的通知已被清除,系统则会创建一个新通知。
以下代码段演示了经过更新以反映所发生事件数量的通知。 它将通知堆叠并显示摘要:
mNotificatiOnManager=
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Sets an ID for the notification, so it can be updated
int notifyID = 1;
mNotifyBuilder = new NotificationCompat.Builder(this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
numMessages = 0;
// Start of a loop that processes data and then notifies the user
...
mNotifyBuilder.setContentText(currentText)
.setNumber(++numMessages);
// Because the ID remains unchanged, the existing notification is
// updated.
mNotificationManager.notify(
notifyID,
mNotifyBuilder.build());
...
除非发生以下情况之一,否则通知仍然可见:
- 用户单独或通过使用“全部清除”清除了该通知(如果通知可以清除)。
- 用户点击通知,且您在创建通知时调用了 setAutoCancel()。
- 您针对特定的通知 ID 调用了 cancel()。此方法还会删除当前通知。
- 您调用了 cancelAll() 方法,该方法将删除之前发出的所有通知。
要在 Android 4.0 及更高版本的平台上使用进度指示器,需调用 setProgress()。对于早期版本,您必须创建包括 ProgressBar 视图的自定义通知布局。
下文介绍如何使用 setProgress() 在通知中显示进度。
要显示限定形式的进度栏,请通过调用 setProgress(max, progress, false) 将进度栏添加到通知,然后发出通知。随着操作继续进行,递增 progress 并更新通知。操作结束时, progress 应该等于 max。调用 setProgress() 的常见方法是将 max 设置为 100,然后将 progress 作为操作的“完成百分比”值递增。
您可以在操作完成后仍保留显示进度栏,也可以将其删除。无论哪种情况,都请记住更新通知文本以显示操作已完成。 要删除进度栏,请调用 setProgress(0, 0, false)。例如:
...
mNotifyManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Picture Download")
.setContentText("Download in progress")
.setSmallIcon(R.drawable.ic_notification);
// Start a lengthy operation in a background thread
new Thread(
new Runnable() {
@Override
public void run() {
int incr;
// Do the "lengthy" operation 20 times
for (incr = 0; incr <= 100; incr+=5) {
// Sets the progress indicator to a max value, the
// current completion percentage, and "determinate"
// state
mBuilder.setProgress(100, incr, false);
// Displays the progress bar for the first time.
mNotifyManager.notify(0, mBuilder.build());
// Sleeps the thread, simulating an operation
// that takes time
try {
// Sleep for 5 seconds
Thread.sleep(5*1000);
} catch (InterruptedException e) {
Log.d(TAG, "sleep failure");
}
}
// When the loop is finished, updates the notification
mBuilder.setContentText("Download complete")
// Removes the progress bar
.setProgress(0,0,false);
mNotifyManager.notify(ID, mBuilder.build());
}
}
// Starts the thread by calling the run() method in its Runnable
).start();
随着 Android 5.0(API 级别 21)的发布,通知现在还可显示在锁定屏幕上。您的应用可以使用此功能提供媒体播放控件以及其他常用操作。 用户可以通过“设置”选择是否将通知显示在锁定屏幕上,并且您可以指定您应用中的通知在锁定屏幕上是否可见。
您的应用可以控制在安全锁定屏幕上显示的通知中可见的详细级别。 调用 setVisibility() 并指定以下值之一: