Skip to content

Instantly share code, notes, and snippets.

@bbenetskyy
Last active Apr 18, 2022
Embed
What would you like to do?
/// <summary>
/// Native Background Worker Interface
/// </summary>
public interface IBackgroundWorker
{
/// <summary>
/// Worker Stopped Event
/// </summary>
public event EventHandler WorkerStopped;
/// <summary>
/// Actual Background Work
/// </summary>
public Func<Task> BackgroundWork { get; }
/// <summary>
/// Start Native Background or Foreground Service
/// </summary>
void StartWorker(Func<Task> backgroundWork);
/// <summary>
/// Force stop worked foreground or background service
/// </summary>
void StopWorker();
}
/// <summary>
/// Native Background Worker
/// </summary>
public class BackgroundWorker : IBackgroundWorker
{
/// <summary>
/// Worker Stopped Event
/// </summary>
public event EventHandler WorkerStopped;
/// <summary>
/// Actual Background Work
/// </summary>
public Func<Task> BackgroundWork { get; private set; }
#region Public Methods
/// <summary>
/// Start Native Background or Foreground Service
/// </summary>
public void StartWorker(Func<Task> backgroundWork)
{
BackgroundWork = backgroundWork;
var intent = new Intent(Application.Context, typeof(BackgroundService));
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
Application.Context.StartForegroundService(intent);
}
else
{
Application.Context.StartService(intent);
}
}
/// <summary>
/// Force stop worked foreground or background service
/// </summary>
public void StopWorker()
{
WorkerStopped?.Invoke(this, EventArgs.Empty);
}
#endregion Public Methods
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment