1 /* 2 * Copyright (C) 2015 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.tv.util; 18 19 import android.os.SystemClock; 20 import android.util.Log; 21 22 import com.android.tv.common.BuildConfig; 23 24 /** 25 * Times a duration. 26 */ 27 public final class DurationTimer { 28 private static final String TAG = "DurationTimer"; 29 public static final long TIME_NOT_SET = -1; 30 31 private long mStartTimeMs = TIME_NOT_SET; 32 private String mTag = TAG; 33 private boolean mLogEngOnly; 34 DurationTimer()35 public DurationTimer() { } 36 DurationTimer(String tag, boolean logEngOnly)37 public DurationTimer(String tag, boolean logEngOnly) { 38 mTag = tag; 39 mLogEngOnly = logEngOnly; 40 } 41 42 /** 43 * Returns true if the timer is running. 44 */ isRunning()45 public boolean isRunning() { 46 return mStartTimeMs != TIME_NOT_SET; 47 } 48 49 /** 50 * Start the timer. 51 */ start()52 public void start() { 53 mStartTimeMs = SystemClock.elapsedRealtime(); 54 } 55 56 /** 57 * Returns true if timer is started. 58 */ isStarted()59 public boolean isStarted() { 60 return mStartTimeMs != TIME_NOT_SET; 61 } 62 63 /** 64 * Returns the current duration in milliseconds or {@link #TIME_NOT_SET} if the timer is not 65 * running. 66 */ getDuration()67 public long getDuration() { 68 return isRunning() ? SystemClock.elapsedRealtime() - mStartTimeMs : TIME_NOT_SET; 69 } 70 71 /** 72 * Stops the timer and resets its value to {@link #TIME_NOT_SET}. 73 * 74 * @return the current duration in milliseconds or {@link #TIME_NOT_SET} if the timer is not 75 * running. 76 */ reset()77 public long reset() { 78 long duration = getDuration(); 79 mStartTimeMs = TIME_NOT_SET; 80 return duration; 81 } 82 83 /** 84 * Adds information and duration time to the log. 85 */ log(String message)86 public void log(String message) { 87 if (isRunning() && (!mLogEngOnly || BuildConfig.ENG)) { 88 Log.i(mTag, message + " : " + getDuration() + "ms"); 89 } 90 } 91 } 92