In my .NET Maui Android app, I'm trying to use an AndroidX.Work.Worker
to fire up a long running process that listens for events from the Accelerometer. Problem I'm having is that as soon as the DoWork
method exits, the Worker terminates. So I need to keep the Worker running by preventing DoWork
from exiting, but can't figure out the code for this.
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);
}
}