Forum Xamarin.Forms

Service doesn't work when device sleeps

EliranEliran USMember ✭✭✭

I've built a simple service which works fine.

public class FibonacciJob : JobService
    public override bool OnStartJob(JobParameters jobParams)
        int x = jobParams.Extras.GetInt("secondsToWait", -1);

        Task.Run(() =>
            JobFinished(jobParams, false);
        return true;

    public override bool OnStopJob(JobParameters jobParams)
        return false;

The calling to the service is done by the next class:

    public class Class1: I1
        public const string JobSchedulerService = "jobscheduler";
        public void F1(int seconds)
            var instance = MainActivity.Instance;

            Java.Lang.Class javaClass = Java.Lang.Class.FromType(typeof(FibonacciJob));
            ComponentName component = new ComponentName(instance, javaClass);
            var jobParameters = new PersistableBundle();
            jobParameters.PutInt("secondsToWait", seconds);

            JobInfo.Builder builder = new JobInfo.Builder(1, component)

            JobInfo jobInfo = builder.Build();

            JobScheduler jobScheduler = (JobScheduler)instance.GetSystemService(JobSchedulerService);
            int result = jobScheduler.Schedule(jobInfo);        

The problem is that when I switch the phone to sleep mode (click the button on the device's side, so the screen is turned off),
the service doesn't work- the SetOverrideDeadline(10000) will not be taken in account.
Nothing will happen no matter how much time will pass.

How can I cause the service to start after X time (Lets say 1 hour) , no matter if the device sleeps or not.

Best Answer


Sign In or Register to comment.