日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

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

發(fā)布時間:2025/6/15 66 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android官方开发文档Training系列课程中文版:通知用户之构建通知 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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

引言

通知用于在有事件發(fā)生時,將事情以更便捷的方式展示給用戶。用戶可以在他們方便的時候直接與通知交互。

Notifications design guide課程講述了如何設計有效的通知以及何時去使用它們。這節(jié)課將會學習如何實現(xiàn)通用的通知設計。

構(gòu)建通知

這節(jié)課的實現(xiàn)主要基于NotificationCompat.Builder類,NotificationCompat.Builder類屬于支持庫。開發(fā)者應該使用NotificationCompat及其子類,特別是NotificationCompat.Builder,以便支持更寬泛的平臺。

創(chuàng)建通知構(gòu)建器

當創(chuàng)建通知時,需要指定通知的UI內(nèi)容以及它的點擊行為。一個Builder對象至少要包含以下條件:

  • 一個小圖標,通過setSmallIcon()方法設置。
  • 通知標題,通過setContentTitle()方法設置。
  • 詳細文本,通過setContentText()方法設置。

比如:

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

定義通知的行為

創(chuàng)建通知時,應當至少為通知添加一個行為。這個行為會將用戶帶到Activity中,這個Activity中詳細的展示了發(fā)生了什么事情,或者可以使用戶采取進一步的行動。在通知內(nèi)部,行為由PendingIntent所包含的Intent指定,它可以用來啟動Activity.

如何構(gòu)造PendingIntent取決于要啟動的Activity的類型。當由通知啟動Activity時,開發(fā)者必須考慮用戶所期待的導航體驗。在下面的代碼中,點擊通知會啟動一個新的Activity,這個Activity繼承了通知所產(chǎn)生的行為習慣。在這種情況下不需要創(chuàng)建人為的回退棧。

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與手勢產(chǎn)生關(guān)聯(lián),需要調(diào)用NotificationCompat.Builder的對應方法。比如要啟動一個Activity,則調(diào)用setContentIntent()方法添加PendingIntent即可。

發(fā)布通知

發(fā)布通知需要執(zhí)行以下步驟:

  • 獲得NotificationManager的實例。
  • 使用notify()方法發(fā)布通知。在調(diào)用notify()方法時需要指定通知的ID,這個ID用于通知的稍后更新。
  • 調(diào)用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());

總結(jié)

以上是生活随笔為你收集整理的Android官方开发文档Training系列课程中文版:通知用户之构建通知的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。