如何让我的应用程序在加载但不在前台运行时发出通知?

Ala*_*an2 11 c# xamarin.ios xamarin.android xamarin xamarin.forms

我有一个有时会使用的应用程序。我一定是睡前把它留在了后台。当我醒来时,我在屏幕上看到了这个通知。

在此处输入图片说明

有没有人对我如何在XF应用程序中显示这样的通知有任何建议?

另外,这些通知也会出现在Android 上吗?我从未在我的Android手机上看到过它们,但这可能是因为我很少使用它。

Bra*_*ick 14

我们可以使用Shiny.Notifications NuGet 包在 Xamarin.Forms 中创建跨平台的本地通知

示例应用程序

可以在此处找到使用以下代码创建的完整示例应用程序:https : //github.com/brminnick/LocalNotificationsSample

演练

1. 安装 Shiny.Notifications

Shiny.Notifications NuGet 包 v1.2.0.1755添加到 Xamarin.Forms 项目、Xamarin.iOS 项目和 Xamarin.Android 项目。

2. 初始化 Shiny.Notifications

安卓

[Application]类中OnCreate,通过调用 Shiny.AndroidShinyHost.Init和设置其图标来初始化 Shiny 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";
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

MainActivity.cs, 在OnRequestPermission, 通过添加允许 Shiny 呈现来自用户的请求通知权限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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

IOS

AppDelegate.cs, 在FinishedLaunching, 通过调用初始化 Shiny 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

3. 安排本地通知

在这个例子中,我们将立即发送一个本地通知,并安排在应用程序启动后一分钟发送一个

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明 在此处输入图片说明

https://github.com/brminnick/LocalNotificationsSample


Jes*_*SFT 2

你可以用它Notifications来实现这个功能。从Xamarin.Forms中的文档 本地通知中,我们会发现:

本地通知是由移动设备上安装的应用程序发送的警报。本地通知通常用于以下功能:

  • 项目清单
  • 日历事件
  • 提醒事项

基于位置的触发器 每个平台以不同的方式处理本地通知的创建、显示和使用。

您可以定义应用程序可用于与通知交互的跨平台 API。

  public interface INotificationManager
{
    event EventHandler NotificationReceived;

    void Initialize();

    int ScheduleNotification(string title, string message);

    void ReceiveNotification(string title, string message);
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,您可以查看上面的文档,并且此链接还包含有关通知的示例。它应该对您有所帮助。

当然,如果您希望应用程序在后台时发送通知,您可以使用后台任务。

欲了解更多详情,您可以查看:

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/