Пуш-уведомления Xamarin.Forms передаются очень ненадежно (поздно или совсем нет) - PullRequest
0 голосов
/ 26 марта 2019

Я пишу приложение на основе Xamarin.forms, которое в настоящее время работает на платформе Android. Это первый раз, когда мне нужно использовать push-уведомления. Я следовал руководству от Microsoft (https://docs.microsoft.com/de-de/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=vswin)") для реализации уведомлений.

Целевой версией Android является 8.1 API 27. Приложение работает на активной вкладке Samsung 2 с Android 8.1.

Я настроил приложение, как показано в руководстве. Я нажимаю сообщения через определенный канал, и этот канал подписан в приложении. Сообщения отправляются сервером, который запускает остальной вызов для API FCM. В первый день я провел несколько тестов, и коробка передач работала очень хорошо, и я бы сказал, что она была (почти) надежной.

На следующий день я реализовал некоторые другие функции и хотел снова протестировать push-уведомления. Затем: я был очень смущен, большинство сообщений не было доставлено или ОЧЕНЬ ОЧЕНЬ поздно. Я не уверен, что если все сообщения были переданы, могут быть некоторые потеряны.

Для меня служба FCM - это большой черный ящик, где я могу делегировать некоторую работу, и тогда мне нужно надеяться, что сообщения будут переданы. Я очень смущен сейчас.

Я вставляю сюда некоторый код, но это почти то, что вы можете найти в руководстве:

Мои вопросы: Что я могу сделать? Есть ли что-то, чтобы получить от FCM дополнительную информацию о том, что мои сообщения в настоящее время делают? Или есть проблемы с кодом?

Это выполняется в mainActivity:

if (this.IsPlayServicesAvailable())
        {
            // Creates a notification channel
            this.CreateNotificationChannel();

            //Console.WriteLine("InstanceID token: " + FirebaseInstanceId.Instance.Token);


            // Subscribe to notification token
            FirebaseMessaging.Instance.SubscribeToTopic("channel");



            Log.Debug(TAG, "Subscribed to remote notifications");
}

Это проверяет, может ли канал быть создан, и создает его: (вызывается в mainActivity)

private void CreateNotificationChannel()
    {
        // The app is not running on Android 8.0 or higher
        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;
        }

        // Create a notification channel for publishing notifications
        var channel = new NotificationChannel(CHANNEL_ID, "FCM Notifications", NotificationImportance.Default)
        {
            Description = "Firebase Cloud Messages appear in this channel"
        };

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

Проверяет, доступны ли playServices: (также вызывается в mainActivity)

public bool IsPlayServicesAvailable()
    {
        int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.Success)
        {
            if (GoogleApiAvailability.Instance.IsUserResolvableError(resultCode))
            {
                Log.Debug(TAG, GoogleApiAvailability.Instance.GetErrorString(resultCode));
            }
            else
            {
                Log.Debug(TAG, "This device has no compatible Google Play services APK - Download an APK from the Google Play Store or to enable it in the device's system settings!");
                Finish();
            }
            return false;
        }
        else
        {
            Log.Debug(TAG, "Google Play Services are available.");
            return true;
        }
    }

Последний перехватил сервис для обработки уведомления и информирования пользователя:

[Service]
[IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })]
public class CustomFirebaseMessagingService : FirebaseMessagingService
{
    // Logging Tag
    private static readonly string TAG = "CustomFirebaseMessagingService";

    /* Handles data messages and notifications messages if the app is in foreground. 
     * 
     * Apps only have 10 seconds in which to handle an incoming Firebase Cloud Message. 
     * Any work that takes longer than this should be scheduled for background execution using a library such as the 'Android Job Scheduler' or the 'Firebase Job Dispatcher'.
     * 
     */
    public override void OnMessageReceived(RemoteMessage message)
    {
        Log.Debug(TAG, "Message from: " + message.From);

        // If the message data payload is not empty, display a notification
        if (message.Data.Count > 0)
        {
            Log.Debug(TAG, "Data Payload: " + message.Data.ToString());
            this.SendNotification(message.Data);
        }
    }

    // Converts the incoming FCM message into a local notification
    private void SendNotification(IDictionary<string, string> data)
    {
        Console.WriteLine("Push Message received");

        var intent = new Intent(this, typeof(MainActivity));
        intent.AddFlags(ActivityFlags.ClearTop);

        if (data.TryGetValue("message", out string message))
        {
            foreach (var key in data.Keys)
            {
                intent.PutExtra(key, data[key]);
            }

            var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.OneShot);


            var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                                      .SetSmallIcon(Resource.Drawable.NotificationIcon)
                                      .SetContentTitle("TITEL")
                                      .SetContentText(message)
                                      .SetAutoCancel(true)
                                      .SetContentIntent(pendingIntent);

            var notificationManager = NotificationManagerCompat.From(this);
            notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());


        }
    }
}
...