locked
How to approach push notifications on Xamarin.Forms project? RRS feed

  • Question

  • User27898 posted

    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?

    Monday, July 21, 2014 2:23 PM

All replies

  • User2927 posted

    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?

    Monday, July 21, 2014 3:03 PM
  • User27898 posted

    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.

    Monday, July 21, 2014 4:29 PM
  • User2927 posted

    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 )

    Monday, July 21, 2014 4:43 PM
  • User108021 posted

    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.

    Sunday, March 8, 2015 8:56 AM
  • User2927 posted

    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.

    Sunday, March 8, 2015 9:01 AM
  • User53295 posted

    I also completed a tutorial here - https://azure.microsoft.com/en-us/documentation/articles/partner-xamarin-mobile-services-xamarin-forms-get-started-push/ . Although it doesn't contain any code that opens specific pages in the shared library based on notification events.

    Wednesday, June 3, 2015 7:55 PM
  • User81188 posted

    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?

    Wednesday, June 3, 2015 10:53 PM
  • User92953 posted

    Hi there, I have implemented push notifications in one of my Xamarin.Forms apps and I wrote a blog post regarding it, with some code shared.. Hope it might come in handy for some of you.. :)

    https://theconfuzedsourcecode.wordpress.com/2015/06/19/so-i-just-implemented-push-notifications-in-awesome-xamarin-forms/

    @KevinJonesD the above post might come in handy for you..

    Friday, June 19, 2015 9:11 AM
  • User131060 posted

    @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

    Thursday, June 25, 2015 7:20 AM
  • User191150 posted

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

    Friday, May 6, 2016 1:42 PM
  • User191150 posted

    ...?

    Tuesday, May 10, 2016 1:58 PM
  • User197084 posted

    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.

    Tuesday, May 10, 2016 3:03 PM
  • User19283 posted

    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) :-(

    Tuesday, June 28, 2016 6:50 AM
  • User151333 posted

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

    Monday, July 25, 2016 5:09 PM
  • User19283 posted

    @Xnaina I can't say no to a cute Xamarin Developer girl... :wink:

    this is the concept : - One "notification sending server" (WindowsServer) for multiples cross-platform applications (the same notification format for all applications : Title, Description and URL in option) - For each application, we have a ServiceWindows that contains a Timer and send every X seconds the notifications to the devices - the notification can be created before with a backend (code not shared, sorry), be affected to one or multiple devices (notification2user) and with the "create_date" you can plan the notification sending in advance.

    I'm using VS2013Update5 and Pushsharp 2.2.1.0 in this sample (But I have to update it with PushSharp 4.0 !!!) -> Thanks to Jonathan Dick (@Redth) for his great work, he is faster than me for updates ;-)

    It actually works in production with a tens of applications (just a recent bug (since 06/07/2016) / StackTrace attached / with iOS only but the notification is sent correctly by the way... if anybody had an idea to resolve - except updating PushSharp4.0 ;-))

    The bases are here, but I recommend you to start or update with PushSharp 4.0 : https://github.com/Redth/PushSharp

    If you need the see the "client side" of the notification management code, you can ask me by MP.

    I hope this will help you (and others)

    Jérôme

    Tuesday, July 26, 2016 7:53 AM
  • User151333 posted

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

    Thursday, July 28, 2016 3:28 PM
  • User243511 posted

    @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?

    Friday, August 19, 2016 1:02 PM
  • User247044 posted

    @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

    Friday, November 11, 2016 3:31 PM
  • User19283 posted

    @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...

    Friday, November 11, 2016 4:02 PM
  • User257359 posted

    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.

    Tuesday, January 17, 2017 3:15 AM
  • User195916 posted

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

    Thursday, March 30, 2017 9:53 AM
  • User333621 posted

    @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

    Friday, July 7, 2017 10:31 AM
  • User331858 posted

    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!

    Thursday, August 17, 2017 10:38 AM
  • User310920 posted

    @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 ?

    Tuesday, January 23, 2018 5:46 AM
  • User149388 posted

    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.

    Tuesday, March 20, 2018 9:29 AM
  • User149388 posted

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

    Tuesday, March 20, 2018 9:36 AM
  • User19283 posted

    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)

    Tuesday, March 20, 2018 10:45 AM
  • User212782 posted

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

    Thursday, August 30, 2018 10:37 AM
  • User19283 posted

    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 : - on android, in the native project, you have to implement this : https://docs.microsoft.com/en-us/xamarin/android/data-cloud/google-messaging/remote-notifications-with-fcm?tabs=vswin - on iOS, in the native project, you have to implement this : https://docs.microsoft.com/en-us/xamarin/ios/platform/user-notifications/

    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.

    Thursday, August 30, 2018 12:12 PM
  • User212782 posted

    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).

    Thursday, August 30, 2018 1:27 PM
  • User19283 posted

    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.

    Thursday, August 30, 2018 1:40 PM
  • User367513 posted

    @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

    Thursday, September 13, 2018 1:39 PM
  • User19283 posted

    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... ;-)

    Thursday, September 13, 2018 2:13 PM
  • User367513 posted

    @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.

    Thursday, September 13, 2018 2:17 PM