1 /* 2 * Copyright 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package androidx.work.impl.background.systemalarm; 18 19 import android.content.Context; 20 import android.content.Intent; 21 import android.support.annotation.NonNull; 22 import android.support.annotation.RestrictTo; 23 import android.util.Log; 24 25 import androidx.work.impl.Scheduler; 26 import androidx.work.impl.model.WorkSpec; 27 28 /** 29 * A {@link Scheduler} that schedules work using {@link android.app.AlarmManager}. 30 * 31 * @hide 32 */ 33 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 34 public class SystemAlarmScheduler implements Scheduler { 35 36 private static final String TAG = "SystemAlarmScheduler"; 37 38 private final Context mContext; 39 40 public SystemAlarmScheduler(@NonNull Context context) { 41 mContext = context.getApplicationContext(); 42 } 43 44 @Override 45 public void schedule(WorkSpec... workSpecs) { 46 for (WorkSpec workSpec : workSpecs) { 47 scheduleWorkSpec(workSpec); 48 } 49 } 50 51 @Override 52 public void cancel(@NonNull String workSpecId) { 53 Intent cancelIntent = CommandHandler.createStopWorkIntent(mContext, workSpecId); 54 mContext.startService(cancelIntent); 55 } 56 57 /** 58 * Periodic work is rescheduled using one-time alarms after each run. This allows the delivery 59 * times to drift to guarantee that the interval duration always elapses between alarms. 60 */ 61 private void scheduleWorkSpec(@NonNull WorkSpec workSpec) { 62 Log.d(TAG, String.format("Scheduling work with workSpecId %s", workSpec.id)); 63 Intent scheduleIntent = CommandHandler.createScheduleWorkIntent(mContext, workSpec.id); 64 mContext.startService(scheduleIntent); 65 } 66 } 67