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 20 import androidx.annotation.MainThread; 21 import androidx.work.Logger; 22 import androidx.work.impl.WorkManagerImpl; 23 import androidx.work.impl.utils.WorkTimer; 24 25 import com.google.android.gms.gcm.GcmTaskService; 26 import com.google.android.gms.gcm.TaskParams; 27 28 import org.jspecify.annotations.NonNull; 29 30 /** 31 * The {@link GcmTaskService} responsible for handling requests for executing 32 * {@link androidx.work.WorkRequest}s. 33 */ 34 public class WorkManagerGcmService extends GcmTaskService { 35 36 private static final String TAG = "WorkManagerGcmService"; 37 38 private boolean mIsShutdown; 39 private WorkManagerGcmDispatcher mGcmDispatcher; 40 41 @Override onCreate()42 public void onCreate() { 43 super.onCreate(); 44 initializeDispatcher(); 45 } 46 47 @Override 48 @MainThread onInitializeTasks()49 public void onInitializeTasks() { 50 checkDispatcher(); 51 // Reschedule all eligible work, as all tasks have been cleared in GCMNetworkManager. 52 // This typically happens after an upgrade. 53 mGcmDispatcher.onInitializeTasks(); 54 } 55 56 @Override onRunTask(@onNull TaskParams taskParams)57 public int onRunTask(@NonNull TaskParams taskParams) { 58 checkDispatcher(); 59 return mGcmDispatcher.onRunTask(taskParams); 60 } 61 62 @Override onDestroy()63 public void onDestroy() { 64 super.onDestroy(); 65 mIsShutdown = true; 66 } 67 68 @MainThread checkDispatcher()69 private void checkDispatcher() { 70 if (mIsShutdown) { 71 Logger.get().debug(TAG, "Re-initializing dispatcher after a request to shutdown"); 72 initializeDispatcher(); 73 } 74 } 75 76 @MainThread initializeDispatcher()77 private void initializeDispatcher() { 78 mIsShutdown = false; 79 WorkManagerImpl workManager = WorkManagerImpl.getInstance(getApplicationContext()); 80 WorkTimer timer = new WorkTimer(workManager.getConfiguration().getRunnableScheduler()); 81 mGcmDispatcher = new WorkManagerGcmDispatcher(workManager, timer); 82 } 83 } 84