How to get dependency services like Sqlite,Logger registered in mauiprogram.cs in workmanager worker(android) class or BGTaskScheduler(iOS) when app in background/killed/closed state

Satya 160 Reputation points
2024-10-25T08:06:21.94+00:00

I am using WorkManager(Android) and BGTaskScheduler(iOS) for Scheduling an background task.

I have shared the code for below for scheduling and scheduling is working fine even app is in closed/killed state, but dependencies are not resolving in closed/killed state.

Do i need to create a new instance of eacj service again in background or is there any way to get the mauiprogram registered services?

#if ANDROID
        public void AddWorker<TWorker>(TimeSpan interval, Constraints workConstraints) where TWorker : Worker
        {
            try
            {
                var request = PeriodicWorkRequest.Builder.From<TWorker>(interval)
                             .SetConstraints(workConstraints).AddTag("OfflinePunchWork")
                             .Build();
                WorkManager.GetInstance(Microsoft.Maui.ApplicationModel.Platform.AppContext).EnqueueUniquePeriodicWork(nameof(TWorker), ExistingPeriodicWorkPolicy.Keep, request);
            }
            catch (Exception ex)             {                 //todo log exception             }         } #endif


For Scheduling the Task

#if ANDROID
                WorkManager.GetInstance(Microsoft.Maui.ApplicationModel.Platform.AppContext).CancelUniqueWork(nameof(OfflinePunchWorker));
                using var builder = new Constraints.Builder();
                builder.SetRequiredNetworkType(networkType: AndroidX.Work.NetworkType.Connected);
                builder.SetRequiresBatteryNotLow(true);
                var workConstraints = builder.Build();
                AddWorker<OfflinePunchWorker>(TimeSpan.FromMinutes(30), workConstraints);
                Android.Widget.Toast.MakeText(Microsoft.Maui.ApplicationModel.Platform.AppContext, "Work is scheduled", ToastLength.Long).Show();
#elif IOS
                BGTaskScheduler.Shared.Register("com.offlinepunchsync", null, task =>
              {
                  GetSQLiteDataAndCallAPIs();
                  task.SetTaskCompleted(true);
              });
                var appRefreshTaskRequest = new BGAppRefreshTaskRequest("com.offlinepunchsync")
                {
                    EarliestBeginDate = NSDate.Now
                };
                try
                {
                    BGTaskScheduler.Shared.Submit(appRefreshTaskRequest, out NSError error);
                    if (error == null)
                    {
                        //await Toast.Make("BG Task is scheduled", duration: CommunityToolkit.Maui.Core.ToastDuration.Long).Show();
                    }
                    else
                    {
                        Debug.WriteLine(error);
                      //  await Toast.Make("BG Task is not scheduled", duration: CommunityToolkit.Maui.Core.ToastDuration.Long).Show();
                    }
                }
                catch(Exception ex)
                {
                    Debug.WriteLine(ex);
                }
#endif

Android Worker

    public class OfflinePunchWorker : Worker
    {
        public OfflinePunchWorker(nint javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
        {
        }
        private Context Context;
        public OfflinePunchWorker(Context context, WorkerParameters workerParams) : base(context, workerParams)
        {
            Context = context;
        }
        public override Result DoWork()
        {
            try
            {
                MainThread.InvokeOnMainThreadAsync(async () =>
                {
                    
                    Toast.MakeText(Context ?? Microsoft.Maui.ApplicationModel.Platform.AppContext, "DO WORK Triggered", ToastLength.Long).Show();
                    OfflineHelper offlineHelper = new();
                    offlineHelper.GetSQLiteDataAndCallAPIs();
                });
                return Result.InvokeSuccess();
            }
            catch (Exception ex)
            {
                MainThread.InvokeOnMainThreadAsync(async () =>
                {
                     Toast.MakeText(Context ?? Microsoft.Maui.ApplicationModel.Platform.AppContext, "DO WORK Catch Exception", ToastLength.Long).Show();
                });
                WorkManager.GetInstance(Microsoft.Maui.ApplicationModel.Platform.AppContext).CancelUniqueWork(nameof(OfflinePunchWorker));
                return Result.InvokeFailure();
            }
        }
    }

Any help @Bruce (SqlWork.com) @Leon Lu (Shanghai Wicresoft Co,.Ltd.) @Wenyan Zhang (Shanghai Wicresoft Co,.Ltd.) @Yonglun Liu (Shanghai Wicresoft Co,.Ltd.)

Thanks in advance :)

Developer technologies .NET .NET MAUI
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.