Mobile Alerts In Xamarim.forms

In this article, we will cover mobile alerts in Xamarim.Forms. For any mobile app, it’s important to define with the user or the client or the product owner if we work in an Agile context (Scrum), for Android and for iOS. Even if we work in a single shared project, we need to know what every environment can offer in native apps.

Toasts

It’s a simple plugin: Toasts.Forms.Plugin that we can use inside Xamarin.forms project. I advise starting with it because it’s similar to native toast or notification API's especially for iOS developers.

Notifications are placed in the center line to be close to the native platform with some changes in design and it allows the developer to make sound and badges.

Notification in Native environment

iOS uses UNNotificationRequest object to manage notifications.

Android uses -

  • Snackbar that display a simple message and disappears after a lapse of time. (https://developer.android.com/reference/android/support/design/widget/Snackbar.html)

  • Builder if we use at least Lollipop version, where you can set the title and a small or large icon.(https://developer.android.com/reference/android/app/Notification.Builder.html)

  • UWP/WinRT uses ToastNotification: it includes text or image.
    (https://docs.microsoft.com/en-us/uwp/api/windows.ui.notifications.toastnotification)
How to use the Plugin

We add this plugin from NuGet Package Manager Console in Visual Studio 2017  on each platform, even your portable library, because it uses the Dependency Service.

Install-Package Toasts.Forms.Plugin -Version 3.3.2

Or we just open the Search Toasts.Forms.Plugin in Nuget Package Manager and we click on Install,

Xamarin
As mentioned in the project GitHub description, we need to register the dependency in every platform (Android or iOS or UWP/WinRT).

So, for every project, we will add these references in MainActivity.CS or MainPage.cs

  1. using Xamarin.Forms;  
  2. using Plugin.Toasts;  

For Android, this code will be added in the end of MainActivity.OnCreate, to register the dependency and initialize it,

  1. DependencyService.Register<ToastNotification>();  
  2. ToastNotification.Init(this);  

We do the same for the other platforms.

For iOS, we have to add a request permission to display the notifications.

  1. // Request Permissions  
  2. if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))  
  3. {  
  4.     // Request Permissions  
  5.     UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (granted, error) =>  
  6.     {  
  7. // Deal with the problem  
  8.     });  
  9. }  
  10. else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))  
  11. {  
  12.     var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes(  
  13.     UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null);  
  14.   
  15.     app.RegisterUserNotificationSettings(notificationSettings);  
  16. }  

Now, we are able to call a notification anywhere in the app, for example, let’s go back to the main page in Portable Project to start a simple example.

We start by defining the notification options like the title and description. This is the interface INotificationOptions.

  1. public interface INotificationOptions  
  2. {  
  3.     string Title { get; }  
  4.     string Description { get; }  
  5.     bool IsClickable { get; }  
  6.   
  7.     // Platform Specific Options  
  8.     IWindowsOptions WindowsOptions { get; }  
  9.     IAndroidOptions AndroidOptions { get; }  
  10.     IiOSOptions iOSOptions { get; }  
  11. }  

Let’s start.

  1. var options = new NotificationOptions()  
  2. {  
  3.     Title = "Display notifications",  
  4.     Description = "Some Description related to this title….",  
  5.     IsClickable = false // Set to true if you need the result Clicked to come back (if the user clicks it)  
  6. };  
  7.   
  8. // Use dependency service in order to resolve IToastNotificator.  
  9. var notification = DependencyService.Get<IToastNotificator>();  
  10. var result = await notification.Notify(options);  

The result will return a NotificationResult with an Action having one of these values:

  1. [Flags]  
  2. public enum NotificationAction  
  3. {  
  4.     Timeout = 1, // Hides by itself  
  5.     Clicked = 2, // User clicked on notification  
  6.     Dismissed = 4, // User manually dismissed notification  
  7.     ApplicationHidden = 8, // Application went to background  
  8.     Failed = 16 // When failed to display the toast  
  9. }  

Or we invoke the device in this way:

  1. void ToastMessage(String title, String description)  
  2. {  
  3.     Device.BeginInvokeOnMainThread(async () =>  
  4.     {  
  5.         var notifier = DependencyService.Get<IToastNotificator>();  
  6.         var options = new NotificationOptions()  
  7.         {  
  8.             Title = title,  
  9.             Description = description  
  10.         };  
  11.         var result = await notifier.Notify(options);  
  12.     });  
  13. }  
Xamarin
DisplayAlert

It’s a popup; it’s different from Notification because we have a button (Ok or Yes/No) in an Alert.

This is an example:

  1. DisplayAlert ("Alert!""This is my first Alert""OK");  
  2. //Or  
  3. var answer = await DisplayAlert ("First question""Do you know notifications in Xamarin""Yes""No");  
  4. Debug.WriteLine ("Answer: " + answer);  

You can find a complete sample in this link.

UserDialogs

I use this Plugin: Acr.UserDialogs by Allan Ritchie.

Link: https://github.com/aritchie/userdialogs

It’s a new way to use popup link with some different design from toast and Alert. As mentioned in GitHub documentation, it allows the developer “to call for standards user dialogs from shared/portable library, Actionsheets, alerts, confirmations, loading, login, progress, prompt, toast”.

In this video, I explain how we can integrate this plugin: Acr.UserDialogs

https://www.youtube.com/watch?v=_Vvpq9BaBAA

 A simple way as native:

In this article, the author explains how we can display a simple toast in an Android environment using this component in native mode,

  • https://material.io/guidelines/components/snackbars-toasts.html 
  • https://medium.com/@frankiefoo/how-to-display-androids-toast-snackbar-in-xamarin-forms-pcl-project-7ec31b1639b7

And the GitHub is here.