title: Xamarin forms background service is killed when app is killed
body: <p>I am making use of Prism in my xamarin forms project.I am also making use of background services to push long running tasks in the background.The problem is when the app is killed the service is also killed.And by "killed" I mean press home-button -> see all running apps -> swipe my app aside -> app killed .I want to keep the service alive even if the app is killed.I have read many posts which say that it can be done.However I was not able to get it working.
  This is what I have tried :-</p>
  
  <p>This is Android MainActivity.cs</p>
  
  <pre><code>protected override void OnCreate(Bundle bundle)
          {
  
              base.OnCreate(bundle);
              try
              {
  
                  global::Xamarin.Forms.Forms.Init(this, bundle);
  
                  LoadApplication(new App(new AndroidInitializer()));
                  WireUpLongRunningTask(); 
  
              }
              catch(Exception)
              {
  
              }
          }
  
          public void WireUpLongRunningTask()  
          {
              MessagingCenter.Subscribe&lt;StartSyncBackgroundingTask&gt;(this, "StartSyncBackgroundingTask", message =&gt; {
                  var intent = new Intent(this, typeof(AndroidSyncBackgroundService));
                  StartService(intent);
              });
  
  
          }
  </code></pre>
  
  <p>This is AndroidSyncBackgroundService class :-</p>
  
  <pre><code>    [Service]
      public class AndroidSyncBackgroundService : Service
      {
          CancellationTokenSource _cts;
          private ISyncBackgroundService _isyncBackgroundService;
          private App _app =&gt; (App)Xamarin.Forms.Application.Current;
          public override IBinder OnBind(Intent intent)
          {
              return null;
          }
  
          public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
          {
              _cts = new CancellationTokenSource();
  
              Task.Run(() =&gt; {
                  try {
                      //INVOKE THE SHARED CODE
                      _isyncBackgroundService = _app.Container.Resolve&lt;ISyncBackgroundService&gt;();
                     _isyncBackgroundService.RunBackgroundingCode(_cts.Token).Wait();
  
  
                  }
                  catch (System.OperationCanceledException) {
                  }
                  finally {
                      if (_cts.IsCancellationRequested) {
                          var message = new CancelledTask();
                          Device.BeginInvokeOnMainThread(
                              () =&gt; MessagingCenter.Send(message, "CancelledTask")
                          );
                      }
                  }
  
              }, _cts.Token);
  
              return StartCommandResult.Sticky;
          }
  
          public override void OnDestroy()
          {
              if (_cts != null) {
                  _cts.Token.ThrowIfCancellationRequested();
  
                  _cts.Cancel();
              }
              StartService(new Intent("com.xamarin.AndroidSyncBackgroundService"));
              base.OnDestroy();
          }
  
          public override void OnTaskRemoved(Intent rootIntent)
          {
  Intent restartServiceIntent = new Intent(Xamarin.Forms.Forms.Context, typeof(AndroidSyncBackgroundService));
            PendingIntent restartServicePendingIntent = PendingIntent.GetService(Xamarin.Forms.Forms.Context, 1, restartServiceIntent,PendingIntentFlags.OneShot);
              AlarmManager alarmService = (AlarmManager)Xamarin.Forms.Forms.Context.GetSystemService(Context.AlarmService);
  
           alarmService.Set(
           AlarmType.ElapsedRealtime,
           1000,
           restartServicePendingIntent);
          base.OnTaskRemoved(rootIntent);
      }
  
  }
  </code></pre>
  
  <p>This is SyncBackgroundService class :-</p>
  
  <pre><code>public class SyncBackgroundService: ISyncBackgroundService
          {
              private ISqliteCallsService _iSqliteCallsService;
              private IFeedBackSqliteService _feedBackSqliteService;
              private ISettingApiService _isettingApiService;
              private ISettingSqliteService _isettingSqliteService;
              private IWebApiService _iwebApiService;
              private App _app =&gt; (App)Xamarin.Forms.Application.Current;
  
              public async Task RunBackgroundingCode(CancellationToken token)
              {
  
                  _iSqliteCallsService= _app.Container.Resolve&lt;ISqliteCallsService&gt;();
                  await Task.Run(async () =&gt; {
  
                      token.ThrowIfCancellationRequested();
  
                      App.bRunningBackgroundTask = true;
  
  
                      await Task.Run(async () =&gt;
                      {
                          await Task.Delay(1);
  
                          _iSqliteCallsService.ftnSaveOnlineModeXMLFormat("Offline", 0);
                          _iSqliteCallsService.SyncEmployeeTableData();
                          _iSqliteCallsService.SaveOfflineAppCommentData();
                          _iSqliteCallsService.SaveOfflineAdditionToFlowData();
                          await Task.Delay(500);
  
                          //MessagingCenter.Send&lt;SyncBackgroundService&gt;(this, "StopSyncBackgroundingTask");
                      });
  
                 }, token);
              }
  
             }
          }
  </code></pre>
  
  <p>As can be seen in the code snippet I have made use of StartCommandResult.Sticky and still  the service gets killed and does not restart.
  Also i'm making use of Alarm Manager in OnTaskRemoved method,which gets fired when the app is killed according to its documentation.But in my case the service does not restart atall.Can somebody point out what is the mistake in my code? Or provide a working solution so that I can implement it in my app.
  Thanks in advance! </p>