我正在尝试使用DependencyService为Xamarin Forms实现本地推送通知。 这里是界面:
public interface INotification
{
void SetNotification(DateTime notificationDate, TimeSpan notificationTime);
}
以下是实施方案:
[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)
上显示错误为:
无法从'TestMVVM.Droid.NotificationService'转换为 'Andriod.Content.Context'
我明白这个问题。 Context
允许访问特定于应用程序的资源和类,以及对应用程序级操作的上调,例如启动活动,广播和接收意图等(请参阅:https://developer.xamarin.com/api/type/Android.Content.Context/#Remarks)。由于它是一个抽象类,我无法创建对象并将其传递给Builder
的构造函数。
如何将上下文传递给Builder Constructor?
编辑:感谢您的帮助。它正在工作,但通知没有显示只有声音正在工作。这里是代码:
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);
答案 0 :(得分:3)
使用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");
}
}
}