Timer within android service

Agg94Agg94 ESMember ✭✭

Hi all,

I'm using an Android Service to start a timer in order to run a synchronization process every 15 minutes.
This is my code:

[Service]
  public class SynchronizationService : Service
  {    
    .
    .
    .
    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
      AppendToFile("Creation " + DateTime.Now.ToString() + "\n");
      if (isStarted)
      {
        AppendToFile("Already started " + DateTime.Now.ToString() + "\n");
      }

      else
      {
        isStarted = true;
        startTime = DateTime.UtcNow;

        AppendToFile("Starting " + DateTime.Now.ToString() + "\n");
        timer = new Timer(HandleTimerCallback, startTime, 0, TimerWait);
      }

      return StartCommandResult.Sticky;
    }

    async void HandleTimerCallback(object state)
    {
      AppendToFile("Check " + DateTime.Now.ToString() + "\n");

      await SynchronizationProcess();

      AppendToFile("EndCheck " + DateTime.Now.ToString() + "\n");
    }

    .
    .
    .

The output for this while the application is running is the following:

Creation 2/25/2018 11:55:50 AM
Starting 2/25/2018 11:55:50 AM
Check 2/25/2018 11:55:50 AM
EndCheck 2/25/2018 11:55:51 AM

Check 2/25/2018 12:10:51 AM
EndCheck 2/25/2018 12:10:51 AM

Check 2/25/2018 12:25:52 AM
EndCheck 2/25/2018 12:25:52 AM

So it's working OK. But, once the application gets killed until starts running again, the output is the following:

Creation 2/26/2018 11:56:30 AM
Starting 2/26/2018 11:56:30 AM
Check 2/26/2018 11:56:30 AM

Creation 2/26/2018 11:56:33 AM
Starting 2/26/2018 11:56:33 AM
Check 2/26/2018 11:56:33 AM

Creation 2/26/2018 11:56:36 AM
Starting 2/26/2018 11:56:36 AM
Check 2/26/2018 11:56:36 AM
...

And the SynchronizationProcess is never done until the application starts running again...

How can this be solved?

Thanks

Sign In or Register to comment.