1 /* 2 * Copyright (C) 2024 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 com.android.providers.media.photopicker.sync; 18 19 import android.content.Context; 20 import android.util.Log; 21 22 import androidx.annotation.NonNull; 23 import androidx.annotation.Nullable; 24 import androidx.work.Configuration; 25 import androidx.work.WorkManager; 26 27 import java.util.concurrent.Executor; 28 import java.util.concurrent.Executors; 29 30 public class WorkManagerInitializer { 31 private static final String TAG = "WorkManagerInitializer"; 32 // Thread pool size should be at least equal to the number of unique work requests in 33 // {@link PickerSyncManager} to ensure that any request type is not blocked on other request 34 // types. It is advisable to use unique work requests because in case the number of queued 35 // requests grows, they should not block other work requests. 36 private static final int WORK_MANAGER_THREAD_POOL_SIZE = 6; 37 @Nullable 38 private static volatile Executor sWorkManagerExecutor; 39 40 /** 41 * Initialize the {@link WorkManager} if it is not initialized already. 42 * 43 * @return a {@link WorkManager} object that can be used to run work requests. 44 */ 45 @NonNull getWorkManager(Context mContext)46 public static WorkManager getWorkManager(Context mContext) { 47 if (!WorkManager.isInitialized()) { 48 Log.i(TAG, "Work manager not initialised. Attempting to initialise."); 49 WorkManager.initialize(mContext, getWorkManagerConfiguration()); 50 } 51 return WorkManager.getInstance(mContext); 52 } 53 54 @NonNull getWorkManagerConfiguration()55 private static Configuration getWorkManagerConfiguration() { 56 ensureWorkManagerExecutor(); 57 return new Configuration.Builder() 58 .setMinimumLoggingLevel(Log.INFO) 59 .setExecutor(sWorkManagerExecutor) 60 .build(); 61 } 62 ensureWorkManagerExecutor()63 private static void ensureWorkManagerExecutor() { 64 if (sWorkManagerExecutor == null) { 65 synchronized (WorkManagerInitializer.class) { 66 if (sWorkManagerExecutor == null) { 67 sWorkManagerExecutor = Executors 68 .newFixedThreadPool(WORK_MANAGER_THREAD_POOL_SIZE); 69 } 70 } 71 } 72 } 73 } 74