Home | History | Annotate | Download | only in analytics
      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.analytics;
     18 
     19 import android.os.SystemClock;
     20 
     21 /**
     22  * Times a duration.
     23  */
     24 public final class DurationTimer {
     25     public static final long TIME_NOT_SET = -1;
     26 
     27     private long startTimeMs = TIME_NOT_SET;
     28 
     29     /**
     30      * Returns true if the timer is running.
     31      */
     32     public boolean isRunning() {
     33         return startTimeMs != TIME_NOT_SET;
     34     }
     35 
     36     /**
     37      * Start the timer.
     38      */
     39     public void start() {
     40         startTimeMs = SystemClock.elapsedRealtime();
     41     }
     42 
     43     /**
     44      * Returns the current duration in milliseconds or {@link #TIME_NOT_SET} if the timer is not
     45      * running.
     46      */
     47     public long getDuration() {
     48         return isRunning() ? SystemClock.elapsedRealtime() - startTimeMs : TIME_NOT_SET;
     49     }
     50 
     51     /**
     52      * Stops the timer and resets its value to {@link #TIME_NOT_SET}.
     53      *
     54      * @return the current duration in milliseconds or {@link #TIME_NOT_SET} if the timer is not
     55      * running.
     56      */
     57     public long reset() {
     58         long duration = getDuration();
     59         startTimeMs = TIME_NOT_SET;
     60         return duration;
     61     }
     62 }
     63