title: Run background service in android for data syncing
body: <p>I'm new to Xamarin platform. I'm developing an application for Android platform using Xamarin.forms. How can I sync data with my server in the background. I want to upload the data as soon as the internet connection is available and at that time whatever the user is doing.</p>
  
  <p>Here is the sample service code by which I have tried</p>
  
  <pre><code>[Service]
  public class LongRunningTaskService : Service
  {
      public override IBinder OnBind (Intent intent)
      {
          return null;
      }
  
      public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId)
      {
          // start a task here
          new Task (() =&gt; {
              // long running code
              DoWork();
          }).Start();
  
          return StartCommandResult.Sticky;
      }
  
      public override void OnDestroy ()
      {
          base.OnDestroy ();
      }
  
      public void DoWork ()
      {
          while (true) 
          {
              //Printing text for checking if service is continously running or not
              Log.Write ("Hello");
              Thread.Sleep (5000);
          }
      }
  }
  </code></pre>
  
  <p>Now to start this service I have wriiten following code on my Activity class</p>
  
  <pre><code>this.StartService (new Intent (this, typeof(LongRunningTaskService)));
  </code></pre>
  
  <p>So then this task is writing that sample text in file in each 5secs, but the problem is that if that application is closed by the user using recent activity button of the mobile, the task is also stopped and text writing in log file is stopped.</p>
  
  <p>I need to keep running that task on a timely manner and as soon as the internet connection gets available and there are some local data to be uploaded on server, it should upload the data and keep checking for new files on the local device.</p>
  
  <p>Thank you</p>