How to stop a foreground service in the correct way? #15071
Unanswered
ComptonAlvaro
asked this question in
Q&A
Replies: 2 comments
-
I am wondering about this |
Beta Was this translation helpful? Give feedback.
0 replies
-
I do it this way. public partial class ForegroundServiceHandler
{
// Source: https://stackoverflow.com/a/61227156/10083577
bool _isStarted = false;
static Context context = Platform.CurrentActivity.ApplicationContext;
public partial void Start()
{
if (context == null)
{
return;
}
Intent intent = new Intent(context, typeof(RestServerCommunicationService));
if (_isStarted)
{
return;
}
if (OperatingSystem.IsAndroidVersionAtLeast(26))
{
_ = context.StartForegroundService(intent);
}
else
{
_ = context.StartService(intent);
}
_isStarted = true;
}
public partial void Stop()
{
if (context == null || !_isStarted)
{
return;
}
Intent intent = new(context, typeof(RestServerCommunicationService));
_ = context.StopService(intent);
_isStarted = false;
}
} namespace KlipperRemoteControl.Services
{
// Source: https://stackoverflow.com/a/61227156/10083577
[Service]
public class RestServerCommunicationService : Service
{
#region Properties
public int Progress { get; set; } = 0;
public bool IsPrinting { get; set; } = false;
#endregion
public override IBinder OnBind(Intent intent)
{
return null;
}
public const int ServiceRunningNotifID = 9000;
int _counter = 0;
int _offlineCounter = 0;
Timer timer;
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
try
{
Notification notif = DependencyService.Get<ServiceNotificationHelper>().ReturnNotif(Strings.Klipper3d, Strings.ForegroundServiceActive);
StartForeground(ServiceRunningNotifID, notif);
TimeSpan startTimeSpan = TimeSpan.Zero;
TimeSpan periodTimeSpan = TimeSpan.FromSeconds(SettingsApp.BackgroundMode_UpdateInterval);
timer = new Timer((e) =>
{
_ = DoLongRunningOperationThings();
}, null, startTimeSpan, periodTimeSpan);
}
catch (Exception exc)
{
EventManager.Instance.LogError(exc);
}
return StartCommandResult.Sticky;
}
public override void OnDestroy()
{
//StopSelf();
try
{
if (timer != null)
{
_ = timer.Change(Timeout.Infinite, Timeout.Infinite);
timer.Dispose();
timer = null;
}
}
catch (Exception exc)
{
EventManager.Instance.LogError(exc);
}
base.OnDestroy();
}
public override bool StopService(Intent name)
{
try
{
if (timer != null)
{
_ = timer.Change(Timeout.Infinite, Timeout.Infinite);
timer.Dispose();
timer = null;
}
}
catch (Exception exc)
{
EventManager.Instance.LogError(exc);
}
return base.StopService(name);
}
async Task DoLongRunningOperationThings()
{
try
{
if (MoonrakerClient.Instance == null || !MoonrakerClient.Instance.IsReady || _offlineCounter >= 3)
{
_offlineCounter = 0;
StopSelf();
return;
}
// Do some stuff
}
catch (Exception exc)
{
EventManager.Instance.LogError(exc);
}
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I am trying to create a service that I could start and stop when I se a switch.
This is my code:
I have realize that I can start and stop the foreground service if I do it in the OnStartCommand(). If I try to do it outside, it doesn't work.
For this reason, the implementation of my Stop() method is this:
The problem with this code, is that I am using the StartForegroundService() to force to execute the code in OnStartCommand(). But It looks like a bad workaround, because StartForegroundService it should be to use to start the foreground, not to stop it.
However, I try anothers implmentantions of the Stop() method, but no one of these works. Something like this:
I have try an example application that I found in youtube that it works. The implementation is this:
But in my case, MainActivity.ActivityCurrent is not available. Also I am not the reason to create the intent in this way. Why is it used the MainActivity of Android? Wouldn't it better to use the application context instead? Which is the difference?
So in summary, I would like to know how I should Stop the service.
Thanks so much.
Beta Was this translation helpful? Give feedback.
All reactions