blob: 3421790894ed532b2f44e3af21c03375ad17289d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 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 android.widget;
18
19import android.content.Context;
Dan Sandlera79a7472015-06-05 16:52:22 -040020import android.content.res.Resources;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.res.TypedArray;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.os.SystemClock;
23import android.text.format.DateUtils;
24import android.util.AttributeSet;
25import android.util.Log;
26import android.widget.RemoteViews.RemoteView;
27
Selim Cineked1a33c2016-02-18 17:12:57 -080028import com.android.internal.R;
29
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import java.util.Formatter;
31import java.util.IllegalFormatException;
32import java.util.Locale;
33
34/**
35 * Class that implements a simple timer.
36 * <p>
37 * You can give it a start time in the {@link SystemClock#elapsedRealtime} timebase,
38 * and it counts up from that, or if you don't give it a base time, it will use the
Selim Cineked1a33c2016-02-18 17:12:57 -080039 * time at which you call {@link #start}.
40 *
41 * <p>The timer can also count downward towards the base time by
42 * setting {@link #setCountDown(boolean)} to true.
43 *
44 * <p>By default it will display the current
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045 * timer value in the form "MM:SS" or "H:MM:SS", or you can use {@link #setFormat}
46 * to format the timer value into an arbitrary string.
47 *
48 * @attr ref android.R.styleable#Chronometer_format
Selim Cineked1a33c2016-02-18 17:12:57 -080049 * @attr ref android.R.styleable#Chronometer_countDown
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050 */
51@RemoteView
52public class Chronometer extends TextView {
53 private static final String TAG = "Chronometer";
54
55 /**
56 * A callback that notifies when the chronometer has incremented on its own.
57 */
58 public interface OnChronometerTickListener {
59
60 /**
61 * Notification that the chronometer has changed.
62 */
63 void onChronometerTick(Chronometer chronometer);
64
65 }
66
67 private long mBase;
Dan Sandlera79a7472015-06-05 16:52:22 -040068 private long mNow; // the currently displayed time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 private boolean mVisible;
70 private boolean mStarted;
71 private boolean mRunning;
72 private boolean mLogged;
73 private String mFormat;
74 private Formatter mFormatter;
75 private Locale mFormatterLocale;
76 private Object[] mFormatterArgs = new Object[1];
77 private StringBuilder mFormatBuilder;
78 private OnChronometerTickListener mOnChronometerTickListener;
79 private StringBuilder mRecycle = new StringBuilder(8);
Selim Cineked1a33c2016-02-18 17:12:57 -080080 private boolean mCountDown;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082 /**
83 * Initialize this Chronometer object.
84 * Sets the base to the current time.
85 */
86 public Chronometer(Context context) {
87 this(context, null, 0);
88 }
89
90 /**
91 * Initialize with standard view layout information.
92 * Sets the base to the current time.
93 */
94 public Chronometer(Context context, AttributeSet attrs) {
95 this(context, attrs, 0);
96 }
97
98 /**
99 * Initialize with standard view layout information and style.
100 * Sets the base to the current time.
101 */
Alan Viverette617feb92013-09-09 18:09:13 -0700102 public Chronometer(Context context, AttributeSet attrs, int defStyleAttr) {
103 this(context, attrs, defStyleAttr, 0);
104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Alan Viverette617feb92013-09-09 18:09:13 -0700106 public Chronometer(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
107 super(context, attrs, defStyleAttr, defStyleRes);
108
109 final TypedArray a = context.obtainStyledAttributes(
110 attrs, com.android.internal.R.styleable.Chronometer, defStyleAttr, defStyleRes);
Selim Cineked1a33c2016-02-18 17:12:57 -0800111 setFormat(a.getString(R.styleable.Chronometer_format));
112 setCountDown(a.getBoolean(R.styleable.Chronometer_countDown, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 a.recycle();
114
115 init();
116 }
117
118 private void init() {
119 mBase = SystemClock.elapsedRealtime();
120 updateText(mBase);
121 }
122
123 /**
Selim Cineked1a33c2016-02-18 17:12:57 -0800124 * Set this view to count down to the base instead of counting up from it.
125 *
126 * @param countDown whether this view should count down
127 *
128 * @see #setBase(long)
129 */
130 @android.view.RemotableViewMethod
131 public void setCountDown(boolean countDown) {
132 mCountDown = countDown;
133 }
134
135 /**
136 * @return whether this view counts down
137 *
138 * @see #setCountDown(boolean)
139 */
140 public boolean isCountDown() {
141 return mCountDown;
142 }
143
144 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145 * Set the time that the count-up timer is in reference to.
146 *
147 * @param base Use the {@link SystemClock#elapsedRealtime} time base.
148 */
149 @android.view.RemotableViewMethod
150 public void setBase(long base) {
151 mBase = base;
152 dispatchChronometerTick();
153 updateText(SystemClock.elapsedRealtime());
154 }
155
156 /**
157 * Return the base time as set through {@link #setBase}.
158 */
159 public long getBase() {
160 return mBase;
161 }
162
163 /**
164 * Sets the format string used for display. The Chronometer will display
165 * this string, with the first "%s" replaced by the current timer value in
166 * "MM:SS" or "H:MM:SS" form.
167 *
168 * If the format string is null, or if you never call setFormat(), the
169 * Chronometer will simply display the timer value in "MM:SS" or "H:MM:SS"
170 * form.
171 *
172 * @param format the format string.
173 */
174 @android.view.RemotableViewMethod
175 public void setFormat(String format) {
176 mFormat = format;
177 if (format != null && mFormatBuilder == null) {
178 mFormatBuilder = new StringBuilder(format.length() * 2);
179 }
180 }
181
182 /**
183 * Returns the current format string as set through {@link #setFormat}.
184 */
185 public String getFormat() {
186 return mFormat;
187 }
188
189 /**
190 * Sets the listener to be called when the chronometer changes.
191 *
192 * @param listener The listener.
193 */
194 public void setOnChronometerTickListener(OnChronometerTickListener listener) {
195 mOnChronometerTickListener = listener;
196 }
197
198 /**
199 * @return The listener (may be null) that is listening for chronometer change
200 * events.
201 */
202 public OnChronometerTickListener getOnChronometerTickListener() {
203 return mOnChronometerTickListener;
204 }
205
206 /**
207 * Start counting up. This does not affect the base as set from {@link #setBase}, just
208 * the view display.
209 *
210 * Chronometer works by regularly scheduling messages to the handler, even when the
211 * Widget is not visible. To make sure resource leaks do not occur, the user should
212 * make sure that each start() call has a reciprocal call to {@link #stop}.
213 */
214 public void start() {
215 mStarted = true;
216 updateRunning();
217 }
218
219 /**
220 * Stop counting up. This does not affect the base as set from {@link #setBase}, just
221 * the view display.
222 *
223 * This stops the messages to the handler, effectively releasing resources that would
224 * be held as the chronometer is running, via {@link #start}.
225 */
226 public void stop() {
227 mStarted = false;
228 updateRunning();
229 }
230
231 /**
232 * The same as calling {@link #start} or {@link #stop}.
Jeffrey Sharkey3ff7eb92009-04-13 16:57:28 -0700233 * @hide pending API council approval
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 */
235 @android.view.RemotableViewMethod
236 public void setStarted(boolean started) {
237 mStarted = started;
238 updateRunning();
239 }
240
241 @Override
242 protected void onDetachedFromWindow() {
243 super.onDetachedFromWindow();
244 mVisible = false;
245 updateRunning();
246 }
247
248 @Override
249 protected void onWindowVisibilityChanged(int visibility) {
250 super.onWindowVisibilityChanged(visibility);
251 mVisible = visibility == VISIBLE;
252 updateRunning();
253 }
254
255 private synchronized void updateText(long now) {
Dan Sandlera79a7472015-06-05 16:52:22 -0400256 mNow = now;
Selim Cineked1a33c2016-02-18 17:12:57 -0800257 long seconds = mCountDown ? mBase - now : now - mBase;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800258 seconds /= 1000;
Selim Cineked1a33c2016-02-18 17:12:57 -0800259 boolean negative = false;
260 if (seconds < 0) {
261 seconds = -seconds;
262 negative = true;
263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800264 String text = DateUtils.formatElapsedTime(mRecycle, seconds);
Selim Cineked1a33c2016-02-18 17:12:57 -0800265 if (negative) {
266 text = getResources().getString(R.string.negative_duration, text);
267 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800268
269 if (mFormat != null) {
270 Locale loc = Locale.getDefault();
271 if (mFormatter == null || !loc.equals(mFormatterLocale)) {
272 mFormatterLocale = loc;
273 mFormatter = new Formatter(mFormatBuilder, loc);
274 }
275 mFormatBuilder.setLength(0);
276 mFormatterArgs[0] = text;
277 try {
278 mFormatter.format(mFormat, mFormatterArgs);
279 text = mFormatBuilder.toString();
280 } catch (IllegalFormatException ex) {
281 if (!mLogged) {
282 Log.w(TAG, "Illegal format string: " + mFormat);
283 mLogged = true;
284 }
285 }
286 }
287 setText(text);
288 }
289
290 private void updateRunning() {
291 boolean running = mVisible && mStarted;
292 if (running != mRunning) {
293 if (running) {
294 updateText(SystemClock.elapsedRealtime());
295 dispatchChronometerTick();
John Reckd0374c62015-10-20 13:25:01 -0700296 postDelayed(mTickRunnable, 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 } else {
John Reckd0374c62015-10-20 13:25:01 -0700298 removeCallbacks(mTickRunnable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 }
300 mRunning = running;
301 }
302 }
John Reckd0374c62015-10-20 13:25:01 -0700303
304 private final Runnable mTickRunnable = new Runnable() {
305 @Override
306 public void run() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 if (mRunning) {
308 updateText(SystemClock.elapsedRealtime());
309 dispatchChronometerTick();
John Reckd0374c62015-10-20 13:25:01 -0700310 postDelayed(mTickRunnable, 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800311 }
312 }
313 };
314
315 void dispatchChronometerTick() {
316 if (mOnChronometerTickListener != null) {
317 mOnChronometerTickListener.onChronometerTick(this);
318 }
319 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -0800320
Dan Sandlera79a7472015-06-05 16:52:22 -0400321 private static final int MIN_IN_SEC = 60;
322 private static final int HOUR_IN_SEC = MIN_IN_SEC*60;
323 private static String formatDuration(long ms) {
324 final Resources res = Resources.getSystem();
325 final StringBuilder text = new StringBuilder();
326
327 int duration = (int) (ms / DateUtils.SECOND_IN_MILLIS);
328 if (duration < 0) {
329 duration = -duration;
330 }
331
332 int h = 0;
333 int m = 0;
334
335 if (duration >= HOUR_IN_SEC) {
336 h = duration / HOUR_IN_SEC;
337 duration -= h * HOUR_IN_SEC;
338 }
339 if (duration >= MIN_IN_SEC) {
340 m = duration / MIN_IN_SEC;
341 duration -= m * MIN_IN_SEC;
342 }
343 int s = duration;
344
345 try {
346 if (h > 0) {
347 text.append(res.getQuantityString(
348 com.android.internal.R.plurals.duration_hours, h, h));
349 }
350 if (m > 0) {
351 if (text.length() > 0) {
352 text.append(' ');
353 }
354 text.append(res.getQuantityString(
355 com.android.internal.R.plurals.duration_minutes, m, m));
356 }
357
358 if (text.length() > 0) {
359 text.append(' ');
360 }
361 text.append(res.getQuantityString(
362 com.android.internal.R.plurals.duration_seconds, s, s));
363 } catch (Resources.NotFoundException e) {
364 // Ignore; plurals throws an exception for an untranslated quantity for a given locale.
365 return null;
366 }
367 return text.toString();
368 }
369
370 @Override
371 public CharSequence getContentDescription() {
372 return formatDuration(mNow - mBase);
373 }
374
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -0800375 @Override
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -0800376 public CharSequence getAccessibilityClassName() {
377 return Chronometer.class.getName();
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -0800378 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800379}