I am adding a JobService to my app using which I need to access an API every 2 hours.
I have added the JobService code below and scheduled it in my SplashActivity where I have my API function to get data from server but it is throwing this error.
Please help. I am not able to understand how can I use this API using JobService.
MyJobService:
public class MyJobService extends JobService {
private static final String TAG = MyJobService.class.getSimpleName();
boolean isWorking = false;
public boolean jobCancelled = false;
// Called by the Android system when it's time to run the job
@Override
public boolean onStartJob(JobParameters jobParameters) {
Log.d(TAG, "Job started!");
isWorking = true;
// We need 'jobParameters' so we can call 'jobFinished'
startWorkOnNewThread(jobParameters); // Services do NOT run on a separate thread
return isWorking;
}
private void startWorkOnNewThread(final JobParameters jobParameters) {
new Thread(new Runnable() {
public void run() {
doWork(jobParameters);
}
}).start();
}
private void doWork(JobParameters jobParameters) {
// 10 seconds of 'working' (1000*10ms)
new SplashActivity().productsDetailsApi();
Log.d(TAG, "Job finished!");
isWorking = false;
boolean needsReschedule = false;
jobFinished(jobParameters, needsReschedule);
}
// Called if the job was cancelled before being finished
@Override
public boolean onStopJob(JobParameters jobParameters) {
Log.d(TAG, "Job cancelled before being completed.");
jobCancelled = true;
boolean needsReschedule = isWorking;
jobFinished(jobParameters, needsReschedule);
return needsReschedule;
}
}
SplashActivity:
ComponentName componentName = new ComponentName(this, MyJobService.class);
JobInfo jobInfo = new JobInfo.Builder(12, componentName)
.setRequiresCharging(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPeriodic(120000)
.build();
JobScheduler jobScheduler = (JobScheduler)getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d("TAG", "Job scheduled!");
} else {
Log.d("TAG", "Job not scheduled");
}