1 /*
2  * Copyright (C) 2016 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 com.android.deskclock;
18 
19 import android.widget.TextView;
20 
21 import static android.text.format.DateUtils.HOUR_IN_MILLIS;
22 import static android.text.format.DateUtils.MINUTE_IN_MILLIS;
23 import static android.text.format.DateUtils.SECOND_IN_MILLIS;
24 
25 /**
26  * A controller which will format a provided time in millis to display as a timer.
27  */
28 public final class TimerTextController {
29 
30     private final TextView mTextView;
31 
TimerTextController(TextView textView)32     public TimerTextController(TextView textView) {
33         mTextView = textView;
34     }
35 
setTimeString(long remainingTime)36     public void setTimeString(long remainingTime) {
37         boolean isNegative = false;
38         if (remainingTime < 0) {
39             remainingTime = -remainingTime;
40             isNegative = true;
41         }
42 
43         int hours = (int) (remainingTime / HOUR_IN_MILLIS);
44         int remainder = (int) (remainingTime % HOUR_IN_MILLIS);
45 
46         int minutes = (int) (remainder / MINUTE_IN_MILLIS);
47         remainder = (int) (remainder % MINUTE_IN_MILLIS);
48 
49         int seconds = (int) (remainder / SECOND_IN_MILLIS);
50         remainder = (int) (remainder % SECOND_IN_MILLIS);
51 
52         // Round up to the next second
53         if (!isNegative && remainder != 0) {
54             seconds++;
55             if (seconds == 60) {
56                 seconds = 0;
57                 minutes++;
58                 if (minutes == 60) {
59                     minutes = 0;
60                     hours++;
61                 }
62             }
63         }
64 
65         String time = Utils.getTimeString(mTextView.getContext(), hours, minutes, seconds);
66         if (isNegative && !(hours == 0 && minutes == 0 && seconds == 0)) {
67             time = "\u2212" + time;
68         }
69 
70         mTextView.setText(time);
71     }
72 }
73