【发布时间】:2017-02-17 15:21:41
【问题描述】:
我正在尝试使用 Xamarin 表单的 DependencyService 实现本地推送通知。 这里是界面:
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 构造函数?
编辑:感谢您的帮助。它正在工作,但通知不仅显示声音正在工作。这里是代码:
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);
【问题讨论】:
标签: c# xamarin.android xamarin.forms