I want to write an application that requests data from a socket every 30-60 seconds and notify the user if there is new data.
I wrote a service but after sometime (50-60 min) Android kills the process. I'm trying to start it again in onDestroy().
The issue is when android kills the process, it does not invoke onDestroy().
What direction to look for? Read about WorkManager, it works with 15 minimum frequency.
Thanks in advance
Service
public class DataSource : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public const int ServiceRunningNotifID = 9000;
static readonly int TimerPerio = 10000;
Timer timer;
DateTime startTime;
bool isStarted = false;
INotification notification = DependencyService.Get<INotification>();
public ITaskService TaskService => DependencyService.Get<ITaskService>();
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Log.Debug(TAG, $"OnStartCommand called at {startTime}, flags={flags}, startid={startId}");
Notification notif = notification.ReturnNotif();
StartForeground(ServiceRunningNotifID, notif);
/*_ = DoLongRunningOperationThings()*/
if (isStarted)
{
TimeSpan runtime = DateTime.UtcNow.Subtract(startTime);
Log.Debug(TAG, $"This service was already started, it's been running for {runtime:c}.");
}
else
{
startTime = DateTime.UtcNow;
Log.Debug(TAG, $"Starting the service, at {startTime}.");
timer = new Timer(HandleTimerCallback, startTime, 0, TimerPerio);
isStarted = true;
}
return StartCommandResult.Sticky;
}
string TAG = "X: ";
void HandleTimerCallback(object state)
{
Location location;
TimeSpan runTime = DateTime.UtcNow.Subtract(startTime);
Log.Debug(TAG, $"This service has been running for {runTime:c} (since ${state}).");
Task.Run(async () =>
{
// do every 30 sec. GetDataFromServer();
});} }