使用FirebaseJobDispatcher的Android 8.0后台计划任务

时间:2018-09-25 22:00:38

标签: android background scheduled-tasks firebase-job-dispatcher

我有一个应用程序,只要有互联网连接,就可以使用FirebaseJobDispatcher运行计划的任务。它适用于Nougat,但在应用后台执行限制后,我不知道如何在Oreo 8.0中修复它。 https://developer.android.com/about/versions/oreo/background 我的时间表代码是这个

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;
}

和MyService.class是

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;
}
}

我没有在清单中添加任何特殊许可以使用较低级别的API(<26)。

0 个答案:

没有答案