Xamarin表单的本地推送通知
问题描述:
我想使用Xamarin表单的DependencyService实现本地推送通知。 这里的接口:Xamarin表单的本地推送通知
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)
为:
无法从 '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);
答
使用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");
}
}
}
感谢您的帮助。有用。但我遇到了另一个问题。通知未显示,只有声音正在工作。我编辑了这个问题。请看 – Vivek
不好主意修改原来的问题,最好是你创建了一个新的线程,但我们已经在这里。由于您未设置图标,因此通知未显示。设置任何东西,以便测试它。使用'.SetSmallIcon(Android.Resource.Drawable.AlertDarkFrame)' – apineda