Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@bbenetskyy
Last active April 18, 2022 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bbenetskyy/1ae9beb57705bf281a7418d329d95a53 to your computer and use it in GitHub Desktop.
Save bbenetskyy/1ae9beb57705bf281a7418d329d95a53 to your computer and use it in GitHub Desktop.
/// <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