saturdaymp - SaturdayMP.XPlugin.Notifications 0.2.2-rc0021

Plugin for creating and handling notifications in Xamarin Forms applications.

PM> Install-Package SaturdayMP.XPlugin.Notifications -Version 0.2.2-rc0021 -Source https://www.myget.org/F/saturdaymp/api/v3/index.json

Copy to clipboard

> nuget.exe install SaturdayMP.XPlugin.Notifications -Version 0.2.2-rc0021 -Source https://www.myget.org/F/saturdaymp/api/v3/index.json

Copy to clipboard

> dotnet add package SaturdayMP.XPlugin.Notifications --version 0.2.2-rc0021 --source https://www.myget.org/F/saturdaymp/api/v3/index.json

Copy to clipboard
<PackageReference Include="SaturdayMP.XPlugin.Notifications" Version="0.2.2-rc0021" />
Copy to clipboard
source https://www.myget.org/F/saturdaymp/api/v3/index.json

nuget SaturdayMP.XPlugin.Notifications  ~> 0.2.2-rc0021
Copy to clipboard

> choco install SaturdayMP.XPlugin.Notifications --version 0.2.2-rc0021 --source https://www.myget.org/F/saturdaymp/api/v2

Copy to clipboard
Import-Module PowerShellGet
Register-PSRepository -Name "saturdaymp" -SourceLocation "https://www.myget.org/F/saturdaymp/api/v2"
Install-Module -Name "SaturdayMP.XPlugin.Notifications" -RequiredVersion "0.2.2-rc0021" -Repository "saturdaymp" -AllowPreRelease
Copy to clipboard

GitHub release (with filter) Nuget GitHub Sponsors

XPlugins.Notifications

Provides a common interface to schedule notifications for Xamarin Forms.

This project is archived as there is a better version of Local Noticiations at thudugala/Plugin.LocalNotification. That said, if you think I should un-archive this project please let me know by opening an issue.

Installing

The plugin is released as a NuGet package at "SaturdayMP.XPlugin.Notifications". You can get the alpha builds (i.e. continous integration builds) from MyGet.

Schedule NotificationQuick Start

Assuming you have an existing Xamarin Forms application the below should get you sending notifications in a couple of minutes. If you need further help please check out the ExampleClient projects in the source code.

Platform Specific Setup

Once you have the NuGet package installed you need to setup a dependency reference in each project you want to use notifications in. This is usually done in the

Android

For Android you register the NotificatonScheduler in the main activity:

Public class MainActivity : Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
    // Code we don't care about....

    // Setup Xamarin forms.
    Xamarin.Forms.Forms.Init(this, bundle);

    // Register the notification dependency.
    DependencyService.Register<NotificationScheduler>();
  
    // Start the application.
    LoadApplication(new App());
}

iOS

Similar to Andorid you need to register the NotificationScheduler but this time in your AppDelete FinishedLaunching method.

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    Forms.Init();

    // Check if the user wants notifications.
    var settings = UIUserNotificationSettings.GetSettingsForTypes(
      UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound,
      new NSSet());
    UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);


    // Register the notification dependency.  Don't forget to do this.
    DependencyService.Register<NotificationScheduler>();


    // Launch the app.
    LoadApplication(new App());
    return base.FinishedLaunching(app, options);
}

Notice that on iOS you also need to prompt the user to allow notifications.

Scheduling a Notification

You can schedule a notification using the following code in your Xamarin Forms PCL project:

notificationScheduler = DependencyService.Get<INotificationScheduler>();
var notificationNumber = notificationScheduler.Create("Schedule Now", $"Created: {DateTime.Now:G}, Scheduled: {DateTime.Now:G}");

The above code snippet will schedule a notification that will display right away.

If you use Prism in your application you don't need to use DependencyService to load the scheduler. Instead you can just pass in a INotificationScheduler in your views constructors.

public MyClass(INotificationScheduler notificationScheduler)
{
  _notificationScheduler = notificationScheduler;
}
    
public void CreateNotification()
{
  var notificationNumber = _notificationScheduler.Create("Title", "Message", Date.Now);
}

The create method returns a unique identification number for the newly created notification. If you need to cancel or update a notification then keep track of this number. Otherwise you can just ignore this return value.

Cancel a Notification

To cancel a notification you need to know the notification number. If you didn't track the notification number when you created then shame on you. Also you won't be able to cancel the notification. Assuming you have the notification number then just do:

notificationScheduler.Cancel(notificationNumber);

This method has no return value. If the notification exists it was canceled. If the notification does not exist then there is nothing to cancel so no error is raised.

Find a Notification

If need be you can find an existing notification as such:

var foundNotification = notificationScheduler.Find(notificationNumber);
   
if (foundNotification != null)
{
  Console.Writeline(foundNotification.Id.ToString());
  Console.Writeline(foundNotification.Title);
  Console.Writeline(foundNotification.Message);
}

Will only find notifications that have not been canceled. On iOS this will only return notifications in the future. It won't find notifications in the past.

Receive Notifications Quick Start

Now that you can send notifications it would be nice to react when you get one. The below will let your Xamarin Forms handle incoming local notifications.

Platform Specific Setup

Similar to scheduling notifications it requires a small amount of platform specific code.

Android

When you schedule a notification in Android it is setup to reuse your existing activity but with a new intent. Override the OnNewIntent in the MainActivity:

public class MainActivity : FormsAppCompatActivity
{

    protected override void OnCreate(Bundle bundle)
    {
        // Code we aren't intersted in.
    }
    
    protected override void OnNewIntent(Intent intent)
    {
        // Let the parent do it's thing.
        base.OnNewIntent(intent);

        // Let the notification plugin translate the Andorid notification (i.e. Intent)
        // to a XPlugins notification.  This will also trigger the event in the portable
        // project assuming it has registered an observer.
        var listener = new NotificationListener();
        listener.NotificationRecieved(intent);
    }    
}

iOS

In iOS override the ReceivedLocalNotification method in the AppDelete class:

public class AppDelegate : FormsApplicationDelegate
{

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        // Code we aren't interested in.
    }

    public override void ReceivedLocalNotification(UIApplication application, UILocalNotification notification)
    {
        // The XPlugin know that we recieved a local notifiation.  It will
        // take are of the rest.
        var listener = new NotificationListener();
        listener.NotificationReceived(notification);
    }
}

Handling Notifications

In your portable class project you need to subscribe to receive incoming notifications. To do this create class that implments the INotificationObserver interface and it's one method NotificationRecieved. For example:

public class NotificationObserver : INotificationObserver
{
    public void NotificationReceived(Notification notification)
    {
        Console.WriteLine(notification.Id);
        Console.WriteLine(notification.Title);
        Console.WriteLine(notification.Message);
    }
}

The below example displays a new page when a notification is recieved with the details of the notification.

public class NotificationObserver : INotificationObserver
{
    /// <summary>
    ///     When a notification is recieved update the repository and show
    ///     the recieved notification to the user.
    /// </summary>
    /// <param name="notification"></param>
    public void NotificationReceived(Notification notification)
    {
        // Copy the notification values to the view model
        var viewModel = new NotificationRecievedViewModel
        {
            Id = notification.Id,
            Title = notification.Title,
            Message = notification.Message
        };

        // Only copy the extra info if it exists.
        if (notification.ExtraInfo.ContainsKey("ExtraInfoOne"))
            viewModel.ExtraInfoOne = notification.ExtraInfo["ExtraInfoOne"];

        if (notification.ExtraInfo.ContainsKey("ExtraInfoTwo"))
            viewModel.ExtraInfoTwo = notification.ExtraInfo["ExtraInfoTwo"];


        // Save the recieved view model.
        ScheduledNotificationRepository.NotificationRecieved(notification.Id, viewModel.Title, viewModel.Message, viewModel.ExtraInfoOne, viewModel.ExtraInfoTwo);


        // Show the notifcation page.
        var notificationPage = new NotificationRecievedPage(viewModel);
        Application.Current.MainPage.Navigation.PushAsync(notificationPage);
    }
}

Then register your INotificationObserver class as shown below. This example shows subscribing at the application start but that's not required.

public partial class App
{
    public App()
    {
        InitializeComponent();

        // Register the notification listener.
        NotificationListener.Subscribe(new NotificationObserver());

        MainPage = new NavigationPage(new Views.MainPage());
    }
}

Known Issues

Don't forget to unsubscribe if you no longer wish to receive local notifications. This usually won't be a problem because, I think, most applications will subscribe to receive notifications when they start and continue to receive them until terminated.

I'm also not 100% happy with the notification listener implementation. If you have any suggestions please let me know.

Acknowledgements

Project was inspired by edsnider/Xamarin.Plugins and EgorBo/Toasts.Forms.Plugin.

  • Portable Class Library (.NETFramework 4.5, Windows 8.0, WindowsPhoneApp 8.1): Profile111: 0.0.0.0
  • MonoAndroid 1.0: 1.0.0.0
  • Xamarin.iOS 1.0: 1.0.0.0

Owners

Christopher Cumming

Authors

SaturdayMP, chrisc

Project URL

https://github.com/saturdaymp/XPlugins.Notifications

License

MIT

Info

126 total downloads
5 downloads for version 0.2.2-rc0021
Download (21.54 KB)
Found on the current feed only

Package history

Version Size Last updated Downloads Mirrored?
0.3.0-rc0002 20.55 KB Tue, 16 May 2017 18:48:31 GMT 12
0.3.0-rc0001 20.54 KB Tue, 16 May 2017 18:18:31 GMT 3
0.3.0-beta0001 20.59 KB Tue, 16 May 2017 15:25:56 GMT 4
0.3.0-alpha0041 20.58 KB Thu, 03 Aug 2017 17:40:40 GMT 4
0.3.0-alpha0040 20.56 KB Thu, 03 Aug 2017 17:24:03 GMT 4
0.3.0-alpha0038 20.55 KB Thu, 06 Jul 2017 16:05:47 GMT 3
0.3.0-alpha0036 20.55 KB Thu, 18 May 2017 21:16:18 GMT 3
0.3.0-alpha0035 20.55 KB Mon, 15 May 2017 22:38:48 GMT 3
0.2.2-rc0024 20.58 KB Sat, 15 Apr 2017 21:10:34 GMT 3
0.2.2-rc0023 20.56 KB Mon, 20 Mar 2017 23:04:17 GMT 5
0.2.2-rc0022 21.55 KB Sat, 18 Mar 2017 14:38:15 GMT 5
0.2.2-rc0021 21.54 KB Sat, 18 Mar 2017 13:36:50 GMT 5
0.2.2-rc0020 20.54 KB Fri, 10 Mar 2017 16:59:16 GMT 3
0.2.2-rc0019 20.48 KB Tue, 07 Mar 2017 17:49:02 GMT 3
0.2.2-rc0018 20.53 KB Mon, 06 Mar 2017 17:47:02 GMT 3
0.2.2-rc0015 20.56 KB Sun, 26 Feb 2017 14:36:14 GMT 3
0.2.2-rc0013 20.26 KB Fri, 03 Feb 2017 18:40:19 GMT 3
0.2.2-rc0012 20.24 KB Wed, 01 Feb 2017 22:57:10 GMT 3
0.2.2-rc0011 20.24 KB Wed, 25 Jan 2017 23:46:40 GMT 3
0.2.2-rc0010 20.35 KB Wed, 25 Jan 2017 23:38:04 GMT 3
0.2.2-rc0008 20.35 KB Wed, 21 Dec 2016 16:31:04 GMT 4
0.2.2-rc0002 20.58 KB Tue, 18 Apr 2017 17:12:09 GMT 2
0.2.2-rc0001 20.38 KB Wed, 21 Dec 2016 15:45:03 GMT 3
0.2.1-beta0001 20.43 KB Wed, 21 Dec 2016 15:31:49 GMT 2
0.2.1-alpha0012 20.29 KB Thu, 08 Dec 2016 00:12:45 GMT 2
0.2.1-alpha0011 20.33 KB Wed, 07 Dec 2016 23:44:32 GMT 2
0.2.1-alpha0009 20.31 KB Wed, 07 Dec 2016 23:32:25 GMT 3
0.2.1-alpha0007 20.3 KB Wed, 07 Dec 2016 22:38:59 GMT 3
0.2.0 14.98 KB Fri, 02 Dec 2016 20:23:18 GMT 4
0.1.0-unstable0029 15.05 KB Fri, 02 Dec 2016 17:05:16 GMT 2
0.1.0-unstable0028 14.35 KB Wed, 30 Nov 2016 23:07:10 GMT 2
0.1.0-unstable0026 14.36 KB Wed, 30 Nov 2016 22:53:16 GMT 2
0.1.0-unstable0025 13.9 KB Sun, 27 Nov 2016 21:26:46 GMT 2
0.1.0-unstable0023 13.9 KB Sun, 27 Nov 2016 21:23:09 GMT 2
0.1.0-unstable0021 13.63 KB Sun, 27 Nov 2016 20:47:56 GMT 2
0.1.0-unstable0020 13.5 KB Fri, 25 Nov 2016 04:30:04 GMT 2
0.1.0-unstable0018 13.49 KB Fri, 18 Nov 2016 23:49:41 GMT 3
0.1.0-unstable0016 10.43 KB Fri, 18 Nov 2016 22:49:36 GMT 3
0.1.0-unstable0015 10.43 KB Fri, 18 Nov 2016 19:56:24 GMT 1
0.1.0-unstable0001 10.42 KB Fri, 18 Nov 2016 19:36:21 GMT 2