1/*
2 * Copyright (C) 2013 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
17package com.android.incallui;
18
19import com.google.common.base.Preconditions;
20
21import android.os.Handler;
22import android.os.SystemClock;
23
24/**
25 * Helper class used to keep track of events requiring regular intervals.
26 */
27public class CallTimer extends Handler {
28    private Runnable mInternalCallback;
29    private Runnable mCallback;
30    private long mLastReportedTime;
31    private long mInterval;
32    private boolean mRunning;
33
34    public CallTimer(Runnable callback) {
35        Preconditions.checkNotNull(callback);
36
37        mInterval = 0;
38        mLastReportedTime = 0;
39        mRunning = false;
40        mCallback = callback;
41        mInternalCallback = new CallTimerCallback();
42    }
43
44    public boolean start(long interval) {
45        if (interval <= 0) {
46            return false;
47        }
48
49        // cancel any previous timer
50        cancel();
51
52        mInterval = interval;
53        mLastReportedTime = SystemClock.uptimeMillis();
54
55        mRunning = true;
56        periodicUpdateTimer();
57
58        return true;
59    }
60
61    public void cancel() {
62        removeCallbacks(mInternalCallback);
63        mRunning = false;
64    }
65
66    private void periodicUpdateTimer() {
67        if (!mRunning) {
68            return;
69        }
70
71        final long now = SystemClock.uptimeMillis();
72        long nextReport = mLastReportedTime + mInterval;
73        while (now >= nextReport) {
74            nextReport += mInterval;
75        }
76
77        postAtTime(mInternalCallback, nextReport);
78        mLastReportedTime = nextReport;
79
80        // Run the callback
81        mCallback.run();
82    }
83
84    private class CallTimerCallback implements Runnable {
85        @Override
86        public void run() {
87            periodicUpdateTimer();
88        }
89    }
90}
91