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.utils.taskexecutor; 18 19 import android.support.annotation.Nullable; 20 import android.support.annotation.RestrictTo; 21 22 /** 23 * A static class that serves as a central point to execute common tasks in WorkManager. 24 * This is used for business logic internal to WorkManager and NOT for worker processing. 25 * Adapted from {@link android.arch.core.executor.ArchTaskExecutor} 26 * @hide 27 */ 28 29 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 30 public class WorkManagerTaskExecutor implements TaskExecutor { 31 private static WorkManagerTaskExecutor sInstance; 32 private final TaskExecutor mDefaultTaskExecutor = new DefaultTaskExecutor(); 33 private TaskExecutor mTaskExecutor = mDefaultTaskExecutor; 34 35 /** 36 * Returns an instance of the task executor. 37 * @return The singleton WorkManagerTaskExecutor. 38 */ 39 public static synchronized WorkManagerTaskExecutor getInstance() { 40 if (sInstance == null) { 41 sInstance = new WorkManagerTaskExecutor(); 42 } 43 return sInstance; 44 } 45 46 private WorkManagerTaskExecutor() { 47 } 48 49 /** 50 * Overrides the task executor used by {@link androidx.work.impl.WorkManagerImpl}. 51 * 52 * @param taskExecutor The instance of the {@link TaskExecutor}. 53 */ 54 public void setTaskExecutor(@Nullable TaskExecutor taskExecutor) { 55 mTaskExecutor = taskExecutor == null ? mDefaultTaskExecutor : taskExecutor; 56 } 57 58 @Override 59 public void postToMainThread(Runnable r) { 60 mTaskExecutor.postToMainThread(r); 61 } 62 63 @Override 64 public void executeOnBackgroundThread(Runnable r) { 65 mTaskExecutor.executeOnBackgroundThread(r); 66 } 67 } 68