Debian Codegraph @

core/java/android/widget/AnalogClock.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 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 android.widget;
18
19 import android.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.app.AppGlobals;
22 import android.compat.annotation.UnsupportedAppUsage;
23 import android.content.BroadcastReceiver;
24 import android.content.Context;
25 import android.content.Intent;
26 import android.content.IntentFilter;
27 import android.content.res.ColorStateList;
28 import android.content.res.TypedArray;
29 import android.graphics.BlendMode;
30 import android.graphics.Canvas;
31 import android.graphics.drawable.Drawable;
32 import android.graphics.drawable.Icon;
33 import android.text.format.DateUtils;
34 import android.util.AttributeSet;
35 import android.util.Log;
36 import android.view.RemotableViewMethod;
37 import android.view.View;
38 import android.view.inspector.InspectableProperty;
39 import android.widget.RemoteViews.RemoteView;
40
41 import java.time.Clock;
42 import java.time.DateTimeException;
43 import java.time.Duration;
44 import java.time.Instant;
45 import java.time.LocalTime;
46 import java.time.ZoneId;
47 import java.time.ZonedDateTime;
48 import java.util.Formatter;
49 import java.util.Locale;
50
51 /**
52 * This widget displays an analogic clock with two hands for hours and minutes.
53 *
54 * @attr ref android.R.styleable#AnalogClock_dial
55 * @attr ref android.R.styleable#AnalogClock_hand_hour
56 * @attr ref android.R.styleable#AnalogClock_hand_minute
57 * @attr ref android.R.styleable#AnalogClock_hand_second
58 * @attr ref android.R.styleable#AnalogClock_timeZone
59 * @deprecated This widget is no longer supported; except for
60 * {@link android.widget.RemoteViews} use cases like
61 * <a href="https://developer.android.com/develop/ui/views/appwidgets/overview">
62 * app widgets</a>.
63 *
64 */
65 @RemoteView
66 @Deprecated
67 public class AnalogClock extends View {
68 private static final String LOG_TAG = "AnalogClock";
69
70 /** How many times per second that the seconds hand advances. */
71 private final int mSecondsHandFps;
72
73 private Clock mClock;
74 @Nullable
75 private ZoneId mTimeZone;
76
77 @UnsupportedAppUsage
78 private Drawable mHourHand;
79 private final TintInfo mHourHandTintInfo = new TintInfo();
80 @UnsupportedAppUsage
81 private Drawable mMinuteHand;
82 private final TintInfo mMinuteHandTintInfo = new TintInfo();
83 @Nullable
84 private Drawable mSecondHand;
85 private final TintInfo mSecondHandTintInfo = new TintInfo();
86 @UnsupportedAppUsage
87 private Drawable mDial;
88 private final TintInfo mDialTintInfo = new TintInfo();
89
90 private int mDialWidth;
91 private int mDialHeight;
92
93 private boolean mVisible;
94
95 private float mSeconds;
96 private float mMinutes;
97 private float mHour;
98 private boolean mChanged;
99
100 public AnalogClock(Context context) {
101 this(context, null);
102 }
103
104 public AnalogClock(Context context, AttributeSet attrs) {
105 this(context, attrs, 0);
106 }
107
108 public AnalogClock(Context context, AttributeSet attrs, int defStyleAttr) {
109 this(context, attrs, defStyleAttr, 0);
110 }
111
112 public AnalogClock(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
113 super(context, attrs, defStyleAttr, defStyleRes);
114
115 mSecondsHandFps = AppGlobals.getIntCoreSetting(
116 WidgetFlags.KEY_ANALOG_CLOCK_SECONDS_HAND_FPS,
117 context.getResources()
118 .getInteger(com.android.internal.R.integer
119 .config_defaultAnalogClockSecondsHandFps));
120
121 final TypedArray a = context.obtainStyledAttributes(
122 attrs, com.android.internal.R.styleable.AnalogClock, defStyleAttr, defStyleRes);
123 saveAttributeDataForStyleable(context, com.android.internal.R.styleable.AnalogClock,
124 attrs, a, defStyleAttr, defStyleRes);
125
126 mDial = a.getDrawable(com.android.internal.R.styleable.AnalogClock_dial);
127 if (mDial == null) {
128 mDial = context.getDrawable(com.android.internal.R.drawable.clock_dial);
129 }
130
131 ColorStateList dialTintList = a.getColorStateList(
132 com.android.internal.R.styleable.AnalogClock_dialTint);
133 if (dialTintList != null) {
134 mDialTintInfo.mTintList = dialTintList;
135 mDialTintInfo.mHasTintList = true;
136 }
137 BlendMode dialTintMode = Drawable.parseBlendMode(
138 a.getInt(com.android.internal.R.styleable.AnalogClock_dialTintMode, -1),
139 null);
140 if (dialTintMode != null) {
141 mDialTintInfo.mTintBlendMode = dialTintMode;
142 mDialTintInfo.mHasTintBlendMode = true;
143 }
144 if (mDialTintInfo.mHasTintList || mDialTintInfo.mHasTintBlendMode) {
145 mDial = mDialTintInfo.apply(mDial);
146 }
147
148 mHourHand = a.getDrawable(com.android.internal.R.styleable.AnalogClock_hand_hour);
149 if (mHourHand == null) {
150 mHourHand = context.getDrawable(com.android.internal.R.drawable.clock_hand_hour);
151 }
152
153 ColorStateList hourHandTintList = a.getColorStateList(
154 com.android.internal.R.styleable.AnalogClock_hand_hourTint);
155 if (hourHandTintList != null) {
156 mHourHandTintInfo.mTintList = hourHandTintList;
157 mHourHandTintInfo.mHasTintList = true;
158 }
159 BlendMode hourHandTintMode = Drawable.parseBlendMode(
160 a.getInt(com.android.internal.R.styleable.AnalogClock_hand_hourTintMode, -1),
161 null);
162 if (hourHandTintMode != null) {
163 mHourHandTintInfo.mTintBlendMode = hourHandTintMode;
164 mHourHandTintInfo.mHasTintBlendMode = true;
165 }
166 if (mHourHandTintInfo.mHasTintList || mHourHandTintInfo.mHasTintBlendMode) {
167 mHourHand = mHourHandTintInfo.apply(mHourHand);
168 }
169
170 mMinuteHand = a.getDrawable(com.android.internal.R.styleable.AnalogClock_hand_minute);
171 if (mMinuteHand == null) {
172 mMinuteHand = context.getDrawable(com.android.internal.R.drawable.clock_hand_minute);
173 }
174
175 ColorStateList minuteHandTintList = a.getColorStateList(
176 com.android.internal.R.styleable.AnalogClock_hand_minuteTint);
177 if (minuteHandTintList != null) {
178 mMinuteHandTintInfo.mTintList = minuteHandTintList;
179 mMinuteHandTintInfo.mHasTintList = true;
180 }
181 BlendMode minuteHandTintMode = Drawable.parseBlendMode(
182 a.getInt(com.android.internal.R.styleable.AnalogClock_hand_minuteTintMode, -1),
183 null);
184 if (minuteHandTintMode != null) {
185 mMinuteHandTintInfo.mTintBlendMode = minuteHandTintMode;
186 mMinuteHandTintInfo.mHasTintBlendMode = true;
187 }
188 if (mMinuteHandTintInfo.mHasTintList || mMinuteHandTintInfo.mHasTintBlendMode) {
189 mMinuteHand = mMinuteHandTintInfo.apply(mMinuteHand);
190 }
191
192 mSecondHand = a.getDrawable(com.android.internal.R.styleable.AnalogClock_hand_second);
193
194 ColorStateList secondHandTintList = a.getColorStateList(
195 com.android.internal.R.styleable.AnalogClock_hand_secondTint);
196 if (secondHandTintList != null) {
197 mSecondHandTintInfo.mTintList = secondHandTintList;
198 mSecondHandTintInfo.mHasTintList = true;
199 }
200 BlendMode secondHandTintMode = Drawable.parseBlendMode(
201 a.getInt(com.android.internal.R.styleable.AnalogClock_hand_secondTintMode, -1),
202 null);
203 if (secondHandTintMode != null) {
204 mSecondHandTintInfo.mTintBlendMode = secondHandTintMode;
205 mSecondHandTintInfo.mHasTintBlendMode = true;
206 }
207 if (mSecondHandTintInfo.mHasTintList || mSecondHandTintInfo.mHasTintBlendMode) {
208 mSecondHand = mSecondHandTintInfo.apply(mSecondHand);
209 }
210
211 mTimeZone = toZoneId(a.getString(com.android.internal.R.styleable.AnalogClock_timeZone));
212 createClock();
213
214 a.recycle();
215
216 mDialWidth = mDial.getIntrinsicWidth();
217 mDialHeight = mDial.getIntrinsicHeight();
218 }
219
220 /** Sets the dial of the clock to the specified Icon. */
221 @RemotableViewMethod
222 public void setDial(@NonNull Icon icon) {
223 mDial = icon.loadDrawable(getContext());
224 mDialWidth = mDial.getIntrinsicWidth();
225 mDialHeight = mDial.getIntrinsicHeight();
226 if (mDialTintInfo.mHasTintList || mDialTintInfo.mHasTintBlendMode) {
227 mDial = mDialTintInfo.apply(mDial);
228 }
229
230 mChanged = true;
231 invalidate();
232 }
233
234 /**
235 * Applies a tint to the dial drawable.
236 * <p>
237 * Subsequent calls to {@link #setDial(Icon)} will
238 * automatically mutate the drawable and apply the specified tint and tint
239 * mode using {@link Drawable#setTintList(ColorStateList)}.
240 *
241 * @param tint the tint to apply, may be {@code null} to clear tint
242 *
243 * @attr ref android.R.styleable#AnalogClock_dialTint
244 * @see #getDialTintList()
245 * @see Drawable#setTintList(ColorStateList)
246 */
247 @RemotableViewMethod
248 public void setDialTintList(@Nullable ColorStateList tint) {
249 mDialTintInfo.mTintList = tint;
250 mDialTintInfo.mHasTintList = true;
251
252 mDial = mDialTintInfo.apply(mDial);
253 }
254
255 /**
256 * @return the tint applied to the dial drawable
257 * @attr ref android.R.styleable#AnalogClock_dialTint
258 * @see #setDialTintList(ColorStateList)
259 */
260 @InspectableProperty(attributeId = com.android.internal.R.styleable.AnalogClock_dialTint)
261 @Nullable
262 public ColorStateList getDialTintList() {
263 return mDialTintInfo.mTintList;
264 }
265
266 /**
267 * Specifies the blending mode used to apply the tint specified by
268 * {@link #setDialTintList(ColorStateList)}} to the dial drawable.
269 * The default mode is {@link BlendMode#SRC_IN}.
270 *
271 * @param blendMode the blending mode used to apply the tint, may be
272 * {@code null} to clear tint
273 * @attr ref android.R.styleable#AnalogClock_dialTintMode
274 * @see #getDialTintBlendMode()
275 * @see Drawable#setTintBlendMode(BlendMode)
276 */
277 @RemotableViewMethod
278 public void setDialTintBlendMode(@Nullable BlendMode blendMode) {
279 mDialTintInfo.mTintBlendMode = blendMode;
280 mDialTintInfo.mHasTintBlendMode = true;
281
282 mDial = mDialTintInfo.apply(mDial);
283 }
284
285 /**
286 * @return the blending mode used to apply the tint to the dial drawable
287 * @attr ref android.R.styleable#AnalogClock_dialTintMode
288 * @see #setDialTintBlendMode(BlendMode)
289 */
290 @InspectableProperty(attributeId = com.android.internal.R.styleable.AnalogClock_dialTintMode)
291 @Nullable
292 public BlendMode getDialTintBlendMode() {
293 return mDialTintInfo.mTintBlendMode;
294 }
295
296 /** Sets the hour hand of the clock to the specified Icon. */
297 @RemotableViewMethod
298 public void setHourHand(@NonNull Icon icon) {
299 mHourHand = icon.loadDrawable(getContext());
300 if (mHourHandTintInfo.mHasTintList || mHourHandTintInfo.mHasTintBlendMode) {
301 mHourHand = mHourHandTintInfo.apply(mHourHand);
302 }
303
304 mChanged = true;
305 invalidate();
306 }
307
308 /**
309 * Applies a tint to the hour hand drawable.
310 * <p>
311 * Subsequent calls to {@link #setHourHand(Icon)} will
312 * automatically mutate the drawable and apply the specified tint and tint
313 * mode using {@link Drawable#setTintList(ColorStateList)}.
314 *
315 * @param tint the tint to apply, may be {@code null} to clear tint
316 *
317 * @attr ref android.R.styleable#AnalogClock_hand_hourTint
318 * @see #getHourHandTintList()
319 * @see Drawable#setTintList(ColorStateList)
320 */
321 @RemotableViewMethod
322 public void setHourHandTintList(@Nullable ColorStateList tint) {
323 mHourHandTintInfo.mTintList = tint;
324 mHourHandTintInfo.mHasTintList = true;
325
326 mHourHand = mHourHandTintInfo.apply(mHourHand);
327 }
328
329 /**
330 * @return the tint applied to the hour hand drawable
331 * @attr ref android.R.styleable#AnalogClock_hand_hourTint
332 * @see #setHourHandTintList(ColorStateList)
333 */
334 @InspectableProperty(
335 attributeId = com.android.internal.R.styleable.AnalogClock_hand_hourTint
336 )
337 @Nullable
338 public ColorStateList getHourHandTintList() {
339 return mHourHandTintInfo.mTintList;
340 }
341
342 /**
343 * Specifies the blending mode used to apply the tint specified by
344 * {@link #setHourHandTintList(ColorStateList)}} to the hour hand drawable.
345 * The default mode is {@link BlendMode#SRC_IN}.
346 *
347 * @param blendMode the blending mode used to apply the tint, may be
348 * {@code null} to clear tint
349 * @attr ref android.R.styleable#AnalogClock_hand_hourTintMode
350 * @see #getHourHandTintBlendMode()
351 * @see Drawable#setTintBlendMode(BlendMode)
352 */
353 @RemotableViewMethod
354 public void setHourHandTintBlendMode(@Nullable BlendMode blendMode) {
355 mHourHandTintInfo.mTintBlendMode = blendMode;
356 mHourHandTintInfo.mHasTintBlendMode = true;
357
358 mHourHand = mHourHandTintInfo.apply(mHourHand);
359 }
360
361 /**
362 * @return the blending mode used to apply the tint to the hour hand drawable
363 * @attr ref android.R.styleable#AnalogClock_hand_hourTintMode
364 * @see #setHourHandTintBlendMode(BlendMode)
365 */
366 @InspectableProperty(
367 attributeId = com.android.internal.R.styleable.AnalogClock_hand_hourTintMode)
368 @Nullable
369 public BlendMode getHourHandTintBlendMode() {
370 return mHourHandTintInfo.mTintBlendMode;
371 }
372
373 /** Sets the minute hand of the clock to the specified Icon. */
374 @RemotableViewMethod
375 public void setMinuteHand(@NonNull Icon icon) {
376 mMinuteHand = icon.loadDrawable(getContext());
377 if (mMinuteHandTintInfo.mHasTintList || mMinuteHandTintInfo.mHasTintBlendMode) {
378 mMinuteHand = mMinuteHandTintInfo.apply(mMinuteHand);
379 }
380
381 mChanged = true;
382 invalidate();
383 }
384
385 /**
386 * Applies a tint to the minute hand drawable.
387 * <p>
388 * Subsequent calls to {@link #setMinuteHand(Icon)} will
389 * automatically mutate the drawable and apply the specified tint and tint
390 * mode using {@link Drawable#setTintList(ColorStateList)}.
391 *
392 * @param tint the tint to apply, may be {@code null} to clear tint
393 *
394 * @attr ref android.R.styleable#AnalogClock_hand_minuteTint
395 * @see #getMinuteHandTintList()
396 * @see Drawable#setTintList(ColorStateList)
397 */
398 @RemotableViewMethod
399 public void setMinuteHandTintList(@Nullable ColorStateList tint) {
400 mMinuteHandTintInfo.mTintList = tint;
401 mMinuteHandTintInfo.mHasTintList = true;
402
403 mMinuteHand = mMinuteHandTintInfo.apply(mMinuteHand);
404 }
405
406 /**
407 * @return the tint applied to the minute hand drawable
408 * @attr ref android.R.styleable#AnalogClock_hand_minuteTint
409 * @see #setMinuteHandTintList(ColorStateList)
410 */
411 @InspectableProperty(
412 attributeId = com.android.internal.R.styleable.AnalogClock_hand_minuteTint
413 )
414 @Nullable
415 public ColorStateList getMinuteHandTintList() {
416 return mMinuteHandTintInfo.mTintList;
417 }
418
419 /**
420 * Specifies the blending mode used to apply the tint specified by
421 * {@link #setMinuteHandTintList(ColorStateList)}} to the minute hand drawable.
422 * The default mode is {@link BlendMode#SRC_IN}.
423 *
424 * @param blendMode the blending mode used to apply the tint, may be
425 * {@code null} to clear tint
426 * @attr ref android.R.styleable#AnalogClock_hand_minuteTintMode
427 * @see #getMinuteHandTintBlendMode()
428 * @see Drawable#setTintBlendMode(BlendMode)
429 */
430 @RemotableViewMethod
431 public void setMinuteHandTintBlendMode(@Nullable BlendMode blendMode) {
432 mMinuteHandTintInfo.mTintBlendMode = blendMode;
433 mMinuteHandTintInfo.mHasTintBlendMode = true;
434
435 mMinuteHand = mMinuteHandTintInfo.apply(mMinuteHand);
436 }
437
438 /**
439 * @return the blending mode used to apply the tint to the minute hand drawable
440 * @attr ref android.R.styleable#AnalogClock_hand_minuteTintMode
441 * @see #setMinuteHandTintBlendMode(BlendMode)
442 */
443 @InspectableProperty(
444 attributeId = com.android.internal.R.styleable.AnalogClock_hand_minuteTintMode)
445 @Nullable
446 public BlendMode getMinuteHandTintBlendMode() {
447 return mMinuteHandTintInfo.mTintBlendMode;
448 }
449
450 /**
451 * Sets the second hand of the clock to the specified Icon, or hides the second hand if it is
452 * null.
453 */
454 @RemotableViewMethod
455 public void setSecondHand(@Nullable Icon icon) {
456 mSecondHand = icon == null ? null : icon.loadDrawable(getContext());
457 if (mSecondHandTintInfo.mHasTintList || mSecondHandTintInfo.mHasTintBlendMode) {
458 mSecondHand = mSecondHandTintInfo.apply(mSecondHand);
459 }
460 // Re-run the tick runnable immediately as the presence or absence of a seconds hand affects
461 // the next time we need to tick the clock.
462 mTick.run();
463
464 mChanged = true;
465 invalidate();
466 }
467
468 /**
469 * Applies a tint to the second hand drawable.
470 * <p>
471 * Subsequent calls to {@link #setSecondHand(Icon)} will
472 * automatically mutate the drawable and apply the specified tint and tint
473 * mode using {@link Drawable#setTintList(ColorStateList)}.
474 *
475 * @param tint the tint to apply, may be {@code null} to clear tint
476 *
477 * @attr ref android.R.styleable#AnalogClock_hand_secondTint
478 * @see #getSecondHandTintList()
479 * @see Drawable#setTintList(ColorStateList)
480 */
481 @RemotableViewMethod
482 public void setSecondHandTintList(@Nullable ColorStateList tint) {
483 mSecondHandTintInfo.mTintList = tint;
484 mSecondHandTintInfo.mHasTintList = true;
485
486 mSecondHand = mSecondHandTintInfo.apply(mSecondHand);
487 }
488
489 /**
490 * @return the tint applied to the second hand drawable
491 * @attr ref android.R.styleable#AnalogClock_hand_secondTint
492 * @see #setSecondHandTintList(ColorStateList)
493 */
494 @InspectableProperty(
495 attributeId = com.android.internal.R.styleable.AnalogClock_hand_secondTint
496 )
497 @Nullable
498 public ColorStateList getSecondHandTintList() {
499 return mSecondHandTintInfo.mTintList;
500 }
501
502 /**
503 * Specifies the blending mode used to apply the tint specified by
504 * {@link #setSecondHandTintList(ColorStateList)}} to the second hand drawable.
505 * The default mode is {@link BlendMode#SRC_IN}.
506 *
507 * @param blendMode the blending mode used to apply the tint, may be
508 * {@code null} to clear tint
509 * @attr ref android.R.styleable#AnalogClock_hand_secondTintMode
510 * @see #getSecondHandTintBlendMode()
511 * @see Drawable#setTintBlendMode(BlendMode)
512 */
513 @RemotableViewMethod
514 public void setSecondHandTintBlendMode(@Nullable BlendMode blendMode) {
515 mSecondHandTintInfo.mTintBlendMode = blendMode;
516 mSecondHandTintInfo.mHasTintBlendMode = true;
517
518 mSecondHand = mSecondHandTintInfo.apply(mSecondHand);
519 }
520
521 /**
522 * @return the blending mode used to apply the tint to the second hand drawable
523 * @attr ref android.R.styleable#AnalogClock_hand_secondTintMode
524 * @see #setSecondHandTintBlendMode(BlendMode)
525 */
526 @InspectableProperty(
527 attributeId = com.android.internal.R.styleable.AnalogClock_hand_secondTintMode)
528 @Nullable
529 public BlendMode getSecondHandTintBlendMode() {
530 return mSecondHandTintInfo.mTintBlendMode;
531 }
532
533 /**
534 * Indicates which time zone is currently used by this view.
535 *
536 * @return The ID of the current time zone or null if the default time zone,
537 * as set by the user, must be used
538 *
539 * @see java.util.TimeZone
540 * @see java.util.TimeZone#getAvailableIDs()
541 * @see #setTimeZone(String)
542 */
543 @InspectableProperty
544 @Nullable
545 public String getTimeZone() {
546 ZoneId zoneId = mTimeZone;
547 return zoneId == null ? null : zoneId.getId();
548 }
549
550 /**
551 * Sets the specified time zone to use in this clock. When the time zone
552 * is set through this method, system time zone changes (when the user
553 * sets the time zone in settings for instance) will be ignored.
554 *
555 * @param timeZone The desired time zone's ID as specified in {@link java.util.TimeZone}
556 * or null to user the time zone specified by the user
557 * (system time zone)
558 *
559 * @see #getTimeZone()
560 * @see java.util.TimeZone#getAvailableIDs()
561 * @see java.util.TimeZone#getTimeZone(String)
562 *
563 * @attr ref android.R.styleable#AnalogClock_timeZone
564 */
565 @RemotableViewMethod
566 public void setTimeZone(@Nullable String timeZone) {
567 mTimeZone = toZoneId(timeZone);
568
569 createClock();
570 onTimeChanged();
571 }
572
573 @Override
574 public void onVisibilityAggregated(boolean isVisible) {
575 super.onVisibilityAggregated(isVisible);
576
577 if (isVisible) {
578 onVisible();
579 } else {
580 onInvisible();
581 }
582 }
583
584 @Override
585 protected void onAttachedToWindow() {
586 super.onAttachedToWindow();
587 IntentFilter filter = new IntentFilter();
588
589 if (!mReceiverAttached) {
590 filter.addAction(Intent.ACTION_TIME_CHANGED);
591 filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
592
593 // OK, this is gross but needed. This class is supported by the
594 // remote views mechanism and as a part of that the remote views
595 // can be inflated by a context for another user without the app
596 // having interact users permission - just for loading resources.
597 // For example, when adding widgets from a user profile to the
598 // home screen. Therefore, we register the receiver as the current
599 // user not the one the context is for.
600 getContext().registerReceiverAsUser(mIntentReceiver,
601 android.os.Process.myUserHandle(), filter, null, getHandler());
602 mReceiverAttached = true;
603 }
604
605 // NOTE: It's safe to do these after registering the receiver since the receiver always runs
606 // in the main thread, therefore the receiver can't run before this method returns.
607
608 // The time zone may have changed while the receiver wasn't registered, so update the clock.
609 createClock();
610
611 // Make sure we update to the current time
612 onTimeChanged();
613 }
614
615 @Override
616 protected void onDetachedFromWindow() {
617 if (mReceiverAttached) {
618 getContext().unregisterReceiver(mIntentReceiver);
619 mReceiverAttached = false;
620 }
621 super.onDetachedFromWindow();
622 }
623
624 private void onVisible() {
625 if (!mVisible) {
626 mVisible = true;
627 mTick.run();
628 }
629
630 }
631
632 private void onInvisible() {
633 if (mVisible) {
634 removeCallbacks(mTick);
635 mVisible = false;
636 }
637 }
638
639 @Override
640 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
641
642 int widthMode = MeasureSpec.getMode(widthMeasureSpec);
643 int widthSize = MeasureSpec.getSize(widthMeasureSpec);
644 int heightMode = MeasureSpec.getMode(heightMeasureSpec);
645 int heightSize = MeasureSpec.getSize(heightMeasureSpec);
646
647 float hScale = 1.0f;
648 float vScale = 1.0f;
649
650 if (widthMode != MeasureSpec.UNSPECIFIED && widthSize < mDialWidth) {
651 hScale = (float) widthSize / (float) mDialWidth;
652 }
653
654 if (heightMode != MeasureSpec.UNSPECIFIED && heightSize < mDialHeight) {
655 vScale = (float )heightSize / (float) mDialHeight;
656 }
657
658 float scale = Math.min(hScale, vScale);
659
660 setMeasuredDimension(resolveSizeAndState((int) (mDialWidth * scale), widthMeasureSpec, 0),
661 resolveSizeAndState((int) (mDialHeight * scale), heightMeasureSpec, 0));
662 }
663
664 @Override
665 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
666 super.onSizeChanged(w, h, oldw, oldh);
667 mChanged = true;
668 }
669
670 @Override
671 protected void onDraw(Canvas canvas) {
672 super.onDraw(canvas);
673
674 boolean changed = mChanged;
675 if (changed) {
676 mChanged = false;
677 }
678
679 int availableWidth = mRight - mLeft;
680 int availableHeight = mBottom - mTop;
681
682 int x = availableWidth / 2;
683 int y = availableHeight / 2;
684
685 final Drawable dial = mDial;
686 int w = dial.getIntrinsicWidth();
687 int h = dial.getIntrinsicHeight();
688
689 boolean scaled = false;
690
691 if (availableWidth < w || availableHeight < h) {
692 scaled = true;
693 float scale = Math.min((float) availableWidth / (float) w,
694 (float) availableHeight / (float) h);
695 canvas.save();
696 canvas.scale(scale, scale, x, y);
697 }
698
699 if (changed) {
700 dial.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
701 }
702 dial.draw(canvas);
703
704 canvas.save();
705 canvas.rotate(mHour / 12.0f * 360.0f, x, y);
706 final Drawable hourHand = mHourHand;
707 if (changed) {
708 w = hourHand.getIntrinsicWidth();
709 h = hourHand.getIntrinsicHeight();
710 hourHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
711 }
712 hourHand.draw(canvas);
713 canvas.restore();
714
715 canvas.save();
716 canvas.rotate(mMinutes / 60.0f * 360.0f, x, y);
717
718 final Drawable minuteHand = mMinuteHand;
719 if (changed) {
720 w = minuteHand.getIntrinsicWidth();
721 h = minuteHand.getIntrinsicHeight();
722 minuteHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
723 }
724 minuteHand.draw(canvas);
725 canvas.restore();
726
727 final Drawable secondHand = mSecondHand;
728 if (secondHand != null && mSecondsHandFps > 0) {
729 canvas.save();
730 canvas.rotate(mSeconds / 60.0f * 360.0f, x, y);
731
732 if (changed) {
733 w = secondHand.getIntrinsicWidth();
734 h = secondHand.getIntrinsicHeight();
735 secondHand.setBounds(x - (w / 2), y - (h / 2), x + (w / 2), y + (h / 2));
736 }
737 secondHand.draw(canvas);
738 canvas.restore();
739 }
740
741 if (scaled) {
742 canvas.restore();
743 }
744 }
745
746 /**
747 * Return the current Instant to be used for drawing the clockface. Protected to allow
748 * subclasses to override this to show a different time from the system clock.
749 *
750 * @return the Instant to be shown on the clockface
751 * @hide
752 */
753 protected Instant now() {
754 return mClock.instant();
755 }
756
757 /**
758 * @hide
759 */
760 protected void onTimeChanged() {
761 Instant now = now();
762 onTimeChanged(now.atZone(mClock.getZone()).toLocalTime(), now.toEpochMilli());
763 }
764
765 private void onTimeChanged(LocalTime localTime, long nowMillis) {
766 float previousHour = mHour;
767 float previousMinutes = mMinutes;
768
769 float rawSeconds = localTime.getSecond() + localTime.getNano() / 1_000_000_000f;
770 // We round the fraction of the second so that the seconds hand always occupies the same
771 // n positions between two given numbers, where n is the number of ticks per second. This
772 // ensures the second hand advances by a consistent distance despite our handler callbacks
773 // occurring at inconsistent frequencies.
774 mSeconds =
775 mSecondsHandFps <= 0
776 ? rawSeconds
777 : Math.round(rawSeconds * mSecondsHandFps) / (float) mSecondsHandFps;
778 mMinutes = localTime.getMinute() + mSeconds / 60.0f;
779 mHour = localTime.getHour() + mMinutes / 60.0f;
780 mChanged = true;
781
782 // Update the content description only if the announced hours and minutes have changed.
783 if ((int) previousHour != (int) mHour || (int) previousMinutes != (int) mMinutes) {
784 updateContentDescription(nowMillis);
785 }
786 }
787
788 /** Intent receiver for the time or time zone changing. */
789 private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
790 @Override
791 public void onReceive(Context context, Intent intent) {
792 if (Intent.ACTION_TIMEZONE_CHANGED.equals(intent.getAction())) {
793 createClock();
794 }
795
796 mTick.run();
797 }
798 };
799 private boolean mReceiverAttached;
800
801 private final Runnable mTick = new Runnable() {
802 @Override
803 public void run() {
804 removeCallbacks(this);
805 if (!mVisible) {
806 return;
807 }
808
809 Instant now = now();
810 ZonedDateTime zonedDateTime = now.atZone(mClock.getZone());
811 LocalTime localTime = zonedDateTime.toLocalTime();
812
813 long millisUntilNextTick;
814 if (mSecondHand == null || mSecondsHandFps <= 0) {
815 // If there's no second hand, then tick at the start of the next minute.
816 //
817 // This must be done with ZonedDateTime as opposed to LocalDateTime to ensure proper
818 // handling of DST. Also note that because of leap seconds, it should not be assumed
819 // that one minute == 60 seconds.
820 Instant startOfNextMinute = zonedDateTime.plusMinutes(1).withSecond(0).toInstant();
821 millisUntilNextTick = Duration.between(now, startOfNextMinute).toMillis();
822 if (millisUntilNextTick <= 0) {
823 // This should never occur, but if it does, then just check the tick again in
824 // one minute to ensure we're always moving forward.
825 millisUntilNextTick = Duration.ofMinutes(1).toMillis();
826 }
827 } else {
828 // If there is a seconds hand, then determine the next tick point based on the fps.
829 //
830 // How many milliseconds through the second we currently are.
831 long millisOfSecond = Duration.ofNanos(localTime.getNano()).toMillis();
832 // How many milliseconds there are between tick positions for the seconds hand.
833 double millisPerTick = 1000 / (double) mSecondsHandFps;
834 // How many milliseconds we are past the last tick position.
835 long millisPastLastTick = Math.round(millisOfSecond % millisPerTick);
836 // How many milliseconds there are until the next tick position.
837 millisUntilNextTick = Math.round(millisPerTick - millisPastLastTick);
838 // If we are exactly at the tick position, this could be 0 milliseconds due to
839 // rounding. In this case, advance by the full amount of millis to the next
840 // position.
841 if (millisUntilNextTick <= 0) {
842 millisUntilNextTick = Math.round(millisPerTick);
843 }
844 }
845
846 // Schedule a callback for when the next tick should occur.
847 postDelayed(this, millisUntilNextTick);
848
849 onTimeChanged(localTime, now.toEpochMilli());
850
851 invalidate();
852 }
853 };
854
855 private void createClock() {
856 ZoneId zoneId = mTimeZone;
857 if (zoneId == null) {
858 mClock = Clock.systemDefaultZone();
859 } else {
860 mClock = Clock.system(zoneId);
861 }
862 }
863
864 private void updateContentDescription(long timeMillis) {
865 final int flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_24HOUR;
866 String contentDescription =
867 DateUtils.formatDateRange(
868 mContext,
869 new Formatter(new StringBuilder(50), Locale.getDefault()),
870 timeMillis /* startMillis */,
871 timeMillis /* endMillis */,
872 flags,
873 getTimeZone())
874 .toString();
875 setContentDescription(contentDescription);
876 }
877
878 /**
879 * Tries to parse a {@link ZoneId} from {@code timeZone}, returning null if it is null or there
880 * is an error parsing.
881 */
882 @Nullable
883 private static ZoneId toZoneId(@Nullable String timeZone) {
884 if (timeZone == null) {
885 return null;
886 }
887
888 try {
889 return ZoneId.of(timeZone);
890 } catch (DateTimeException e) {
891 Log.w(LOG_TAG, "Failed to parse time zone from " + timeZone, e);
892 return null;
893 }
894 }
895
896 private final class TintInfo {
897 boolean mHasTintList;
898 @Nullable ColorStateList mTintList;
899 boolean mHasTintBlendMode;
900 @Nullable BlendMode mTintBlendMode;
901
902 /**
903 * Returns a mutated copy of {@code drawable} with tinting applied, or null if it's null.
904 */
905 @Nullable
906 Drawable apply(@Nullable Drawable drawable) {
907 if (drawable == null) return null;
908
909 Drawable newDrawable = drawable.mutate();
910
911 if (mHasTintList) {
912 newDrawable.setTintList(mTintList);
913 }
914
915 if (mHasTintBlendMode) {
916 newDrawable.setTintBlendMode(mTintBlendMode);
917 }
918
919 // All drawables should have the same state as the View itself.
920 if (drawable.isStateful()) {
921 newDrawable.setState(getDrawableState());
922 }
923
924 return newDrawable;
925 }
926 }
927 }