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());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值