Click here to Skip to main content
15,861,168 members
Articles / Mobile Apps / Xamarin

Alerts in Xamarin

Rate me:
Please Sign up or sign in to vote.
4.80/5 (9 votes)
24 Apr 2018CPOL3 min read 15.4K   5   1
Mobile alerts in Xamarim.forms

Introduction

In this article, we will cover the Mobile alerts in Xamarim.forms, for any mobile apps, 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 will work in a single shared project, we need to know what every environment can offer in native apps.

Background

Some knowledge of Xamarin.Forms and Visual Studio 2017.

Toast

It’s a simple Plugin: Toasts.Forms.Plugin that we can use inside Xamarin.forms project, I advise to start 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 developers to perform sound and badges.

Notification in Native Environment

iOS uses UNNotificationRequest object to manage notifications.

Android uses:

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:

Image 1

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.

C#
using Xamarin.Forms;
using Plugin.Toasts;

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

C#
DependencyService.Register<ToastNotification>();
ToastNotification.Init(this);

We do the same for the other platforms.

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

C#
// 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:

C#
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:

C#
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:

C#
[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:

C#
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);
    });
}

Image 2

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:

C#
DisplayAlert ("Alert!", "This is my first Alert", "OK"); 

Or:

C#
var answer = await DisplayAlert ("First question", "Do you know notifications in Xamarin", "Yes", "No");

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 on Youtube.

Simple Way as Native

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

And the GitHub is: https://github.com/xyfoo/XamarinForms-AndroidPopUp

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
Canada Canada
I am Rebaï Hamida, Microsoft MVP in Visual Studio and Development Technologies.
I'm a software architect and developer who like to build open source projects, writing articles, learning and teaching best practices. you can find out in my blog : http://hamidarebai.blogspot.com/

Innovative Software engineer : hands-on, competent software engineer, passionate and proficient C# developer, offering more than seven years of experience in the full software development lifecycle – from concept through delivery of next-generation applications and customized solutions, producing code to a consistently high standard and testing software across a variety of platforms.
Expert in advanced development methodologies, tools and processes contributing to the design and roll-out of cutting-edge software applications.
Known for excellent troubleshooting skills – able to analyze code and engineer well-researched, cost-effective and responsive solutions.


Success is only a consequence of a continuous work and remarkable intelligence.
I believe that I have to make a change in my country, I can’t live without leaving my footprint.

Comments and Discussions

 
PraiseNice one Pin
Logesh Palani4-Aug-19 4:35
Logesh Palani4-Aug-19 4:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.