1 /* 2 * Copyright (C) 2020 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 package com.android.wallpaper.util; 17 18 import android.content.BroadcastReceiver; 19 import android.content.Context; 20 import android.content.Intent; 21 import android.content.IntentFilter; 22 import android.text.format.DateFormat; 23 24 import androidx.annotation.Nullable; 25 26 import java.util.Calendar; 27 28 /** Utility class for clock time preview. */ 29 public class TimeUtils { 30 31 private static final String CLOCK_FORMAT_12HOUR = "h:mm"; 32 private static final String CLOCK_FORMAT_24HOUR = "H:mm"; 33 34 /** Returns the clock formatted time. For 12-hour format, there's no AM/PM field displayed. */ getFormattedTime(Context context, Calendar calendar)35 public static CharSequence getFormattedTime(Context context, Calendar calendar) { 36 return DateFormat.format( 37 DateFormat.is24HourFormat(context) 38 ? CLOCK_FORMAT_24HOUR 39 : CLOCK_FORMAT_12HOUR, 40 calendar); 41 } 42 43 /** 44 * BroadcastReceiver that can notify a listener when the system time (minutes) changes. 45 * Use {@link #registerNewReceiver(Context, TimeListener)} to create a new instance that will be 46 * automatically registered using the given Context. 47 */ 48 public static class TimeTicker extends BroadcastReceiver { 49 50 /** 51 * Listener for the system time's change. 52 */ 53 public interface TimeListener { 54 /** 55 * Called when the system time (minutes) changes. 56 */ onCurrentTimeChanged()57 void onCurrentTimeChanged(); 58 } 59 60 /** 61 * Registers a broadcast receiver for time tick. 62 */ registerNewReceiver(Context context, @Nullable TimeListener listener)63 public static TimeTicker registerNewReceiver(Context context, 64 @Nullable TimeListener listener) { 65 TimeTicker receiver = new TimeTicker(listener); 66 // Register broadcast receiver for time tick 67 final IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK); 68 context.registerReceiver(receiver, filter); 69 return receiver; 70 } 71 72 private TimeListener mListener; 73 TimeTicker(@ullable TimeListener listener)74 private TimeTicker(@Nullable TimeListener listener) { 75 mListener = listener; 76 } 77 78 @Override onReceive(Context context, Intent intent)79 public void onReceive(Context context, Intent intent) { 80 if (mListener != null) { 81 mListener.onCurrentTimeChanged(); 82 } 83 } 84 } 85 } 86