1 /* 2 * Copyright (C) 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 android.theme.app; 18 19 import android.content.Context; 20 import android.os.Handler; 21 import android.util.Pair; 22 23 import java.util.ArrayList; 24 import java.util.function.Consumer; 25 import java.util.function.Supplier; 26 27 /** 28 * Runnable that re-posts itself on a handler until either all of the conditions are satisfied 29 * or a retry threshold is exceeded. 30 */ 31 class ConditionCheck implements Runnable { 32 private static final int MAX_RETRIES = 10; 33 private static final int RETRY_DELAY = 500; 34 35 private final Handler mHandler; 36 private final Runnable mOnSuccess; 37 private final Consumer<String> mOnFailure; 38 private final ArrayList<Pair<String, Supplier<Boolean>>> mConditions = new ArrayList<>(); 39 40 private ArrayList<Pair<String, Supplier<Boolean>>> mRemainingConditions = new ArrayList<>(); 41 private int mRemainingRetries; 42 ConditionCheck(Context context, Runnable onSuccess, Consumer<String> onFailure)43 ConditionCheck(Context context, Runnable onSuccess, Consumer<String> onFailure) { 44 mHandler = new Handler(context.getMainLooper()); 45 mOnSuccess = onSuccess; 46 mOnFailure = onFailure; 47 } 48 addCondition(String summary, Supplier<Boolean> condition)49 public ConditionCheck addCondition(String summary, Supplier<Boolean> condition) { 50 mConditions.add(new Pair<>(summary, condition)); 51 return this; 52 } 53 start()54 public void start() { 55 mRemainingConditions = new ArrayList<>(mConditions); 56 mRemainingRetries = 0; 57 58 mHandler.removeCallbacks(this); 59 mHandler.post(this); 60 } 61 cancel()62 public void cancel() { 63 mHandler.removeCallbacks(this); 64 } 65 66 @Override run()67 public void run() { 68 mRemainingConditions.removeIf(condition -> condition.second.get()); 69 if (mRemainingConditions.isEmpty()) { 70 mOnSuccess.run(); 71 } else if (mRemainingRetries < MAX_RETRIES) { 72 mRemainingRetries++; 73 mHandler.removeCallbacks(this); 74 mHandler.postDelayed(this, RETRY_DELAY); 75 } else { 76 final StringBuffer buffer = new StringBuffer("Failed conditions:"); 77 mRemainingConditions.forEach(condition -> 78 buffer.append("\n").append(condition.first)); 79 mOnFailure.accept(buffer.toString()); 80 } 81 } 82 } 83