为什么我无法使用Xamarin NotificationManager.notify(..)方法发送本地通知

时间:2016-05-05 18:19:38

标签: xamarin notifications xamarin.android

我只是想发送一个简单的通知。我从这个简单的界面开始:

public interface INotifier
{
    void LocalNotify(string title, string message);

}

然后在.droid项目中实现这样的接口:

class PlatformNotifier :INotifier
{

    public void LocalNotify(string title, string message)
    {
        NotificationManager notificationManager = Android.App.Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;
        Notification.Builder builder = new Notification.Builder(Android.App.Application.Context)
            .SetContentTitle(title)
            .SetContentText(message)
            .SetAutoCancel(true);

        Notification notification = builder.Build();
        notificationManager.Notify(1, notification);
    }
}

在我的实现的命名空间定义之前,我有这一行来使它成为一个依赖服务

[assembly: Dependency(typeof(PlatformNotifier))]

最后,我使用以下代码调用服务

private void DoneButton_Clicked(object sender, EventArgs e)
{
    INotifier notifier = DependencyService.Get<INotifier>();
    notifier.LocalNotify( "Test", "this is a notification");           
}

通过调试,我确认已达到Platform通知程序中的代码,并且Notify(...)被调用,但是没有通知显示。

2 个答案:

答案 0 :(得分:0)

这可能是您向Notification.Builder提供的上下文。尝试当前活动而不是应用程序。

您可以使用James Montemagno's CurrentActivity plugin来获取当前活动。

通过Nuget将Plugin.CurrentActivity安装到您的Xamarin.Android项目中,然后尝试:

...

    Notification.Builder builder = new Notification.Builder(CrossCurrentActivity.Current.Activity)...

...

答案 1 :(得分:0)

使用该代码,将起作用;)

方法Platform Notifier中的LocalNotify课程:

Notification.Builder builder = new Notification.Builder(Android.App.Application.Context)
    .SetContentTitle(Title)
    .SetContentText(ContentMessage)
    .SetSmallIcon(Resource.Drawable.icon);

    // Build the notification:
    Notification notification = builder.Build();

    // Get the notification manager:
    NotificationManager notificationManager = Android.App.Application.Context.GetSystemService(Context.NotificationService) as NotificationManager;

    // Publish the notification:
    const int notificationId = 0;
    notificationManager.Notify(notificationId, notification);