Local Notifications for a Cross Platform app

Hi All,

I'm am learning Xamarin.Forms and have been at it for just over a week now, and i should just say that these are my first steps into app development using Xamarin.

I want to write a cross platform app so I can release on Android as well as iOS, but I'd also like to use the Xamarin.iOS local notification system. I dont even know if Android has such a thing, but if it does, I'd like to use that too.

I found this guide on how to do this (for iOS) using Xamarin.iOS and even got the example working on my PC/MacBookPro combination using Visual Studio 2017 on my PC, and must say the code looks a little alien to me, and doesn't reflect the Xamarin.Forms way of doing things at all.

Is there a simple way of re-engineering an example (this one in particular) from Xamarin.iOS to Xamarin.Forms?

Also Are there any good guides out there on how to replicate this for Android using Xamarin.Forms?

The guide I followed is shown below, and is a https link... (The link may or may not work, Apparently I'm too green to post links yet)

developer.xamarin.com/guides/ios/platform_features/user-notifications/deprecated/local_notifications_in_ios_walkthrough/

Posts

  • KarlRhodesKarlRhodes GBMember ✭✭

    Maybe I jumped the gun a bit here... I started to look at the code and tried to work out how recode the parts of it into the different areas of my cross platform app and think i'm getting somewhere.

    The AppDelegate stuff goes right where its meant to. and the other storyboard viewController code is being tested on a button clicked event for now.

    I think I may have found a suitable Adnroid example too...

    developer.xamarin.com/samples/monodroid/LocalNotifications/

  • seanydaseanyda GBMember ✭✭✭✭✭

    Check out the LocalNotifications plugin for Xamarin.Forms which is cross-platform so should ideally work across all iOS, Android and Windows.

    https://github.com/edsnider/LocalNotificationsPlugin

    You will be able to install this as a Nuget package into your PCL, and all your platform specific projects. Read up the documentation and it should be really straight forward to implement, I've used it many times before.

  • KarlRhodesKarlRhodes GBMember ✭✭

    @seanyda said:
    Check out the LocalNotifications plugin for Xamarin.Forms which is cross-platform so should ideally work across all iOS, Android and Windows.

    https://github.com/edsnider/LocalNotificationsPlugin

    You will be able to install this as a Nuget package into your PCL, and all your platform specific projects. Read up the documentation and it should be really straight forward to implement, I've used it many times before.

    That does look easy to use!!

    Thanks for the link Seanyda!!

  • HarshithaLSHarshithaLS USMember ✭✭

    Creating Local notification for Android and iOS

    Local notification for Android

    In your class

               private void RequestNotificationManager()
                    {
                        try
                        {
    
                            Intent intent = new Intent(Intent.ActionView);
                            var AppId = NSBundle.MainBundle.BundleIdentifier;
                           // intent.SetData(Android.Net.Uri.Parse("https://play.google.com/store/apps/details?id=" + AppId));
                            intent.SetData(Android.Net.Uri.Parse("market://details?id=" + AppId));
                            const int _pendingIntentId = 0;
                            PendingIntent oPendingIntent = PendingIntent.GetActivity(Forms.Context, _pendingIntentId, intent, PendingIntentFlags.OneShot);
    
        //For Oreo and above android version Notification.Builder is used
        //For below Oreo versions NotificationCompat.Builder is used.
    
                            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                            {
                                Notification.Builder oBuilder = new Notification.Builder(Forms.Context, "local_notification")
                                     .SetContentIntent(oPendingIntent)
                                     .SetContentTitle("Your notification title")
                                     .SetContentText("Your notification message")
                                     .SetSmallIcon(Resource.Drawable.YourIcon);
    
                                //On click of notification , the notification vanishes
                                //_Builder.SetAutoCancel(true);
                                oBuilder.SetColor(Android.Graphics.Color.ParseColor("#f9cf00"));
                                Notification oNotification = oBuilder.Build();
                                NotificationManager oNotificationManager = NotificationManager.FromContext(Forms.Context);
                                oNotificationManager.Notify(1000, oNotification);
                            }
                            else
                            {
                                NotificationCompat.Builder _Builder = new NotificationCompat.Builder(Forms.Context)
                                         .SetContentIntent(oPendingIntent)
                                         .SetContentTitle("Your notification title")
                                         .SetContentText("Your notification message")
                                         .SetSmallIcon(Resource.Drawable.YourIcon);
                                //On click of notification , the notification vanishes
                                //_Builder.SetAutoCancel(true);
                                _Builder.SetColor(Android.Graphics.Color.ParseColor("#f9cf00"));
                                Notification oNotification = _Builder.Build();
                                NotificationManager oNotificationManager = NotificationManager.FromContext(Forms.Context);
                                oNotificationManager.Notify(1000, oNotification);
                            }
                        }
                        catch (Exception oExp)
                        {
    
                        }
                    }
    

    To support notification for Oreo and above version, a notification channel should be created in MainActivity.cs file

     //in MainActivity.cs file
        protected override void OnCreate(Bundle bundle)
               {
        //Your code
       //Below  Initializer.Initialize();, call below method
          CreateNotificationChannel();
         }
              private void CreateNotificationChannel()
                     {
                       try
                        {
                       if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                             {
                                 var channelName = "YourChannel";
                                var ChannelDescription = "Channel for notification";
                                 var channel = new NotificationChannel("local_notification", channelName, NotificationImportance.Default)
                                {
                                    Description = ChannelDescription
                                };
                                 var cNotificationManager = (NotificationManager)GetSystemService(NotificationService);
                             cNotificationManager.CreateNotificationChannel(channel);
                             }
                         }
                         catch (Exception oExp)
                         {
    
                         }
                      }
    

    Local notification for iOS

    in AppDelegate.cs

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
                    {
    
            //For banner notification
             UNUserNotificationCenter.Current.Delegate = new iOSBannerNotification();
             //Ask user permission to display notification . its support for iOS 8
    
                        var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null);
                        UIApplication.SharedApplication.RegisterUserNotificationSettings(notificationSettings);
            }
            //iOSBannerNotification is  a seperate class
             public class iOSBannerNotification : UNUserNotificationCenterDelegate
                {
                    public iOSBannerNotification()
                    {
    
                    }
                    public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
                    {
                        completionHandler(UNNotificationPresentationOptions.Alert);
                    }
            }
            //Invoke Notification
            //Create a class as iosNotificationManager.cs
             public class iOSNotificationManager
                {
                    public iOSNotificationManager()
                    {
                    }
              public Task CreateDefaultNotification()
                    {
                        return Task.Run(() =>
                        {
                            try
                            {
                                Device.BeginInvokeOnMainThread(() =>
                                {
                                    //Schedule local notification
                                    UNUserNotificationCenter.Current.RemoveAllDeliveredNotifications();
                                    UILocalNotification oNotification = new UILocalNotification();
                                    oNotification.AlertTitle = "your notification title";
                                    oNotification.AlertBody = "Your notification text";
                                    //you can set fire time of notification as well
                                    // oNotification.FireDate = NSDate.FromTimeIntervalSinceNow(1);
                                    //Will push notification after 15 sec
                                    oNotification.SoundName = UILocalNotification.DefaultSoundName;
                                    //Push notification
                                    UIApplication.SharedApplication.ApplicationIconBadgeNumber = 1;
                                    UIApplication.SharedApplication.ScheduleLocalNotification(oNotification);
                                });
    
                            }
                            catch (Exception oExp)
                            {
                            }
                        });
                    }
            }
            //Call notification to create from your class
            public void CreateLocalNotification()
            {
            iOSNotificationManager oiOSNotify = new iOSNotificationManager();
                                    oiOSNotify.CreateDefaultNotification();
            }
    
Sign In or Register to comment.