3

I am working on a Xamarin Forms project. I want to create a background service in the android project. A friend suggested JobDispatcher.

I have found the Xamarin NuGet package marked as unlisted https://www.nuget.org/packages/Xamarin.Firebase.JobDispatcher. When I used Android.App.Job.JobService, it worked perfect but with the local process only. If the process has any code that calls the server, the service will stop.

public static class NotificationsJobInfo
{
    public static JobInfo.Builder CreateJobBuilderUsingJobId<T>(this Context context, int jobId) where T : JobService
    {
        var javaClass = Java.Lang.Class.FromType(typeof(T));
        var componentName = new ComponentName(context, javaClass);
        return new JobInfo.Builder(jobId, componentName);
    }
}

In MainActivity:

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.Main);
    StartNotificationsJob();
}

private void StartNotificationsJob()
{
    try
    {
        Intent intent = new Intent(this, typeof(MainActivity));
        var jobBuilder = this.CreateJobBuilderUsingJobId<MainJob>(1);
        JobInfo jobInfo = jobBuilder
                .SetOverrideDeadline(15*60*1000)
                //.SetRequiredNetworkType(NetworkType.Any)
                //.SetMinimumLatency(15 * 60 * 1000)
                //.SetPeriodic(15 * 60 * 1000)//,1000)
                .Build();

        JobScheduler jobScheduler = (JobScheduler)GetSystemService(JobSchedulerService);
        var result = jobScheduler.Schedule(jobInfo);
    }
    catch (Exception ex)
    {
    }
}

And the Job class:

[Service(Name = "XXXXXXXXXXXXXX.MainJob", Permission = "android.permission.BIND_JOB_SERVICE")]
public class MainJob : JobService
{
    public override bool OnStartJob(JobParameters @params)
    {
        Task.Run(() =>
        {
           //Do Some Process

        });
        return true;
    }

    public override bool OnStopJob(JobParameters @params)
    {
        return false;
    }
}

I need to make a background service that keep working forever and keep calling the server, even after the app has been killed.

Cleptus
  • 3,446
  • 4
  • 28
  • 34
Amir Imam
  • 871
  • 1
  • 12
  • 23

1 Answers1

4

Your best bet is to use WorkManager from Xamarin. You can find an introductory blog to WorkManager here

There's a new article on this topic on the Xamarin's blog: Getting Started With WorkManager.

Keep in mind that, if your app is force stopped, your background work will resume only after the user launch again your app. But WorkManager will keep track of the work and never loose any of it.

You can refer to the WorkManager's documentation for additional information. Keep in mind that WorkManager (as JobScheduler) have a minimum periodic interval of 15 minutes and that this is not a precise delay but just the minimum interval.

pfmaggi
  • 6,116
  • 22
  • 43
  • I upvoted this answer yesterday but now I think I shlould downvote it, but I can't. I now discover that although WorkManger is designed to run in the background , it doesn't in most devices. See [link](https://stackoverflow.com/questions/50682061/android-is-workmanager-running-when-app-is-closed) – quilkin Nov 21 '20 at 16:27
  • WorkManager complies to the general Android OS rules (a force stopped application has all its Alarms/Jobs removed till the user manually launch again the app). On top of that are OEMs that modify the stoc Android OS in ways that limits applications in the background (https://dontkillmyapp.com/). WorkManager has no additional rights than that of a normal application. Said that, you cannot expect that an application can run indefinitely in the background without user intervention: https://developer.android.com/topic/performance/power/power-details – pfmaggi Nov 22 '20 at 13:33