Android 8.0 background scheduled task with FirebaseJobDispatcher

84 Views Asked by At

I have an app that whenever there is internet connection runs a scheduled task using FirebaseJobDispatcher. It works fine up to Nougat but I don't know how to fix it in Oreo 8.0 after background execution limits applied. https://developer.android.com/about/versions/oreo/background My code for schedule is this

synchronized public static void scheduleReminder(@NonNull final Context context) {
    if (sInitialized) return;
    Driver driver = new GooglePlayDriver(context);
    FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(driver);
    Job constraintReminderJob = dispatcher.newJobBuilder()
            .setService(MyService.class)
            .setTag(REMINDER_JOB_TAG)
            .setRecurring(true)
            .setConstraints(Constraint.ON_ANY_NETWORK)
            .setLifetime(Lifetime.FOREVER)
            .setTrigger(Trigger.executionWindow(0,
                    REMINDER_INTERVAL_SECONDS + SYNC_FLEXTIME_SECONDS
                    ))
            .setReplaceCurrent(true)
         .build();
    dispatcher.schedule(constraintReminderJob);
    sInitialized = true;
}

and MyService.class is

public class MyService extends JobService {
private AsyncTask mBackgroundTask;
@Override
public boolean onStartJob(final JobParameters jobParameters) {
    mBackgroundTask = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] params) {
             HttpsURLConnection urlConnection =(HttpsURLConnection) url.openConnection();
   //etc
        }

        @Override
        protected void onPostExecute(Object o) {
            jobFinished(jobParameters, false);
        }
    };
    mBackgroundTask.execute();

    return true;
}
@Override
public boolean onStopJob(JobParameters jobParameters) {
    if (mBackgroundTask != null) mBackgroundTask.cancel(true);
    return true;
}
}

I haven't added any special permitions in manifest for working in lower level API's (<26).

0

There are 0 best solutions below