1 /* 2 * Copyright (C) 2023 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.devicelockcontroller; 18 19 import android.content.Context; 20 21 import androidx.annotation.NonNull; 22 import androidx.annotation.Nullable; 23 import androidx.work.ListenableWorker; 24 import androidx.work.WorkerFactory; 25 import androidx.work.WorkerParameters; 26 27 import com.android.devicelockcontroller.util.LogUtil; 28 29 import com.google.common.util.concurrent.ListeningExecutorService; 30 import com.google.common.util.concurrent.MoreExecutors; 31 32 import java.lang.reflect.InvocationTargetException; 33 import java.util.concurrent.Executors; 34 35 /** A factory which produces {@link ListenableWorker}s with parameters. */ 36 public final class DeviceLockControllerWorkerFactory extends WorkerFactory { 37 private static final String TAG = "DeviceLockControllerWorkerFactory"; 38 39 private static final ListeningExecutorService sExecutorService = 40 MoreExecutors.listeningDecorator(Executors.newCachedThreadPool()); 41 42 @Nullable 43 @Override createWorker( @onNull Context context, @NonNull String workerClassName, @NonNull WorkerParameters workerParameters)44 public ListenableWorker createWorker( 45 @NonNull Context context, 46 @NonNull String workerClassName, 47 @NonNull WorkerParameters workerParameters) { 48 ListenableWorker worker = null; 49 Class<?> clazz = null; 50 try { 51 clazz = Class.forName(workerClassName); 52 } catch (ClassNotFoundException e) { 53 LogUtil.e(TAG, "Can not find class for name: " + workerClassName, e); 54 } 55 56 if (clazz != null) { 57 try { 58 worker = (ListenableWorker) clazz.getConstructor( 59 Context.class, 60 WorkerParameters.class, 61 ListeningExecutorService.class) 62 .newInstance(context, workerParameters, sExecutorService); 63 } catch (InstantiationException | IllegalAccessException 64 | InvocationTargetException | NoSuchMethodException e) { 65 // Unable to create the instance by this WorkerFactory 66 LogUtil.i(TAG, "Delegating to default WorkerFactory to create: " + workerClassName, 67 e); 68 } 69 } 70 return worker; 71 } 72 } 73