【问题标题】:How can I make my app send out notifications when it's loaded but not running in the foreground?如何让我的应用程序在加载但未在前台运行时发送通知?
【发布时间】:2020-01-07 05:04:35
【问题描述】:

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

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

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

【问题讨论】:

  • 试试here。
  • 此外,这些通知是否也会出现在 Android 上? 是的,而且通常不需要它们。所以当你自己实现它们时,请尽量少用它们。
  • 如果提供的任何解决方案不起作用,请告诉我们! :)
  • 您是否尝试在应用启动后立即显示本地通知?
  • 嗨@Alan2!如果您对我的回答有任何疑问,请告诉我!如果它解决了您的问题,请务必将其标记为已回答,以便将来帮助其他开发者!

标签: c# xamarin xamarin.forms xamarin.android xamarin.ios


【解决方案1】:

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

示例应用

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

演练

1。安装 Shiny.Notifications

将Shiny.Notifications NuGet Package 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";
        }
    }
}

在MainActivity.cs,在OnRequestPermission,通过添加Shiny.AndroidShinyHost.OnRequestPermissionsResult(requestCode, permissions, grantResults);允许Shiny向用户展示请求通知权限

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

在AppDelegate.cs,在FinishedLaunching,通过调用Shiny.iOSShinyHost.Init来初始化Shiny:

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。安排本地通知

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

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

【讨论】:

  • 我可以问你一个问题吗?你知道如何将Shiny.Notifications 与前台服务一起使用吗?我的意思是使用StartForeground(int id, Android.App.Notification notification) 方法,通知必须以Android.App.Notification 的形式提供?
  • 在我安装了 shiny.Notifications 包之后 - 我在构建项目时遇到了一个错误 - 说找不到 system.Threading.Tasks 的参考。添加对 system.reactive.... 的引用。我不记得确切的错误。因为我现在卸载了 shiny.Notif 包,并且项目现在正在正常运行..
  • 应用关闭时如何让它工作?
【解决方案2】:

你可以使用Notifications来实现这个功能。 从文档 Local notifications in Xamarin.Forms,我们会发现:

本地通知是安装在 移动设备。本地通知通常用于诸如 如:

  • 列表项
  • 日历事件
  • 提醒

基于位置的触发器每个平台处理创建、显示、 和本地通知的消费不同。

您可以定义一个跨平台 API,应用程序可以使用该 API 与通知进行交互。

  public interface INotificationManager
{
    event EventHandler NotificationReceived;

    void Initialize();

    int ScheduleNotification(string title, string message);

    void ReceiveNotification(string title, string message);
}

更多细节,你可以查看上面的文档,这个链接也包含一个关于通知的示例。它应该对你有帮助。

当然,如果你想让你的应用在后台发送通知,你可以使用后台任务。

更多详情,您可以查看:

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

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

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

【讨论】:

    猜你喜欢
    • 2018-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 1970-01-01
    • 1970-01-01
    • 2017-12-04
    • 2020-12-23
    • 2014-05-18
    相关资源
    最近更新 更多