Plugins for Mobile Alerts in Xamarin
This article will show you several plugins and how to use them to create mobile alerts in Xamarin apps for iOS and Android.
Join the DZone community and get the full member experience.
Join For FreeIn this article, we will cover mobile alerts in Xamarin.Forms. For any mobile app, it’s important to define with the user, client, or product owner if you will be working in an agile context (Scrum), and for Android or iOS. Even if we will work on 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 in a Xamarin.Forms project. I advise starting with it because it’s similar to native Toast or notification APIs, especially for iOS developers. Notifications are placed in the center inline to be close to the native platform, with some changes in design, and it allows developer to perform sound and badges.
Notifications in a Native Environment
iOS uses the UNNotificationRequest object to manage notifications.
Android uses
Snackbar, which displays a simple message and disappears after a certain span of time.
Notification.Builder (if we use at least Lollipop version), where you can set the title and an icon.
UWP/WinRT uses ToastNotification and includes text or an image.
How to Use the Plugin
We add this plugin from NuGet Package Manager Console in Visual Studio 2017 for 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."
As mentioned in the project GitHub description, we need to register the dependency on every platform (Android or iOS or UWP/WinRT).
So, for every project, we will add these references in MainActivity.CS or MainPage.cs:
using Xamarin.Forms;
using Plugin.Toasts;
We do the same for the other platforms.
For Android, this code will be added at the end of MainActivity.OnCreate, to register the dependency and initialize it:
DependencyService.Register<ToastNotification>();
ToastNotification.Init(this);
For iOS, we have to add a request permission to display the notifications:
// Request Permissions
if (UIDevice.CurrentDevice.CheckSystemVersion(10, 0))
{
// Request Permissions
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Alert | UNAuthorizationOptions.Badge | UNAuthorizationOptions.Sound, (granted, error) =>
{
// Deal with the problem
});
}
else if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null);
app.RegisterUserNotificationSettings(notificationSettings);
}
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, description, this is the interface INotificationOptions:
public interface INotificationOptions
{
string Title { get; }
string Description { get; }
bool IsClickable { get; }
// Platform Specific Options
IWindowsOptions WindowsOptions { get; }
IAndroidOptions AndroidOptions { get; }
IiOSOptions iOSOptions { get; }
}
Let’s start:
var options = new NotificationOptions()
{
Title = "Display notifications",
Description = "Some Description related to this title….",
IsClickable = false // Set to true if you need the result Clicked to come back (if the user clicks it)
};
// Use dependency service in order to resolve IToastNotificator.
var notification = DependencyService.Get<IToastNotificator>();
var result = await notification.Notify(options);
The result will return a NotificationResult with an Action having one of these values:
[Flags]
public enum NotificationAction
{
Timeout = 1, // Hides by itself
Clicked = 2, // User clicked on notification
Dismissed = 4, // User manually dismissed notification
ApplicationHidden = 8, // Application went to background
Failed = 16 // When failed to display the toast
}
Or we invoke the device in this way:
void ToastMessage(String title, String description)
{
Device.BeginInvokeOnMainThread(async () =>
{
var notifier = DependencyService.Get<IToastNotificator>();
var options = new NotificationOptions()
{
Title = title,
Description = description
};
var result = await notifier.Notify(options);
});
}
DisplayAlert
DisplayAlert is a popup; it’s different from a Notification because we have buttons (OK or Yes/No) in an Alert.
This is an example:
DisplayAlert ("Alert!", "This is my first Alert", "OK");
or
var answer = await DisplayAlert ("First question", "Do you know notifications in Xamarin", "Yes", "No");
Debug.WriteLine ("Answer: " + answer);
You can find a complete sample here.
UserDialogs
I use the plugin Acr.UserDialogs by Allan Ritchie. It’s a new way to use popup link with some different design from Toast and Alert. As mentioned in the 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 the plugin Acr.UserDialogs.
The Simple Way: Native
In this article, the author explains how we can display a simple Toast in an Android environment using a component in native mode. The GitHub is here.
Opinions expressed by DZone contributors are their own.
Trending
-
Constructing Real-Time Analytics: Fundamental Components and Architectural Framework — Part 2
-
Front-End: Cache Strategies You Should Know
-
Alpha Testing Tutorial: A Comprehensive Guide With Best Practices
-
A React Frontend With Go/Gin/Gorm Backend in One Project
Comments