Xamarin.Forms Android Push-уведомление не появляется - PullRequest
3 голосов
/ 04 апреля 2019

Я использую уведомление Azure Hub.Я разрабатываю свое приложение в Xamarin.Forms.Для Android я могу получить уведомление, когда я проверяю его попадания для отладки, и я могу показать DisplayAlert для этого.

Но я не могу показать его как уведомление.Я искал и после android oreo я должен создать канал уведомлений.

Но я не знаю, как это сделать.Они говорят, что вы должны создать идентификатор уведомления в вашем strings.xml, но у меня нет файла strings.xml.Я не знаю, как это сделать, кто-нибудь может помочь?

internal static readonly string CHANNEL_ID = "cross_channel";
    void CreateNotification(string title, string desc)
    {
        var notificationManager = GetSystemService(Context.NotificationService)
            as NotificationManager;

        var uiIntent = new Intent(this, typeof(MainActivity));
        var pendingIntent = PendingIntent.GetActivity(this, RandomGenerator(), uiIntent, PendingIntentFlags.OneShot);
        var notification = new Notification(Android.Resource.Drawable.ButtonMinus, title)
        {
            Flags = NotificationFlags.AutoCancel
        };
        notification.SetLatestEventInfo(this, title, desc,
            PendingIntent.GetActivity(this, 0, uiIntent, 0));

        if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            var channel = new NotificationChannel(CHANNEL_ID,
                                      "Cross Notifications",
                                      NotificationImportance.High);


            notificationManager.CreateNotificationChannel(channel);
            string channelId = "Cross Channel";
            var notBuilder = new Notification.Builder(Application.Context, CHANNEL_ID).SetContentTitle(title).SetContentText(desc).SetSmallIcon(Android.Resource.Drawable.StarBigOn).SetAutoCancel(true); 
            notificationManager.Notify(1, notBuilder.Build());

            channel.Description = (desc); 
            notBuilder.SetChannelId(channelId);
            }
            notificationManager.Notify(RandomGenerator(), notBuilder.Build());
    }

Ответы [ 2 ]

1 голос
/ 04 апреля 2019

В MainActivity.cs Вы можете вызвать этот метод в методе onCreate:

void CreateNotificationChannel()
    {
        if (Build.VERSION.SdkInt < BuildVersionCodes.O)
        {
            // Notification channels are new in API 26 (and not a part of the
            // support library). There is no need to create a notification 
            // channel on older versions of Android.
            return;
        }

        var channel = new NotificationChannel(CHANNEL_ID, "FCM Notifications", NotificationImportance.Default)
                      {
                          Description = "Firebase Cloud Messages appear in this channel"
                      };

        var notificationManager = (NotificationManager) GetSystemService(NotificationService);
        notificationManager.CreateNotificationChannel(channel);
    }

Где

    internal static readonly string CHANNEL_ID = "my_notification_channel";
    internal static readonly int NOTIFICATION_ID = 100; 

- определение для идентификатора канала и идентификатора уведомления соответственно.

В OnCreate MainActivity после загрузки XF вызовите это:

LoadApplication(new App());
CreateNotificationChannel();

Удачи

Возврат в случае запросов

0 голосов
/ 04 апреля 2019

У меня возникли некоторые проблемы с получением уведомлений, отображаемых с помощью Xamarin.Forms.Я предполагаю, что вы переопределили событие «OnMessageReceived», и вы вызываете «CreateNotification» напрямую?В конце концов, этот код работал для меня:

private void ShowNotification(RemoteMessage msg, IDictionary<string, string> data)
{
    var intent = new Intent();
    intent.AddFlags(ActivityFlags.ClearTop);

    foreach (var key in data.Keys)
        intent.PutExtra(key, data[key]);


    var pendingIntent = PendingIntent.GetActivity(Android.App.Application.Context, 100, intent, PendingIntentFlags.OneShot);

    var notificationBuilder = new NotificationCompat.Builder(Android.App.Application.Context) // Note: Everything I read online said to provide the ChannelID string here, but doing so caused it to not display notifications.
.SetSmallIcon(Resource.Drawable.abc_btn_radio_to_on_mtrl_000) // You can set this to your apps icon
.SetContentTitle(msg.GetNotification().Title)
.SetContentText(msg.GetNotification().Body)
.SetPriority((int)Android.App.NotificationImportance.Max)
.SetDefaults(NotificationCompat.DefaultAll)
.SetContentIntent(pendingIntent) // Even though intent here is empty, you *may* need to include it for the notification to show, I never tried without one.
.SetVisibility((int)NotificationVisibility.Public);


     var notificationManager = NotificationManagerCompat.From(Android.App.Application.Context);
            notificationManager.Notify(100, notificationBuilder.Build());
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...