blob: f8d482dfd5ede2555aa767817bf40337e7dfed8f [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;
20import android.content.res.TypedArray;
21import android.graphics.Canvas;
22import android.os.Handler;
23import android.os.Message;
24import android.os.SystemClock;
25import android.text.format.DateUtils;
26import android.util.AttributeSet;
27import android.util.Log;
Daniel Sandlera2985ed2012-04-03 16:42:00 -040028import android.util.Slog;
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -080029import android.view.accessibility.AccessibilityEvent;
30import android.view.accessibility.AccessibilityNodeInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.widget.RemoteViews.RemoteView;
32
33import java.util.Formatter;
34import java.util.IllegalFormatException;
35import java.util.Locale;
36
37/**
38 * Class that implements a simple timer.
39 * <p>
40 * You can give it a start time in the {@link SystemClock#elapsedRealtime} timebase,
41 * and it counts up from that, or if you don't give it a base time, it will use the
42 * time at which you call {@link #start}. By default it will display the current
43 * timer value in the form "MM:SS" or "H:MM:SS", or you can use {@link #setFormat}
44 * to format the timer value into an arbitrary string.
45 *
46 * @attr ref android.R.styleable#Chronometer_format
47 */
48@RemoteView
49public class Chronometer extends TextView {
50 private static final String TAG = "Chronometer";
51
52 /**
53 * A callback that notifies when the chronometer has incremented on its own.
54 */
55 public interface OnChronometerTickListener {
56
57 /**
58 * Notification that the chronometer has changed.
59 */
60 void onChronometerTick(Chronometer chronometer);
61
62 }
63
64 private long mBase;
65 private boolean mVisible;
66 private boolean mStarted;
67 private boolean mRunning;
68 private boolean mLogged;
69 private String mFormat;
70 private Formatter mFormatter;
71 private Locale mFormatterLocale;
72 private Object[] mFormatterArgs = new Object[1];
73 private StringBuilder mFormatBuilder;
74 private OnChronometerTickListener mOnChronometerTickListener;
75 private StringBuilder mRecycle = new StringBuilder(8);
76
77 private static final int TICK_WHAT = 2;
78
79 /**
80 * Initialize this Chronometer object.
81 * Sets the base to the current time.
82 */
83 public Chronometer(Context context) {
84 this(context, null, 0);
85 }
86
87 /**
88 * Initialize with standard view layout information.
89 * Sets the base to the current time.
90 */
91 public Chronometer(Context context, AttributeSet attrs) {
92 this(context, attrs, 0);
93 }
94
95 /**
96 * Initialize with standard view layout information and style.
97 * Sets the base to the current time.
98 */
Alan Viverette617feb92013-09-09 18:09:13 -070099 public Chronometer(Context context, AttributeSet attrs, int defStyleAttr) {
100 this(context, attrs, defStyleAttr, 0);
101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
Alan Viverette617feb92013-09-09 18:09:13 -0700103 public Chronometer(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
104 super(context, attrs, defStyleAttr, defStyleRes);
105
106 final TypedArray a = context.obtainStyledAttributes(
107 attrs, com.android.internal.R.styleable.Chronometer, defStyleAttr, defStyleRes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 setFormat(a.getString(com.android.internal.R.styleable.Chronometer_format));
109 a.recycle();
110
111 init();
112 }
113
114 private void init() {
115 mBase = SystemClock.elapsedRealtime();
116 updateText(mBase);
117 }
118
119 /**
120 * Set the time that the count-up timer is in reference to.
121 *
122 * @param base Use the {@link SystemClock#elapsedRealtime} time base.
123 */
124 @android.view.RemotableViewMethod
125 public void setBase(long base) {
126 mBase = base;
127 dispatchChronometerTick();
128 updateText(SystemClock.elapsedRealtime());
129 }
130
131 /**
132 * Return the base time as set through {@link #setBase}.
133 */
134 public long getBase() {
135 return mBase;
136 }
137
138 /**
139 * Sets the format string used for display. The Chronometer will display
140 * this string, with the first "%s" replaced by the current timer value in
141 * "MM:SS" or "H:MM:SS" form.
142 *
143 * If the format string is null, or if you never call setFormat(), the
144 * Chronometer will simply display the timer value in "MM:SS" or "H:MM:SS"
145 * form.
146 *
147 * @param format the format string.
148 */
149 @android.view.RemotableViewMethod
150 public void setFormat(String format) {
151 mFormat = format;
152 if (format != null && mFormatBuilder == null) {
153 mFormatBuilder = new StringBuilder(format.length() * 2);
154 }
155 }
156
157 /**
158 * Returns the current format string as set through {@link #setFormat}.
159 */
160 public String getFormat() {
161 return mFormat;
162 }
163
164 /**
165 * Sets the listener to be called when the chronometer changes.
166 *
167 * @param listener The listener.
168 */
169 public void setOnChronometerTickListener(OnChronometerTickListener listener) {
170 mOnChronometerTickListener = listener;
171 }
172
173 /**
174 * @return The listener (may be null) that is listening for chronometer change
175 * events.
176 */
177 public OnChronometerTickListener getOnChronometerTickListener() {
178 return mOnChronometerTickListener;
179 }
180
181 /**
182 * Start counting up. This does not affect the base as set from {@link #setBase}, just
183 * the view display.
184 *
185 * Chronometer works by regularly scheduling messages to the handler, even when the
186 * Widget is not visible. To make sure resource leaks do not occur, the user should
187 * make sure that each start() call has a reciprocal call to {@link #stop}.
188 */
189 public void start() {
190 mStarted = true;
191 updateRunning();
192 }
193
194 /**
195 * Stop counting up. This does not affect the base as set from {@link #setBase}, just
196 * the view display.
197 *
198 * This stops the messages to the handler, effectively releasing resources that would
199 * be held as the chronometer is running, via {@link #start}.
200 */
201 public void stop() {
202 mStarted = false;
203 updateRunning();
204 }
205
206 /**
207 * The same as calling {@link #start} or {@link #stop}.
Jeffrey Sharkey3ff7eb92009-04-13 16:57:28 -0700208 * @hide pending API council approval
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 */
210 @android.view.RemotableViewMethod
211 public void setStarted(boolean started) {
212 mStarted = started;
213 updateRunning();
214 }
215
216 @Override
217 protected void onDetachedFromWindow() {
218 super.onDetachedFromWindow();
219 mVisible = false;
220 updateRunning();
221 }
222
223 @Override
224 protected void onWindowVisibilityChanged(int visibility) {
225 super.onWindowVisibilityChanged(visibility);
226 mVisible = visibility == VISIBLE;
227 updateRunning();
228 }
229
230 private synchronized void updateText(long now) {
231 long seconds = now - mBase;
232 seconds /= 1000;
233 String text = DateUtils.formatElapsedTime(mRecycle, seconds);
234
235 if (mFormat != null) {
236 Locale loc = Locale.getDefault();
237 if (mFormatter == null || !loc.equals(mFormatterLocale)) {
238 mFormatterLocale = loc;
239 mFormatter = new Formatter(mFormatBuilder, loc);
240 }
241 mFormatBuilder.setLength(0);
242 mFormatterArgs[0] = text;
243 try {
244 mFormatter.format(mFormat, mFormatterArgs);
245 text = mFormatBuilder.toString();
246 } catch (IllegalFormatException ex) {
247 if (!mLogged) {
248 Log.w(TAG, "Illegal format string: " + mFormat);
249 mLogged = true;
250 }
251 }
252 }
253 setText(text);
254 }
255
256 private void updateRunning() {
257 boolean running = mVisible && mStarted;
258 if (running != mRunning) {
259 if (running) {
260 updateText(SystemClock.elapsedRealtime());
261 dispatchChronometerTick();
262 mHandler.sendMessageDelayed(Message.obtain(mHandler, TICK_WHAT), 1000);
263 } else {
264 mHandler.removeMessages(TICK_WHAT);
265 }
266 mRunning = running;
267 }
268 }
269
270 private Handler mHandler = new Handler() {
271 public void handleMessage(Message m) {
272 if (mRunning) {
273 updateText(SystemClock.elapsedRealtime());
274 dispatchChronometerTick();
275 sendMessageDelayed(Message.obtain(this, TICK_WHAT), 1000);
276 }
277 }
278 };
279
280 void dispatchChronometerTick() {
281 if (mOnChronometerTickListener != null) {
282 mOnChronometerTickListener.onChronometerTick(this);
283 }
284 }
Svetoslav Ganov8a78fd42012-01-17 14:36:46 -0800285
286 @Override
287 public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
288 super.onInitializeAccessibilityEvent(event);
289 event.setClassName(Chronometer.class.getName());
290 }
291
292 @Override
293 public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
294 super.onInitializeAccessibilityNodeInfo(info);
295 info.setClassName(Chronometer.class.getName());
296 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297}