I have implemented an application in Android that uses JobService to check for updates. I have tested it with some devices: Samsung J3, RedMi 5+, RedMi note pro, MI A2 lite. It is working correctly in J3 but, in other phones that I have tested JobService is not being scheduled if an application is not active or application is not in the recent apps list.
Here is how I have implemented.
MainActivity.java
public static void scheduleJob(Context context) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
JobScheduler js =
(JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo job = new JobInfo.Builder(
MY_BACKGROUND_JOB,
new ComponentName(context, CheckAdService.class))
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true)
.setPeriodic(15 * 60 * 1000)
.build();
int resultCode = js.schedule(job);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
Log.d("JOB", "Scheduled");
} else {
Log.d("JOB", "Not Scheduled");
}
}
}
Service.java
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class CheckAdService extends JobService {
@Override
public boolean onStartJob(JobParameters params) {
Log.d("NetworkAvailable", "Flag No 2");
doBackgroundWork(params);
return true;
}
private void doBackgroundWork(final JobParameters params) {
final Context context = getApplicationContext();
...
IonDB ionDB = new IonDB(CheckAdService.this, "checkStatus");
ionDB.getData(new OnDbData() {
@Override
public void OnDbDataReceived(JsonObject jsonObject, boolean withError) {
...
// after notifying user with news I call jobFinished with rescheduling true option
jobFinished(params, true);
}
});
}
@Override
public boolean onStopJob(JobParameters params) {
Log.d("DBDATA", "Job cancelled before completion");
return true;
}
}
Please correct my implementation of JobService so that it works in all android versions >= LOLLIPOP
.
Considering that I'm new in Android if I made some coding mistakes please let me know any suggestion.