Last active
April 18, 2022 07:49
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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