MonoAndroid:Android 通知服务
使用 Android 通知服务提供通知的代码。
引言
通知服务是 Android 系统提供的用于在后台通知用户的机制。例如,您通过 Google Play 商店更新应用程序时,它会向您显示下载状态或成功更新的通知消息。
使用代码
现在要实现这一点,您需要遵循以下步骤:
- 使用 GetSystemService 方法获取 Notification 系统服务的对象,该对象类型为 NotificationManager。
- 现在通过传递应用程序图标(或您希望向用户显示的任何其他图标)和您希望用户看到的消息字符串来创建
Notification
对象,如下所示:
- 现在创建 PendingIntent 对象,该对象将由通知对象用于生成消息通知。 PendingIntent 简而言之,**“允许外部应用程序使用您的应用程序的权限来执行预定义的代码段。”** 粗体文字摘自 StackOverflow 网站 此处
- 使用通知对象的 SetLatestEventInfo 方法以及要显示的消息,其中第二个参数对应于标题文本,第三个参数对应于较小的文本。
- 现在使用 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”
本系列文章
- MonoAndroid:用 C# 编写自定义通用 BaseAdapter
- MonoAndroid:在您的移动应用程序中使用 GridView
- MonoAndroid:在移动应用程序中使用 TabHost
- MonoAndroid:在移动应用中使用 Fragments
- MonoAndroid:使用 dotnet Web 服务(ASMX)
- MonoAndroid:使用 Started Service
- MonoAndroid:用 C# 编写 ExpandableListView 和 BaseExpandableListAdapter
- MonoAndroid:使用 AlertDialog