13

I have an app that I use sometimes. I must have left it there in the background before I slept. When I woke up I saw this notification on my screen.

enter image description here

Does anyone have any suggestions on how I can make a notification like this appear with my XF application?

Also, do these notifications appear on Android also? I've never seen them on my Android phone but that could be because I use it much less.

Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123
Alan2
  • 23,493
  • 79
  • 256
  • 450
  • Try [here](https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/local-notifications). – Andrew Jan 07 '20 at 05:44
  • _Also, do these notifications appear on Android also?_ Yes, and more often than not they are not wanted. So when you implement them yourself, please use them scarcely. – Bram Vanroy Jan 10 '20 at 14:45
  • Let us know if any of the presented solutions dont work! :) – Saamer Jan 10 '20 at 16:37
  • Are you trying to show local notifications as soon as the App Starts? – Anubhav Ranjan Jan 16 '20 at 13:34
  • Hi @Alan2! Let me know if you have any questions on my answer, below! If it solved your question, please be sure to mark it as Answered to help fellow devs in the future! – Brandon Minnick Jan 18 '20 at 11:59

2 Answers2

16

We can use Shiny.Notifications NuGet Package to create cross-platform Local Notifications in Xamarin.Forms

Sample App

A completed sample app created using the code below can be found here: https://github.com/brminnick/LocalNotificationsSample

Walkthrough

1. Install Shiny.Notifications

Add the Shiny.Notifications NuGet Package v1.2.0.1755 to your Xamarin.Forms project, your Xamarin.iOS project and Xamarin.Android project.

2. Initialize Shiny.Notifications

Android

In the [Application] class, in OnCreate, initialize Shiny by calling Shiny.AndroidShinyHost.Init and setting its icon by calling Shiny.Notifications.AndroidOptions.DefaultSmallIconResourceName:

using System;
using Android.App;
using Android.Runtime;
using Shiny;

namespace LocalNotificationsSample.Droid
{
    [Application]
    public class YourApplication : Application
    {
        public YourApplication(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer)
        {
        }

        public override void OnCreate()
        {
            base.OnCreate();
            AndroidShinyHost.Init(this, platformBuild: services => services.UseNotifications());
            Notifications.AndroidOptions.DefaultSmallIconResourceName = "icon.png";
        }
    }
}

In MainActivity.cs, in OnRequestPermission, allow Shiny to present request notifications permissions from the user by adding Shiny.AndroidShinyHost.OnRequestPermissionsResult(requestCode, permissions, grantResults);

using Android.App;
using Android.Content.PM;
using Android.OS;
using Android.Runtime;

namespace LocalNotificationsSample.Droid
{
    [Activity(Label = "LocalNotificationsSample", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
            Shiny.AndroidShinyHost.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
        }
    }
}

iOS

In AppDelegate.cs, in FinishedLaunching, initialize Shiny by calling Shiny.iOSShinyHost.Init:

using Foundation;
using UIKit;
using Shiny;

namespace LocalNotificationsSample.iOS
{
    [Register(nameof(AppDelegate))]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            iOSShinyHost.Init(platformBuild: services => services.UseNotifications());
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }
    }
}

3. Schedule a Local Notification

In this example, we will send a Local Notification immediately and schedule one to be sent one minute after the app launches

using System;
using System.Threading.Tasks;
using Shiny;
using Shiny.Notifications;
using Xamarin.Forms;

namespace LocalNotificationsSample
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();

            MainPage = new MainPage();
        }

        protected override async void OnStart()
        {
            await SendNotificationNow();
            await ScheduleLocalNotification(DateTimeOffset.UtcNow.AddMinutes(1));
        }

        Task SendNotificationNow()
        {
            var notification = new Notification
            {
                Title = "Testing Local Notifications",
                Message = "It's working",
            };

            return ShinyHost.Resolve<INotificationManager>().RequestAccessAndSend(notification);
        }

        Task ScheduleLocalNotification(DateTimeOffset scheduledTime)
        {
            var notification = new Notification
            {
                Title = "Testing Local Notifications",
                Message = "It's working",
                ScheduleDate = scheduledTime
            };

            return ShinyHost.Resolve<INotificationManager>().Send(notification);
        }
    }
}

enter image description here enter image description here

https://github.com/brminnick/LocalNotificationsSample

Brandon Minnick
  • 13,342
  • 15
  • 65
  • 123
  • May I ask you a question? Do you know how to use `Shiny.Notifications` with a foreground service? I mean with the `StartForeground(int id, Android.App.Notification notification)` method where the notification must be provided as an `Android.App.Notification`? – Eli Jan 14 '20 at 19:03
  • After i install the shiny.Notifications package - I am getting an error while building the project - which says reference not found for system.Threading.Tasks. add reference to system.reactive.... something like that. i dont remember the error exactly. Because i uninstalled the shiny.Notif package now and the proj is buliding fine now.. – Thameem Jul 14 '20 at 13:47
  • How do you make it work when the app is closed? – user1034912 Jan 22 '22 at 23:22
2

You can use Notifications to achieve this function. From document Local notifications in Xamarin.Forms,we will find:

Local notifications are alerts sent by applications installed on a mobile device. Local notifications are often used for features such as:

  • List item
  • Calendar events
  • Reminders

Location-based triggers Each platform handles the creation, display, and consumption of local notifications differently.

You can defines a cross-platform API that the application can use to interact with notifications.

  public interface INotificationManager
{
    event EventHandler NotificationReceived;

    void Initialize();

    int ScheduleNotification(string title, string message);

    void ReceiveNotification(string title, string message);
}

For more details, you can check above document, and this link also contains a sample about Notifications.It should be helpful for you.

Of course, if you want your app send notification when app is in background, you can use background-tasks.

For more details,you can check:

https://xamarinhelp.com/xamarin-background-tasks/

https://learn.microsoft.com/zh-cn/xamarin/ios/app-fundamentals/backgrounding/

https://learn.microsoft.com/en-ie/xamarin/android/app-fundamentals/services/creating-a-service/

Jessie Zhang -MSFT
  • 9,830
  • 1
  • 7
  • 19