0

I am writing an Xamarin.forms based app which is currently running on android platform. It is the first time I need to use push-notifications. I followed a guide from microsoft (https://learn.microsoft.com/de-de/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=vswin)") to implement the notifications.

The target android version is 8.1 API 27. The app runs on a Samsung tab active 2, which has android 8.1.

I configured the app as seen in the tutorial. I push the messages through a defined channel and this channel is subscribed in the app. The messages are pushed by a server which triggers the rest call for the FCM api. The first day I did some tests the transmission worked very good and I would say it was (nearly) reliable.

The next day I implemented some other features and wanted to test the push notifications again. Then: I was very confused, the most messages were not delivered or VERY VERY late. I am not sure if all messages were transmitted, there went may be some lost.

For me the FCM service is a big blackbox where I can delegate some work and then I need to hope that the messages will be transmitted. I am very confused now.

I paste here some code, but it is nearly what you can find in the tutorial:

My Questions: What can I do? Is there something to get some more information from the FCM what my messages are currently doing? Or are there some problems with the code?

This is run in the 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");
}

This checks if the channel can be created and creates it: (is called in the 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);
}

This checks if playServices are available: (also called in 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;
        }
    }

The last snipped is the service to handle a notification and inform the user:

[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());


        }
    }
}
chris000r
  • 297
  • 3
  • 10
  • Please check the MainActivity.NOTIFICATION_ID. Maybe some notifications has the same ID and doesn't appeared. – G.Mich Mar 27 '19 at 00:05
  • Which android version you are using? – K K Mar 27 '19 at 05:22
  • @G.Mich you are right that new notifications override the old. I did already some tests which unique IDs (hash value of current timestamp), but it has no influence. I got a breakpoint in the handler of the notification - it is not hit on every try I send a push notification from the server - so I am sure that not all push notifications are send to the app. – chris000r Mar 27 '19 at 07:26
  • @KK I edited my post. We are using android 8.1 api version 27 – chris000r Mar 27 '19 at 07:28
  • @chris000r Please see this [post](https://stackoverflow.com/questions/52849445/some-oreo-devices-are-not-getting-push-notification/52894271#52894271) may fix your issue – K K Mar 27 '19 at 10:46

0 Answers0