blob: 66c35d903366d939e349df8e63fd41d12310e988 [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;
Aurimas Liutikasba590a62017-04-14 14:51:59 -070020import android.content.Intent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.res.TypedArray;
Roozbeh Pournader241872a2016-12-15 15:17:49 -080022import android.icu.text.MeasureFormat;
23import android.icu.text.MeasureFormat.FormatWidth;
24import android.icu.util.Measure;
25import android.icu.util.MeasureUnit;
Aurimas Liutikasba590a62017-04-14 14:51:59 -070026import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.os.SystemClock;
28import android.text.format.DateUtils;
29import android.util.AttributeSet;
30import android.util.Log;
Simon Dubray814e1f52015-11-05 11:38:40 +010031import android.view.View;
Ashley Rose55f9f922019-01-28 19:29:36 -050032import android.view.inspector.InspectableProperty;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.widget.RemoteViews.RemoteView;
34
Selim Cineked1a33c2016-02-18 17:12:57 -080035import com.android.internal.R;
36
Roozbeh Pournader241872a2016-12-15 15:17:49 -080037import java.util.ArrayList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import java.util.Formatter;
39import java.util.IllegalFormatException;
40import java.util.Locale;
41
42/**
43 * Class that implements a simple timer.
44 * <p>
45 * You can give it a start time in the {@link SystemClock#elapsedRealtime} timebase,
46 * 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 -080047 * time at which you call {@link #start}.
48 *
49 * <p>The timer can also count downward towards the base time by
50 * setting {@link #setCountDown(boolean)} to true.
51 *
52 * <p>By default it will display the current
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053 * timer value in the form "MM:SS" or "H:MM:SS", or you can use {@link #setFormat}
54 * to format the timer value into an arbitrary string.
55 *
56 * @attr ref android.R.styleable#Chronometer_format
Selim Cineked1a33c2016-02-18 17:12:57 -080057 * @attr ref android.R.styleable#Chronometer_countDown
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058 */
59@RemoteView
60public class Chronometer extends TextView {
61 private static final String TAG = "Chronometer";
62
63 /**
64 * A callback that notifies when the chronometer has incremented on its own.
65 */
66 public interface OnChronometerTickListener {
67
68 /**
69 * Notification that the chronometer has changed.
70 */
71 void onChronometerTick(Chronometer chronometer);
72
73 }
74
75 private long mBase;
Dan Sandlera79a7472015-06-05 16:52:22 -040076 private long mNow; // the currently displayed time
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 private boolean mVisible;
78 private boolean mStarted;
79 private boolean mRunning;
80 private boolean mLogged;
81 private String mFormat;
82 private Formatter mFormatter;
83 private Locale mFormatterLocale;
84 private Object[] mFormatterArgs = new Object[1];
85 private StringBuilder mFormatBuilder;
86 private OnChronometerTickListener mOnChronometerTickListener;
87 private StringBuilder mRecycle = new StringBuilder(8);
Selim Cineked1a33c2016-02-18 17:12:57 -080088 private boolean mCountDown;
Aurimas Liutikas99441c52016-10-11 16:48:32 -070089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 /**
91 * Initialize this Chronometer object.
92 * Sets the base to the current time.
93 */
94 public Chronometer(Context context) {
95 this(context, null, 0);
96 }
97
98 /**
99 * Initialize with standard view layout information.
100 * Sets the base to the current time.
101 */
102 public Chronometer(Context context, AttributeSet attrs) {
103 this(context, attrs, 0);
104 }
105
106 /**
107 * Initialize with standard view layout information and style.
108 * Sets the base to the current time.
109 */
Alan Viverette617feb92013-09-09 18:09:13 -0700110 public Chronometer(Context context, AttributeSet attrs, int defStyleAttr) {
111 this(context, attrs, defStyleAttr, 0);
112 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
Alan Viverette617feb92013-09-09 18:09:13 -0700114 public Chronometer(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
115 super(context, attrs, defStyleAttr, defStyleRes);
116
117 final TypedArray a = context.obtainStyledAttributes(
118 attrs, com.android.internal.R.styleable.Chronometer, defStyleAttr, defStyleRes);
Selim Cineked1a33c2016-02-18 17:12:57 -0800119 setFormat(a.getString(R.styleable.Chronometer_format));
120 setCountDown(a.getBoolean(R.styleable.Chronometer_countDown, false));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 a.recycle();
122
123 init();
124 }
125
126 private void init() {
127 mBase = SystemClock.elapsedRealtime();
128 updateText(mBase);
129 }
130
131 /**
Selim Cineked1a33c2016-02-18 17:12:57 -0800132 * Set this view to count down to the base instead of counting up from it.
133 *
134 * @param countDown whether this view should count down
135 *
136 * @see #setBase(long)
137 */
138 @android.view.RemotableViewMethod
139 public void setCountDown(boolean countDown) {
140 mCountDown = countDown;
Selim Cineka2a01712016-05-18 16:59:07 -0700141 updateText(SystemClock.elapsedRealtime());
Selim Cineked1a33c2016-02-18 17:12:57 -0800142 }
143
144 /**
145 * @return whether this view counts down
146 *
147 * @see #setCountDown(boolean)
148 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500149 @InspectableProperty
Selim Cineked1a33c2016-02-18 17:12:57 -0800150 public boolean isCountDown() {
151 return mCountDown;
152 }
153
154 /**
Aurimas Liutikasba590a62017-04-14 14:51:59 -0700155 * @return whether this is the final countdown
156 */
157 public boolean isTheFinalCountDown() {
158 try {
159 getContext().startActivity(
160 new Intent(Intent.ACTION_VIEW, Uri.parse("https://youtu.be/9jK-NcRmVcw"))
161 .addCategory(Intent.CATEGORY_BROWSABLE)
162 .addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT
163 | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT));
164 return true;
165 } catch (Exception e) {
166 return false;
167 }
168 }
169
170 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 * Set the time that the count-up timer is in reference to.
172 *
173 * @param base Use the {@link SystemClock#elapsedRealtime} time base.
174 */
175 @android.view.RemotableViewMethod
176 public void setBase(long base) {
177 mBase = base;
178 dispatchChronometerTick();
179 updateText(SystemClock.elapsedRealtime());
180 }
181
182 /**
183 * Return the base time as set through {@link #setBase}.
184 */
185 public long getBase() {
186 return mBase;
187 }
188
189 /**
190 * Sets the format string used for display. The Chronometer will display
191 * this string, with the first "%s" replaced by the current timer value in
192 * "MM:SS" or "H:MM:SS" form.
193 *
194 * If the format string is null, or if you never call setFormat(), the
195 * Chronometer will simply display the timer value in "MM:SS" or "H:MM:SS"
196 * form.
197 *
198 * @param format the format string.
199 */
200 @android.view.RemotableViewMethod
201 public void setFormat(String format) {
202 mFormat = format;
203 if (format != null && mFormatBuilder == null) {
204 mFormatBuilder = new StringBuilder(format.length() * 2);
205 }
206 }
207
208 /**
209 * Returns the current format string as set through {@link #setFormat}.
210 */
Ashley Rose55f9f922019-01-28 19:29:36 -0500211 @InspectableProperty
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 public String getFormat() {
213 return mFormat;
214 }
215
216 /**
217 * Sets the listener to be called when the chronometer changes.
Aurimas Liutikas99441c52016-10-11 16:48:32 -0700218 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 * @param listener The listener.
220 */
221 public void setOnChronometerTickListener(OnChronometerTickListener listener) {
222 mOnChronometerTickListener = listener;
223 }
224
225 /**
226 * @return The listener (may be null) that is listening for chronometer change
227 * events.
228 */
229 public OnChronometerTickListener getOnChronometerTickListener() {
230 return mOnChronometerTickListener;
231 }
232
233 /**
234 * Start counting up. This does not affect the base as set from {@link #setBase}, just
235 * the view display.
Aurimas Liutikas99441c52016-10-11 16:48:32 -0700236 *
237 * Chronometer works by regularly scheduling messages to the handler, even when the
238 * Widget is not visible. To make sure resource leaks do not occur, the user should
239 * make sure that each start() call has a reciprocal call to {@link #stop}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800240 */
241 public void start() {
242 mStarted = true;
243 updateRunning();
244 }
245
246 /**
247 * Stop counting up. This does not affect the base as set from {@link #setBase}, just
248 * the view display.
Aurimas Liutikas99441c52016-10-11 16:48:32 -0700249 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 * This stops the messages to the handler, effectively releasing resources that would
Aurimas Liutikas99441c52016-10-11 16:48:32 -0700251 * be held as the chronometer is running, via {@link #start}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800252 */
253 public void stop() {
254 mStarted = false;
255 updateRunning();
256 }
257
258 /**
259 * The same as calling {@link #start} or {@link #stop}.
Jeffrey Sharkey3ff7eb92009-04-13 16:57:28 -0700260 * @hide pending API council approval
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800261 */
262 @android.view.RemotableViewMethod
263 public void setStarted(boolean started) {
264 mStarted = started;
265 updateRunning();
266 }
267
268 @Override
269 protected void onDetachedFromWindow() {
270 super.onDetachedFromWindow();
271 mVisible = false;
272 updateRunning();
273 }
274
275 @Override
276 protected void onWindowVisibilityChanged(int visibility) {
277 super.onWindowVisibilityChanged(visibility);
278 mVisible = visibility == VISIBLE;
279 updateRunning();
280 }
281
Simon Dubray814e1f52015-11-05 11:38:40 +0100282 @Override
283 protected void onVisibilityChanged(View changedView, int visibility) {
284 super.onVisibilityChanged(changedView, visibility);
285 updateRunning();
286 }
287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 private synchronized void updateText(long now) {
Dan Sandlera79a7472015-06-05 16:52:22 -0400289 mNow = now;
Selim Cineked1a33c2016-02-18 17:12:57 -0800290 long seconds = mCountDown ? mBase - now : now - mBase;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 seconds /= 1000;
Selim Cineked1a33c2016-02-18 17:12:57 -0800292 boolean negative = false;
293 if (seconds < 0) {
294 seconds = -seconds;
295 negative = true;
296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 String text = DateUtils.formatElapsedTime(mRecycle, seconds);
Selim Cineked1a33c2016-02-18 17:12:57 -0800298 if (negative) {
299 text = getResources().getString(R.string.negative_duration, text);
300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301
302 if (mFormat != null) {
303 Locale loc = Locale.getDefault();
304 if (mFormatter == null || !loc.equals(mFormatterLocale)) {
305 mFormatterLocale = loc;
306 mFormatter = new Formatter(mFormatBuilder, loc);
307 }
308 mFormatBuilder.setLength(0);
309 mFormatterArgs[0] = text;
310 try {
311 mFormatter.format(mFormat, mFormatterArgs);
312 text = mFormatBuilder.toString();
313 } catch (IllegalFormatException ex) {
314 if (!mLogged) {
315 Log.w(TAG, "Illegal format string: " + mFormat);
316 mLogged = true;
317 }
318 }
319 }
320 setText(text);
321 }
322
323 private void updateRunning() {
Simon Dubray814e1f52015-11-05 11:38:40 +0100324 boolean running = mVisible && mStarted && isShown();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800325 if (running != mRunning) {
326 if (running) {
327 updateText(SystemClock.elapsedRealtime());
328 dispatchChronometerTick();
John Reckd0374c62015-10-20 13:25:01 -0700329 postDelayed(mTickRunnable, 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800330 } else {
John Reckd0374c62015-10-20 13:25:01 -0700331 removeCallbacks(mTickRunnable);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 }
333 mRunning = running;
334 }
335 }
John Reckd0374c62015-10-20 13:25:01 -0700336
337 private final Runnable mTickRunnable = new Runnable() {
338 @Override
339 public void run() {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 if (mRunning) {
341 updateText(SystemClock.elapsedRealtime());
342 dispatchChronometerTick();
John Reckd0374c62015-10-20 13:25:01 -0700343 postDelayed(mTickRunnable, 1000);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800344 }
345 }
346 };
347
348 void dispatchChronometerTick() {
349 if (mOnChronometerTickListener != null) {
350 mOnChronometerTickListener.onChronometerTick(this);
351 }
352 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -0800353
Dan Sandlera79a7472015-06-05 16:52:22 -0400354 private static final int MIN_IN_SEC = 60;
355 private static final int HOUR_IN_SEC = MIN_IN_SEC*60;
356 private static String formatDuration(long ms) {
Dan Sandlera79a7472015-06-05 16:52:22 -0400357 int duration = (int) (ms / DateUtils.SECOND_IN_MILLIS);
358 if (duration < 0) {
359 duration = -duration;
360 }
361
362 int h = 0;
363 int m = 0;
364
365 if (duration >= HOUR_IN_SEC) {
366 h = duration / HOUR_IN_SEC;
367 duration -= h * HOUR_IN_SEC;
368 }
369 if (duration >= MIN_IN_SEC) {
370 m = duration / MIN_IN_SEC;
371 duration -= m * MIN_IN_SEC;
372 }
Roozbeh Pournader241872a2016-12-15 15:17:49 -0800373 final int s = duration;
Dan Sandlera79a7472015-06-05 16:52:22 -0400374
Roozbeh Pournader241872a2016-12-15 15:17:49 -0800375 final ArrayList<Measure> measures = new ArrayList<Measure>();
376 if (h > 0) {
377 measures.add(new Measure(h, MeasureUnit.HOUR));
Dan Sandlera79a7472015-06-05 16:52:22 -0400378 }
Roozbeh Pournader241872a2016-12-15 15:17:49 -0800379 if (m > 0) {
380 measures.add(new Measure(m, MeasureUnit.MINUTE));
381 }
382 measures.add(new Measure(s, MeasureUnit.SECOND));
383
384 return MeasureFormat.getInstance(Locale.getDefault(), FormatWidth.WIDE)
Roozbeh Pournader63a13cf2016-12-19 15:56:40 -0800385 .formatMeasures(measures.toArray(new Measure[measures.size()]));
Dan Sandlera79a7472015-06-05 16:52:22 -0400386 }
387
388 @Override
389 public CharSequence getContentDescription() {
390 return formatDuration(mNow - mBase);
391 }
392
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -0800393 @Override
Dianne Hackborna7bb6fb2015-02-03 18:13:40 -0800394 public CharSequence getAccessibilityClassName() {
395 return Chronometer.class.getName();
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -0800396 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800397}