Forum Xamarin Xamarin.Forms

How to approach push notifications on Xamarin.Forms project?

HimanshuRathoreHimanshuRathore USMember, University

So we are working on a pcl project and have our UI set in a page inside the PCL. There is a scenario where our client wants some information to be sent as a push notification. We already have our UI in place and our backend too. We are using Azure to store data and have successfully configured WAMS. However we are scratching head on how to make push notifications work on Android without creating a separate page layout / controls that are android specific.

tl;dr - how do we use the PCL page UI elements to trigger push notifications on an Android device?

Answers

  • smsilvasmsilva PTInsider, University, Developer Group Leader ✭✭

    Like I said before in twitter,

    you should see my sample here
    NotificationHubSample.Droid

    Only when you receive Push Notification and the user open the notification our app will open and you need to update or do something... but not understood the problem with the notifications and UI.

    Is the app the send the notification? Is not the web service?

    For Xamarin.Android you can see this class MyBroadcastReceiver that manage the notification for android.

    I think you are not using NotificationHubs, right?

  • HimanshuRathoreHimanshuRathore USMember, University

    Hey, thanks for the response.

    Basically, we have a few text fields that will be entered by customers and that data will be saved to Azure table via InsertAsync method of Azure mobile service ; todo: on insertion a push notification should be sent to the customer. These fields are on a XAML page inside PCL project.
    I need to trigger submit button event and send all details to WAMS + get Push notifications on Android but all details are entered in PCL's UI elements.

    I hope I was about to clarify.

  • smsilvasmsilva PTInsider, University, Developer Group Leader ✭✭
    edited July 2014

    You want this:
    1. Customers fill some fields in your app (UI)
    2. Data is upload to Azure
    3. Azure send push notifications to device
    4. devices receive notifications

    right?

    Are you using Notification hubs??????????? I think yes but you don´t know.... hummmm Azure Mobile Service has it integrated.

    Your UI is inside in a PCL, right. And ? What is the problem? You wants to use Azure Mobile Service but it is not recognize in PCL? Is that?

    If yes, you should create an interface (In PCL) for define the method to insert and you need to create a class that implements this interface in project target. And then you need to init the app with the interface & implementation (dependency injection is great for it - MVVMLight is great for it! (I use in this sample)

    For get the notification hubs you should see this:
    Notification Hubs - All resources you need

    and see the class I talked before ( MyBroadcastReceiver )

  • SudhirT.4175SudhirT.4175 USMember

    for me the case is little different. I want to open a page (XAML) defined in my shared project when a notification received. So do you know how to open a Xamarin.Forms. page (content page) from Android/iOS?

    I hope I made my self clear.
    thanks in advance.

  • smsilvasmsilva PTInsider, University, Developer Group Leader ✭✭

    I understood what you said. Each time a push notification is received there is an event raised in the application for both targets, use it to send a message to the current page to navigate to a specific page based in the message.

    My sample about Notification Hubs
    https://github.com/saramgsilva/NotificationHubs

    has support for each target, and I have that methods, tried with it... do debug to understand the flow.

  • KevinJonesDKevinJonesD USMember ✭✭
    edited June 2015

    Great find Norm. I've been having some issues with some more outdated articles and this seems to be doing the trick, still having issues being able to open up an actual XF page though. Any ideas?

  • AbdulbashaAbdulbasha USMember ✭✭

    @UdaraAlwis Hi thanks for sharing the code. But as per my requirement i should not use Azure. So is it possible to create Push Notifications in xamarin PCL without using Azure. If yes please share code. Thanks in Advance

  • valentinamaugerivalentinamaugeri USMember

    I also wanted to ask if I create Push Notifications in Xamarin.Forms without using Azure. Thank you all!

  • valentinamaugerivalentinamaugeri USMember

    ...?

  • TravyDaleTravyDale USMember ✭✭

    Azure is not required to handle push notifications. From what I understand, Azure is there to help with the pushing of the notifications to all of your clients/devices. Check out the repo -- https://github.com/rdelrosario/xamarin-plugins/tree/master/PushNotification

    I used that as a reference for handling push notifications. I ended up writing my own, but that repo is a good starting point for someone looking to get started.

  • Liger_JeromeLiger_Jerome FRUniversity ✭✭

    Thanks @TravyDale !
    I use PushSharp for server side, and you're right : Azure is absolutly not a requirement, I'll even say it's useless (and expensive ^^)

    This plugin seems awesome, except that WP8 is not (actually) supported... and I have to target WP8(Silverlight) :-(

  • XnainaXnaina USMember ✭✭✭

    @LigerJrme Will you share the sample of this plug in?

  • XnainaXnaina USMember ✭✭✭

    @Liger_Jerome Thank you so much for response. Its work for me :smile:
    And thanks for compliment :blush:

  • SimoneDAmarioSimoneDAmario USMember
    edited August 2016

    @Liger_Jerome

    When I try to open the NotifyService_Neutralized solution, I receive this error

            Unsupported
            This version of Visual Studio is unable to open the following projects. The project types may not be installed or this version of Visual Studio may not support them. 
            For more information on enabling these project types or otherwise migrating your assets, please see the details in the "Migration Report" displayed after clicking OK.
                 - Setup_NotifyService, "C:\Progetti\NotifyService_Neutralized\Setup_Traitement\Setup_Traitement.vdproj"
    

    I have tried bot VS2013 and VS2015

    What can I do in order to get it work?

  • JordanMaxJordanMax USMember ✭✭

    @Liger_Jerome said:
    Thanks @TravyDale !
    I use PushSharp for server side, and you're right : Azure is absolutly not a requirement, I'll even say it's useless (and expensive ^^)

    This plugin seems awesome, except that WP8 is not (actually) supported... and I have to target WP8(Silverlight) :-(

    It's actually free for first million notifications you send, if it's expensive for you, you're going over that and unless you have no monetization, then that can't be expensive.

    **not affiliated with Azure at all

  • Liger_JeromeLiger_Jerome FRUniversity ✭✭

    @JordanMax It's right that the first million is free... but after that, just 1€ is an infinite more expensive than free solution...
    ;-)

    I'm not affiliate with PushSharp neither Azure, but I'm using both in differents cases... I just choose my platforms on what I need and what I want... it's depends on projects and technical constains...

  • James.gomezJames.gomez NLMember

    Hi all,
    I am gonna implement push notification using OneSignal.com on my Xamarin Forms project.
    Please let me know if you have any good solution for it.
    Thanks for your help.

  • YuraBabiyYuraBabiy UAMember ✭✭✭

    @James.gomez
    Hi, did you manage OneSignal for Xamarin.Forms? Do you have some good tutorials? Or simply say how did you do that?

  • FarhatUllahFarhatUllah USMember

    @Xnaina
    Can you share the sample code.I am beginner in Xamarin Form. I want to push notification else azure or firebase. Please share the sample code for Xamarin.Form notification.

    Thanks

  • DeepakDeepsDeepakDeeps INMember ✭✭✭

    Hi All,

    I have used this plugin for push notification in Xamarin.Forms
    https://github.com/rdelrosario/xamarin-plugins/tree/master/PushNotification

    i am able to register and i got Token and device type but i am unable to receive a notification

       void IPushNotificationListener.OnMessage(JObject values, DeviceType deviceType)
            {
                Debug.WriteLine("Message Arrived");
            }
    
            //Gets the registration token after push registration
            void IPushNotificationListener.OnRegistered(string Token, DeviceType deviceType)
            {
                Debug.WriteLine(string.Format("Push Notification - Device Registered - Token : {0}", Token));
            } 
    

    Please help me find a fix!

  • DeveshMishraDeveshMishra USMember ✭✭

    @valentinamaugeri said:
    I also wanted to ask if I create Push Notifications in Xamarin.Forms without using Azure. Thank you all!

    Hi,

    I am also looking for the same thing. Have you found any solutions ?

  • IamAmitSrivastavIamAmitSrivastav USMember ✭✭

    Can anyone please share their sample solution here?
    I don't want azure, FCM, GCM etc ... to send a push notification.
    Please help me here I want my own database and service to send notifications.

  • IamAmitSrivastavIamAmitSrivastav USMember ✭✭

    @Liger_Jerome Hi,
    Can you please help me here how can i do push notification with my own database and service.

  • Liger_JeromeLiger_Jerome FRUniversity ✭✭

    Hi,
    You can do your own "send server", but you have to use GCM(or FCM), APNS, and eventually WNS (or MPNS).
    Nobody can directly push a notification to a user device, only Google/Apple/Microsoft have a "link/backdoor" on their OS to receive push.
    I advise you to study the "push architecture", PushSharp, and my "complete server sample" in my previous post (.zip)

  • IgorSyrykhIgorSyrykh RUMember

    @Liger_Jerome Hi,
    How can I see the "client side" of the notification management code for Android and iOS from your previous post (.zip)?

  • Liger_JeromeLiger_Jerome FRUniversity ✭✭

    Hi @IgorSyrykh ,
    In fact, there is no "specific" client side... my "custom server" send a "normalized native notification" by FCM or APNS... so from the client side (Android and iOS App), you just have to handle it like a native notification (sended by FCM or APNS).
    So :

    And If you have a Xamarin.Forms application, when a push is received in the "native part", I advise to send a "MessagingCenter" event (with the notification content) that you have subsribed from your Forms part.

  • IgorSyrykhIgorSyrykh RUMember

    Hi @Liger_Jerome,
    Thanks for the reply. Yes, I'm using Xamarin.Forms. I already have a native implementation of receiving messages for each platform. I thought you had a common solution for different platforms (like PushSharp).

  • Liger_JeromeLiger_Jerome FRUniversity ✭✭

    There are tries to put it "crossplatorm" like :
    https://github.com/rdelrosario/xamarin-plugins/tree/master/PushNotification <-no FCM support apparently
    https://github.com/CrossGeeks/PushNotificationPlugin <- recommended

    But if you already have implemented the native receipt of notification, you are quite at the end of the work : all you have to do is a "MessagingCenter.Send(notif_payload)" from the native receiving function, and in your Forms App.cs, just subscribe the MessagingCenter at your app startup (and do a redirection/navigation or whatever you want with the payload when receiving this notification...) -> this is my solution because you are less dependant of plugins, FCM and APNS implementation will be updated more easily, and you can do whatever you want after receiving notification in your forms application logic.

  • @Liger_Jerome
    hello there!
    I have gone through the previous conversation.
    My code on app side is working okay when i tried to migrate to FCM from GCM.
    Whenever i send notification message from FCM console, i am getting that push notification on my device.

    I tried to do the same from the sever app (The code related to FCM has been changed with new API key from here),
    But it gives me error by saying the Push notifications failed due to some unknown error.

    private static void SendNotifications_Android(List<KeyValuePair<string, string>> devices)
            {
                //var config = new  GcmConfiguration("cccapp-677a1", "AIzaSyBKaY0yye2v-ohxgMRpQYq7HfFqtgbfys0", null);
    
    
                var config = new GcmConfiguration("AIzaSyAKx1XYxIE97hHnXSwmuMRI6ljXgbw_HxA");
                config.GcmUrl = "https://fcm.googleapis.com/fcm/send";
                var provider = "FCM";
    
    
                var gcmBroker = new GcmServiceBroker(config);
    
                gcmBroker.OnNotificationFailed += (notification, aggregateEx) =>
                {
    
                    aggregateEx.Handle(ex =>
                    {
                        var r = _notifications.Where(n => n.ToDeviceToken == notification.RegistrationIds.FirstOrDefault()).FirstOrDefault();
    
                        if (ex is GcmNotificationException)
                        {
                            var notificationException = (GcmNotificationException)ex;
    
                            var gcmNotification = notificationException.Notification;
                            var description = notificationException.Description;
    
                            _log.WriteLine(LogLevelEnum.LimitedDebug,
                                string.Format("GCM Notification Failed: Token={0}, Code={1}", gcmNotification.RegistrationIds[0], description));
    
                            if (r != null)
                                r.Status = string.Format("GCM Notification Failed: Code={0}", description);
    
                        }
                        else if (ex is GcmMulticastResultException)
                        {
                            var multicastException = (GcmMulticastResultException)ex;
    
                            if (r != null)
                                r.Status = string.Empty;
    
                            foreach (var succeededNotification in multicastException.Succeeded)
                            {
                                _log.WriteLine(LogLevelEnum.LimitedDebug,
                                string.Format("GCM Notification Succedded: Token={0}, Code={1}", succeededNotification.RegistrationIds[0], succeededNotification.MessageId));
    
                                if (r != null)
                                    r.Status += " | OK";
                            }
    
                            foreach (var failedKvp in multicastException.Failed)
                            {
                                var n = failedKvp.Key;
                                var e = failedKvp.Value;
                                _log.WriteLine(LogLevelEnum.LimitedDebug,
                                string.Format("GCM Notification Failed: Token={0}, Code={1}", n.RegistrationIds[0], e.Message));
    
                                if (r != null)
                                    r.Status += string.Format(" | GCM Notification Failed: Code={0}", e.Message);
                            }
                        }
                        else if (ex is DeviceSubscriptionExpiredException)
                        {
                            var expiredException = (DeviceSubscriptionExpiredException)ex;
    
                            var oldId = expiredException.OldSubscriptionId;
                            var newId = expiredException.NewSubscriptionId;
                            _log.WriteLine(LogLevelEnum.LimitedDebug,
                            string.Format("Device RegistrationId Expired: {0}", oldId));
    
                            if (r != null)
                                r.Status = "Device RegistrationId Expired";
    
                            if (!string.IsNullOrWhiteSpace(newId))
                            {
                                _log.WriteLine(LogLevelEnum.LimitedDebug,
                                string.Format("Device RegistrationId Changed To: {0}", newId));
    
                                if (r != null)
                                    r.Status += string.Format(" | Device RegistrationId Changed To: {0}", newId);
                            }
                        }
                        else if (ex is RetryAfterException)
                        {
                            var retryException = (RetryAfterException)ex;
                            _log.WriteLine(LogLevelEnum.LimitedDebug,
                            string.Format("GCM Rate Limited, don't send more until after {0}", retryException.RetryAfterUtc));
    
                            if (r != null)
                                r.Status = string.Format("GCM Rate Limited, don't send more until after {0}", retryException.RetryAfterUtc);
                        }
                        else
                        {
                            _log.WriteLine(LogLevelEnum.LimitedDebug, "GCM Notification Failed for some unknown reason");
    
                            if (r != null)
                                r.Status = string.Format("GCM Notification Failed for some unknown reason: {0}", ex.InnerException);
                        }
    
                        r.Status = Util.LeftXChars(r.Status, 255);
    
                        return true;
                    });
                };
    
                gcmBroker.OnNotificationSucceeded += (notification) =>
                {
                    _log.WriteLine(LogLevelEnum.LimitedDebug, string.Format("GCM Notification Sent to token: {0}", notification.RegistrationIds[0]));
    
                    var r = _notifications.Where(n => n.ToDeviceToken == notification.RegistrationIds.FirstOrDefault()).FirstOrDefault();
    
                    if (r != null)
                        r.Status = "OK";
                };
    
                gcmBroker.Start();
    
                foreach (var device in devices)
                {
                    gcmBroker.QueueNotification(new GcmNotification
                    {
                        RegistrationIds = new List<string> { 
                            device.Key
                        },
                        Data = JObject.Parse("{\"message\":\"" + device.Value + "\"}")
                    });
                }
    
    
                gcmBroker.Stop();
            }
    

    Please have a look and help me if you get any clue of what could be the issue.

    Thanks

  • Liger_JeromeLiger_Jerome FRUniversity ✭✭

    Hi @prachijignay
    At the first look, your code seems Ok...
    Have you seen this post ? (I think, you've change the config.GcmURL...)
    https://github.com/Redth/PushSharp/issues/870

    Apparently, for emmanuelware it works... and other interresting posts...

    But sorry, I'm very late, I didn't test it myself, I have not "migrate" my production push server yet... (yes I know, GCM will stop shortly, I have to put this thing on the top of my priority but I never have enough time to do it... ;-)

  • @Liger_Jerome
    I can understand, these things comes in priority when its really necessary :smiley:

    Thanks for the reply.
    will check with the post you sent, and update if anything works for me.

Sign In or Register to comment.