Android官方开发文档Training系列课程中文版:通知用户之构建通知

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android官方开发文档Training系列课程中文版:通知用户之构建通知相关的知识,希望对你有一定的参考价值。

原文地址:http://android.xsoftlab.net/training/notify-user/index.html

引言

通知用于在有事件发生时,将事情以更便捷的方式展示给用户。用户可以在他们方便的时候直接与通知交互。

Notifications design guide课程讲述了如何设计有效的通知以及何时去使用它们。这节课将会学习如何实现通用的通知设计。

构建通知

这节课的实现主要基于NotificationCompat.Builder类,NotificationCompat.Builder类属于支持库。开发者应该使用NotificationCompat及其子类,特别是NotificationCompat.Builder,以便支持更宽泛的平台。

创建通知构建器

当创建通知时,需要指定通知的UI内容以及它的点击行为。一个Builder对象至少要包含以下条件:

比如:

NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");

定义通知的行为

创建通知时,应当至少为通知添加一个行为。这个行为会将用户带到Activity中,这个Activity中详细的展示了发生了什么事情,或者可以使用户采取进一步的行动。在通知内部,行为由PendingIntent所包含的Intent指定,它可以用来启动Activity.

如何构造PendingIntent取决于要启动的Activity的类型。当由通知启动Activity时,开发者必须考虑用户所期待的导航体验。在下面的代码中,点击通知会启动一个新的Activity,这个Activity继承了通知所产生的行为习惯。在这种情况下不需要创建人为的回退栈。

Intent resultIntent = new Intent(this, ResultActivity.class);
...
// Because clicking the notification opens a new ("special") activity, there‘s
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
    PendingIntent.getActivity(
    this,
    0,
    resultIntent,
    PendingIntent.FLAG_UPDATE_CURRENT
);

设置通知的点击行为

为了使PendingIntent与手势产生关联,需要调用NotificationCompat.Builder的对应方法。比如要启动一个Activity,则调用setContentIntent()方法添加PendingIntent即可。

发布通知

发布通知需要执行以下步骤:

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

以上是关于Android官方开发文档Training系列课程中文版:通知用户之构建通知的主要内容,如果未能解决你的问题,请参考以下文章

Android官方开发文档Training系列课程中文版:OpenGL绘图之图形绘制

Android官方开发文档Training系列课程中文版:OpenGL绘图之环境配置

Android官方开发文档Training系列课程中文版:OpenGL绘图之响应触摸事件

Android官方开发文档Training系列课程中文版:OpenGL绘图之添加动态效果

Android官方开发文档Training系列课程中文版:Android的安全建议

Android官方开发文档Training系列课程中文版:OpenGL绘图之应用投影与相机视图