gpt4 book ai didi

c# - 使用 Xamarin Forms 的本地推送通知

转载 作者:太空宇宙 更新时间:2023-11-03 23:03:16 25 4
gpt4 key购买 nike

我正在尝试使用 DependencyService for Xamarin Forms 实现本地推送通知。这里的界面:

public interface INotification
{
void SetNotification(DateTime notificationDate, TimeSpan notificationTime);
}

这里是andriod的实现:

[assembly:Dependency(typeof(NotificationService))]
namespace TestMVVM.Droid
{
public class NotificationService : INotification
{
public void SetNotification(DateTime notificationDate, TimeSpan notificationTime)
{
Notification.Builder builder = new Notification.Builder(this)
.SetContentTitle("Test Notification")
.SetContentText("Notification from Xamarin Forms");
}
}
}

它在 Notification.Builder builder = new Notification.Builder(this) 上显示错误:

Cannot Convert from 'TestMVVM.Droid.NotificationService' to 'Andriod.Content.Context'

我确实理解这个问题。 Context 允许访问特定于应用程序的资源和类,以及对应用程序级操作的向上调用,例如启动事件、广播和接收意图等(引用:https://developer.xamarin.com/api/type/Android.Content.Context/#Remarks)。由于它是一个抽象类,我无法创建对象并将其传递给 Builder 的构造函数。如何将上下文传递给 Builder 构造函数?

编辑:感谢您的帮助。它正在工作,但通知并没有显示只有声音在工作。这里的代码:

Notification.Builder builder = new Notification.Builder(Xamarin.Forms.Forms.Context)
.SetContentTitle("Test Notification")
.SetContentText("Notification from Xamarin Forms")
.SetDefaults(NotificationDefaults.Sound)
.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());

Notification notification = builder.Build();
NotificationManager notificationManager =
Forms.Context.GetSystemService(Context.NotificationService) as NotificationManager;
const int notificationId = 0;
notificationManager.Notify(notificationId, notification);

最佳答案

使用 Xamarin.Forms.Forms.Context

[assembly:Dependency(typeof(NotificationService))]
namespace TestMVVM.Droid
{
public class NotificationService : INotification
{
public void SetNotification(DateTime notificationDate, TimeSpan notificationTime)
{
Notification.Builder builder = new Notification.Builder (Xamarin.Forms.Forms.Context)
.SetContentTitle ("Test Notification")
.SetSmallIcon(Android.Resource.Drawable.AlertDarkFrame)
.SetWhen (Java.Lang.JavaSystem.CurrentTimeMillis ())
.SetDefaults (NotificationDefaults.Sound)
.SetContentText ("Notification from Xamarin Forms");
}
}
}

关于c# - 使用 Xamarin Forms 的本地推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42289718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com