1 /* 2 * Copyright 2019 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.gcm; 18 19 import android.content.Context; 20 21 import androidx.work.Clock; 22 import androidx.work.Logger; 23 import androidx.work.impl.Scheduler; 24 import androidx.work.impl.model.WorkSpec; 25 26 import com.google.android.gms.common.ConnectionResult; 27 import com.google.android.gms.common.GoogleApiAvailability; 28 import com.google.android.gms.gcm.GcmNetworkManager; 29 import com.google.android.gms.gcm.Task; 30 31 import org.jspecify.annotations.NonNull; 32 33 /** 34 * The {@link androidx.work.WorkManager} scheduler which uses 35 * {@link com.google.android.gms.gcm.GcmNetworkManager}. 36 */ 37 public class GcmScheduler implements Scheduler { 38 private static final String TAG = Logger.tagWithPrefix("GcmScheduler"); 39 40 private final GcmNetworkManager mNetworkManager; 41 private final GcmTaskConverter mTaskConverter; 42 GcmScheduler(@onNull Context context, @NonNull Clock clock)43 public GcmScheduler(@NonNull Context context, @NonNull Clock clock) { 44 boolean isPlayServicesAvailable = GoogleApiAvailability.getInstance() 45 .isGooglePlayServicesAvailable(context) == ConnectionResult.SUCCESS; 46 if (!isPlayServicesAvailable) { 47 throw new IllegalStateException("Google Play Services not available"); 48 } 49 mNetworkManager = GcmNetworkManager.getInstance(context); 50 mTaskConverter = new GcmTaskConverter(clock); 51 } 52 53 @Override schedule(WorkSpec @onNull .... workSpecs)54 public void schedule(WorkSpec @NonNull ... workSpecs) { 55 for (WorkSpec workSpec : workSpecs) { 56 Task task = mTaskConverter.convert(workSpec); 57 Logger.get().debug(TAG, "Scheduling " + workSpec + "with " + task); 58 mNetworkManager.schedule(task); 59 } 60 } 61 62 @Override cancel(@onNull String workSpecId)63 public void cancel(@NonNull String workSpecId) { 64 Logger.get().debug(TAG, "Cancelling " + workSpecId); 65 mNetworkManager.cancelTask(workSpecId, WorkManagerGcmService.class); 66 } 67 68 @Override hasLimitedSchedulingSlots()69 public boolean hasLimitedSchedulingSlots() { 70 return true; 71 } 72 } 73