服务通知Service Notifications
02/16/2018
本文内容
本指南讨论 Android 服务如何使用本地通知将信息分派给用户。This guide discusses how an Android service may use local notifications to dispatch information to a user.
服务通知概述Service Notifications Overview
服务通知允许应用向用户显示信息,即使 Android 应用程序不在前台。Service notifications allow an app to display information to the user, even if the Android application is not in the foreground. 通知可以为用户提供操作,例如显示应用程序中的活动。It is possible for a notification to provide actions for the user, such as displaying an Activity from an application. 下面的代码示例演示服务如何向用户分派通知:The following code sample demonstrates how a service might dispatch a notification to a user:
[Service]
public class MyService: Service
{
// A notification requires an id that is unique to the application.
const int NOTIFICATION_ID = 9000;
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
// Code omitted for clarity - here is where the service would do something.
// Work has finished, now dispatch anotification to let the user know.
Notification.Builder notificationBuilder = new Notification.Builder(this)
.SetSmallIcon(Resource.Drawable.ic_notification_small_icon)
.SetContentTitle(Resources.GetString(Resource.String.notification_content_title))
.SetContentText(Resources.GetString(Resource.String.notification_content_text));
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.Notify(NOTIFICATION_ID, notificationBuilder.Build());
}
}
此屏幕截图是显示的通知的示例:This screenshot is an example of the notification that is displayed:
当用户从顶部向下滑动通知屏幕时,将显示完整通知:When the user slides down the notification screen from the top, the full notification is displayed:
更新通知Updating A Notification
若要更新通知,服务将使用同一通知 ID 重新发布通知。To update a notification, the service will republish the notification using the same notification ID. Android 将在必要时在状态栏中显示或更新通知。Android will display or update the notification in the status bar as necessary.
void UpdateNotification(string content)
{
var notification = GetNotification(content, pendingIntent);
NotificationManager notificationManager = (NotificationManager)GetSystemService(Context.NotificationService);
notificationManager.Notify(NOTIFICATION_ID, notification);
}
Notification GetNotification(string content, PendingIntent intent)
{
return new Notification.Builder(this)
.SetContentTitle(tag)
.SetContentText(content)
.SetSmallIcon(Resource.Drawable.NotifyLg)
.SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.Icon))
.SetContentIntent(intent).Build();
}
有关通知的详细信息,请访问Android 通知指南的 "本地通知" 部分。More information about notifications is available in the Local Notifications section of the Android Notifications guide.
相关链接Related Links