Search code examples
androidxamarin.formsxamarin.androidandroid-workmanager

Workmanager periodic work request in android app killed state


I need to sync the data from server for every X minutes, even after killing the app. I used the WorkManger with PeriodicWorkRequest to trigger for every X minutes. This is Triggering for every X minutes even if we kill the app. I’m facing the problem after quitting the app how to access static class or variables?

Example Code:

public void InitiateWorkManager()
    { 
        PeriodicWorkRequest myWorkRequest = PeriodicWorkRequest.Builder.From<SyncClass>(System.TimeSpan.FromMinutes(15)).Build();

        WorkManager.Instance.EnqueueUniquePeriodicWork(“MyIUniqueId”, ExistingPeriodicWorkPolicy.Keep, myWorkRequest); 
    }

SyncClass.cs :

  public class SyncClass : Worker
   {
        Context _context;
        public SyncClass(Context context, WorkerParameters workerParameters) : base(context, workerParameters)
        {
            _context = context;
        }

        public override Result DoWork()
        {
             var url = Constants.url;
            var list=  DependencyService.Get<IEmployee>().GetEmployeeList();
        }

  return Result.InvokeSuccess();
}

Constants.cs :

public static class Constants
{
public static string url =“www.xyz.com/getdata”
}

This works fine when app in foreground and background state but fails in killed state because DependencyService class is null.

Here static class DependencyService is accessed from nuget package “Xamarin.Form” and it is null in case of app in killed state.

Link Explains the similar problem but this is more on the process handling.

Is there any way of redefining this static class/variables inside DoWork(), Any hints/suggestions ? Xamarin.Android or in java/kotlin.


Solution

  • Using the below code solves the above problem, before calling DependencyService.Get().GetEmployeeList()

    Xamarin.Forms.Init()