65.9K
CodeProject 正在变化。 阅读更多。
Home

MonoAndroid:Android 通知服务

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.69/5 (6投票s)

2013年9月2日

CPOL

1分钟阅读

viewsIcon

15494

使用 Android 通知服务提供通知的代码。

引言

通知服务是 Android 系统提供的用于在后台通知用户的机制。例如,您通过 Google Play 商店更新应用程序时,它会向您显示下载状态或成功更新的通知消息。

使用代码

现在要实现这一点,您需要遵循以下步骤:

  1. 使用 GetSystemService 方法获取 Notification 系统服务的对象,该对象类型为 NotificationManager

  2. 现在通过传递应用程序图标(或您希望向用户显示的任何其他图标)和您希望用户看到的消息字符串来创建 Notification 对象,如下所示:

     

  3. 现在创建 PendingIntent 对象,该对象将由通知对象用于生成消息通知。 PendingIntent 简而言之,**“允许外部应用程序使用您的应用程序的权限来执行预定义的代码段。”** 粗体文字摘自 StackOverflow 网站 此处

  4. 使用通知对象的 SetLatestEventInfo 方法以及要显示的消息,其中第二个参数对应于标题文本,第三个参数对应于较小的文本。

  5. 现在使用 NotificationManager 的 notify 方法向用户显示消息,以下是相应的代码:


var notificationMgr = GetSystemService (Context.NotificationService) as NotificationManager;

var notificationObj = new Notification (Resource.Drawable.Icon, 
                                        "Message From the CodeProject");
var pendingIntentObj  = 
    PendingIntent.GetActivity(this,0,new Intent(this, typeof(MainActivity)),0);

notificationObj.SetLatestEventInfo (this, 
                                    "CodeProject Notification", 
                                    "Message From MonoAndroid",
                                     pendingIntentObj);

notificationMgr.Notify (0, notificationObj);

您可以在下图所示的图像中清楚地看到标题文本上的文本 “CodeProject Notification” 以及较小的文本 “Message From MonoAndroid”

本系列文章

本系列技巧/窍门

© . All rights reserved.