Forum Xamarin.Forms
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

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(() =>
        {
            Thread.Sleep(1000*x);
            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)
                                                 .SetMinimumLatency(10000)   
                                                 .SetOverrideDeadline(10000) 
                                                 .SetExtras(jobParameters);

            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

Answers

Sign In or Register to comment.