返回介绍

建立Notification

发布于 2020-04-01 13:16:48 字数 3126 浏览 835 评论 0 收藏 0

編寫:fastcome1985 - 原文:http://developer.android.com/training/notify-user/build-notification.html

  • 這節課向你說明如何創建與發佈一個Notification。

  • 這節課的例子是基於NotificationCompat.Builder類的,NotificationCompat.Builder在Support Library中。為了給許多各種不同的平臺提供最好的notification支持,你應該使用NotificationCompat以及它的子類,特別是NotificationCompat.Builder。

創建Notification Buider

  • 創建Notification時,可以用NotificationCompat.Builder對象指定Notification的UI內容與行為。一個Builder至少包含以下內容:

    • 一個小的icon,用setSmallIcon()方法設置
    • 一個標題,用setContentTitle()方法設置。
    • 詳細的文本,用setContentText()方法設置

例如:


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

定義Notification的Action(行為)

  • 儘管在Notification中Actions是可選的,但是你應該至少添加一種Action。一種Action可以讓用戶從Notification直接進入你應用內的Activity,在這個activity中他們可以查看引起Notification的事件或者做下一步的處理。在Notification中,action本身是由PendingIntent定義的,PendingIntent包含了一個啟動你應用內Activity的Intent。

  • 如何構建一個PendingIntent取決於你要啟動的activity的類型。當從Notification中啟動一個activity時,你必須保存用戶的導航體驗。在下面的代碼片段中,點擊Notification啟動一個新的activity,這個activity有效地擴展了Notification的行為。在這種情形下,就沒必要人為地去創建一個返回棧(更多關於這方面的信息,請查看 Preserving Navigation when Starting an 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
);

設置Notification的點擊行為

可以通過調用NotificationCompat.Builder中合適的方法,將上一步創建的PendingIntent與一個手勢產生關聯。比方說,當點擊Notification抽屜裡的Notification文本時,啟動一個activity,可以通過調用setContentIntent()方法把PendingIntent添加進去。

例如:


PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);

發佈Notification

為了發佈notification: * 獲取一個NotificationManager實例 * 使用notify()方法發佈Notification。當你調用notify()方法時,指定一個notification ID。你可以在以後使用這個ID來更新你的notification。這在Managing Notifications中有更詳細的描述。 * 調用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());

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文