0
我想使用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);
感謝您的幫助。有用。但我遇到了另一個問題。通知未顯示,只有聲音正在工作。我編輯了這個問題。請看 – Vivek
不好主意修改原來的問題,最好是你創建了一個新的線程,但我們已經在這裏。由於您未設置圖標,因此通知未顯示。設置任何東西,以便測試它。使用'.SetSmallIcon(Android.Resource.Drawable.AlertDarkFrame)' – apineda