Podemos usar o Pacote NuGet do Shiny.Notifications para criar Notificações Locais entre plataformas no Xamarin.Forms
Sample App
Um exemplo de aplicativo completo criado usando o código abaixo pode ser encontrado aqui: https://github.com/brminnick/LocalNotificationsSample
Passo a passo
1. Instale o Shiny.Notifications
Adicione o pacote NuGet Shiny.Notifications ao seu projeto Xamarin.Forms, seu projeto Xamarin.iOS e projeto Xamarin.Android.
2. Inicialize o Shiny.Notifications
Android
Na [Application]
classe, em OnCreate
, inicialize o Shiny chamando Shiny.AndroidShinyHost.Init
e definindo seu ícone chamando 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";
}
}
}
Em MainActivity.cs
, em OnRequestPermission
, permita que o Shiny apresente permissões de notificação de solicitação ao usuário adicionandoShiny.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
, inicialize o Shiny chamando 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. Agende uma notificação local
Neste exemplo, enviaremos uma notificação local imediatamente e agendaremos uma para ser enviada um minuto após o lançamento do aplicativo
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);
}
}
}
https://github.com/brminnick/LocalNotificationsSample