在我的.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);
}
}