替换过时的Notification.Builder.SetPriority()?

时间:2018-03-06 21:44:30

标签: android xamarin xamarin.android

我尝试在Android上设置通知,并且Visual Studio警告Notification.Builder.SetPriority()已过时。

有替代品吗? Android建议使用SetImportance,但这似乎并不包含在Xamarin中。

1 个答案:

答案 0 :(得分:2)

  

此方法在API级别26中已弃用。   改为使用setImportance(int)。

SetImportance包含在NotificationChannel内的API26中,可以设置为频道上的属性,也可以设置为NotificationChannel构造函数中的属性:

channel.Importance = NotificationImportance.High

channel = new NotificationChannel(myUrgentChannel, channelName, NotificationImportance.High);

条件API通知示例:

var title = "Note from Sushi";
var message = "StackOverflow is a really great source of information";
using (var notificationManager = NotificationManager.FromContext(BaseContext))
{
    Notification notification;
    if (Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.O)
    {
        notification = new Notification.Builder(BaseContext)
                                             .SetContentTitle(title)
                                             .SetContentText(message)
                                             .SetAutoCancel(true)
                                             .SetPriority(1)
                                             .SetSmallIcon(Resource.Drawable.icon)
                                             .SetDefaults(NotificationDefaults.All)
                                             .Build();
    }
    else
    {
        var myUrgentChannel = PackageName;
        const string channelName = "SushiHangover Urgent";

        NotificationChannel channel;
        channel = notificationManager.GetNotificationChannel(myUrgentChannel);
        if (channel == null)
        {
            channel = new NotificationChannel(myUrgentChannel, channelName, NotificationImportance.High);
            channel.EnableVibration(true);
            channel.EnableLights(true);
            channel.LockscreenVisibility = NotificationVisibility.Public;
            notificationManager.CreateNotificationChannel(channel);
        }
        channel?.Dispose();

        notification = new Notification.Builder(BaseContext)
                                             .SetChannelId(myUrgentChannel)
                                             .SetContentTitle(title)
                                             .SetContentText(message)
                                             .SetAutoCancel(true)
                                             .SetSmallIcon(Resource.Drawable.icon)
                                             .Build();
    }
    notificationManager.Notify(1331, notification);
    notification.Dispose();
}