Search code examples
androidandroid-jobscheduler

How to preserve context in JobScheduler


I have a job as under

public class MyPeriodicJob extends JobService{
    @Override
    public boolean onStartJob(JobParameters jobParameters) {

        // do something (but context is needed)

        return false;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return false;
    }
}

It is started in MainActivity

private void scheduleJob(){
        JobScheduler jobScheduler = (JobScheduler)getApplicationContext()
                .getSystemService(JOB_SCHEDULER_SERVICE);

        ComponentName componentName = new ComponentName(this,
                MyPeriodicJob.class);

        JobInfo jobInfo = new JobInfo.Builder(1, componentName)
                .setPeriodic(86400000)
                .setPersisted(true).build();
        jobScheduler.schedule(jobInfo);
    }

The device may restart but the job is expected to persist. How can I pass context (which must persist) to the MyPeriodicJob ?


Solution

  • Job service is the child of Service class, so you don't need to pass the context, anywhere because it's already there. Service class itself belongs to ContextWrapper which belongs to Context. So just use this.(CONTEXT FUNCTION YOU NEED)