Hello, You can stop services in the MainActivity OnStop method, when your application in the background, OnStop method will be executed. We can stop it By StopService with intent.
public class MainActivity : Activity
{
protected override void OnCreate(Bundle? savedInstanceState)
{
base.OnCreate(savedInstanceState);
Intent startServiceIntent = new Intent(this, typeof(BackgroundGeolocationService));
startServiceIntent.SetAction(Constants.ACTION_START_SERVICE);
StartService(startServiceIntent);
}
protected override void OnStop()
{
base.OnStop();
Intent stopServiceIntent = new Intent(this, typeof(BackgroundGeolocationService));
stopServiceIntent.SetAction(Constants.ACTION_STOP_SERVICE);
StopService(stopServiceIntent);
}
}
Then we need to handle the stop intent in OnStartCommand to stop services by StopForeground(true); StopSelf();
method.
[Service(ForegroundServiceType = ForegroundService.TypeLocation)]
public class BackgroundGeolocationService : Service
{
public override IBinder? OnBind(Intent? intent)
{
return null;
}
bool isStarted;
static readonly string TAG = typeof(BackgroundGeolocationService).FullName;
[return: GeneratedEnum]
public override StartCommandResult OnStartCommand(Intent? intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
if (intent.Action.Equals(Constants.ACTION_START_SERVICE))
{
if (isStarted)
{
Log.Info(TAG, "OnStartCommand: The service is already running.");
}
else
{
Log.Info(TAG, "OnStartCommand: The service is starting.");
RegisterForegroundService();
isStarted = true;
}
}
else if (intent.Action.Equals(Constants.ACTION_STOP_SERVICE))
{
Log.Info(TAG, "OnStartCommand: The service is stopping.");
StopForeground(true);
StopSelf();
isStarted = false;
}
else if (intent.Action.Equals(Constants.ACTION_RESTART_TIMER))
{
Log.Info(TAG, "OnStartCommand: Restarting the timer.");
}
// This tells Android not to restart the service if it is killed to reclaim resources.
return StartCommandResult.Sticky;
}
}
By the way, Constants is a static class.
public static class Constants
{
public const string ACTION_START_SERVICE = "ServicesDemo3.action.START_SERVICE";
public const string ACTION_STOP_SERVICE = "ServicesDemo3.action.STOP_SERVICE";
public const string ACTION_RESTART_TIMER = "ServicesDemo3.action.RESTART_TIMER";
}
Best Regards, Leon Lu
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.