Jeff Sharkey | 9911a28 | 2018-02-14 22:29:11 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2018 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.os; |
| 18 | |
| 19 | import android.util.Log; |
| 20 | |
| 21 | import java.time.Clock; |
| 22 | import java.time.DateTimeException; |
| 23 | import java.time.ZoneId; |
| 24 | import java.util.Arrays; |
| 25 | |
| 26 | /** |
| 27 | * Single {@link Clock} that will return the best available time from a set of |
| 28 | * prioritized {@link Clock} instances. |
| 29 | * <p> |
| 30 | * For example, when {@link SystemClock#currentNetworkTimeClock()} isn't able to |
| 31 | * provide the time, this class could use {@link Clock#systemUTC()} instead. |
| 32 | * |
| 33 | * @hide |
| 34 | */ |
| 35 | public class BestClock extends SimpleClock { |
| 36 | private static final String TAG = "BestClock"; |
| 37 | |
| 38 | private final Clock[] clocks; |
| 39 | |
| 40 | public BestClock(ZoneId zone, Clock... clocks) { |
| 41 | super(zone); |
| 42 | this.clocks = clocks; |
| 43 | } |
| 44 | |
| 45 | @Override |
| 46 | public long millis() { |
| 47 | for (Clock clock : clocks) { |
| 48 | try { |
| 49 | return clock.millis(); |
| 50 | } catch (DateTimeException e) { |
| 51 | // Ignore and attempt the next clock |
| 52 | Log.w(TAG, e.toString()); |
| 53 | } |
| 54 | } |
| 55 | throw new DateTimeException( |
| 56 | "No clocks in " + Arrays.toString(clocks) + " were able to provide time"); |
| 57 | } |
| 58 | } |