Activity Code
JobScheduler scheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
ComponentName componentName = new ComponentName(this, EJobService.class);
JobInfo info = new JobInfo.Builder(123, componentName)
.setRequiresCharging(true)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)
.setPersisted(true)
.setPeriodic(5*1000,500)
.build();
int resultCode = scheduler.schedule(info);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d("Job Started", "Job scheduled");
} else {
Log.d("Tag", "Job scheduling failed");
}
Service code
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class EJobService extends JobService {
private static final String TAG = "EJobService";
private boolean jobCancelled = false;
@Override
public boolean onStartJob(JobParameters params) {
getLocation();
return true;
}
private void doBackgroundWork(final JobParameters params) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Log.d(TAG, "run: " + i);
if (jobCancelled) {
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(TAG, "Job finished");
jobFinished(params, false);
}
}).start();
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d(TAG, "Job cancelled before completion");
jobCancelled = true;
return true;
}
public void getLocation() {
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
AndroidManifest.Xml
<service
android:name=".EJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
I am using this code for job scheduler service but the problem is service is not running please tell me what is the problem. i have used this in the Oreo version and this is working fine so please tell me what is the problem.
Getlocation(); crashes app
your code is perfectly working just go and check output in the console.