在我的.NET Maui Android应用程序中,我试图使用AndroidX.Work.Worker来启动一个长时间运行的进程,该进程侦听来自加速度计的事件.我遇到的问题是,一旦DoWork方法退出,Worker就会终止.因此,我需要通过阻止DoWork退出来保持Worker运行,但我找不到实现这一点的代码.

    public class DropDetectorWorker : AndroidX.Work.Worker
    {
        public override Result DoWork()
        {
            CreateInitialNotificationChannel();
            
            var foregroundInfo = new ForegroundInfo(NotificationId++, BuildInitialNotification());
            SetForegroundAsync(foregroundInfo);
            
            InitialiseDropDetector();
            
            // TODO - prevent DoWork from exiting
            return Result.InvokeSuccess();
        }
        
        private void InitialiseDropDetector()
        {
            _dropDetector.DropDetected += DropDetector_DropDetected;
            _dropDetector.Start();
        }
        
        private void DropDetector_DropDetected(object sender, DropDetectedEventArgs e)
        {
            _lastDropDetected = SystemDate.UtcNow;
            TriggerAutoclaimNotification(e.Magnitude);
        }
        
        private void CreateInitialNotificationChannel()
        {
            NotificationChannel channel = new(INITIAL_NOTIFICATION_CHANNEL_ID, INITIAL_NOTIFICATION_CHANNEL_NAME, NotificationImportance.Default)
            {
                LightColor = Microsoft.Maui.Graphics.Color.FromRgba(0, 0, 255, 0).ToInt(),
                LockscreenVisibility = NotificationVisibility.Public
            };
        
            _notificationManager.CreateNotificationChannel(channel);
        }
        
        private void TriggerAutoclaimNotification(double magnitude)
        {
            var foregroundInfo = new ForegroundInfo(NotificationId, BuildMakeClaimNotification(magnitude));
            SetForegroundAsync(foregroundInfo);
        }
    }

推荐答案

最终,我只需要在Android上启动一项长期运行的任务.我采用了Worker方法,因为我遇到了Foreground Service方法没有创建通知的权限的问题.从那以后,我发现了如何绕过这些限制:

  • Android需要用户使用应用程序的主屏幕图标打开应用程序至少一次,然后才能创建通知.
  • 当出现提示时,用户必须允许通知;当应用程序第一次呼叫NotificationManager.CreateNotificationChannel时就会发生这种情况

一旦满足了这些条件,前台服务就会启动,我就可以运行我的加速计监视器了.

Csharp相关问答推荐

如何将两个查询结果组合在C#ASP.NET MHC控制器中

ASP.NET Core -是否可以对所有最小API端点应用过滤器?

错误NU 1301:无法加载源的服务索引

. NET 8使用COM向VB6公开

C#中使用BouncyCastle计算CMac

当我使用NET6作为目标框架时,为什么DotNet使用NET8作为MS包?

==和Tuple对象的相等<>

如何分配对象后的class的属性?

Polly v8—使用PredicateBuilder重试特定的状态代码

如何在Windows 11任务调度程序中每1分钟重复一次任务?

如何使用新的Microsoft.IdentityModel.JsonWebToken创建JwtSecurityToken?

在C#中,非静态接口方法的抽象和虚拟是冗余的吗?

.NET 8 DI GetServices<;对象&>不工作

为什么方法的值在SELECT方法中不会更改?

Regex字母数字校验

为什么ReadOnlySpan;T&>没有Slice(...)的重载接受Range实例的?

使用可空引用类型时C#接口实现错误

SqlException:无法打开数据库.升级到Dotnet 8后-数据库兼容性版本-非EFCore兼容性级别

外部应用&&的LINQ;左外部连接&类似于PostgreSQL的查询

如何获取我在SQL中输入的值