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.text.format; 18 19 import android.annotation.NonNull; 20 import android.annotation.Nullable; 21 import android.content.Context; 22 import android.content.res.Resources; 23 import android.text.BidiFormatter; 24 import android.text.TextUtils; 25 import android.view.View; 26 import android.net.NetworkUtils; 27 import android.net.TrafficStats; 28 29 import java.util.Locale; 30 31 /** 32 * Utility class to aid in formatting common values that are not covered 33 * by the {@link java.util.Formatter} class in {@link java.util} 34 */ 35 public final class Formatter { 36 37 /** {@hide} */ 38 public static final int FLAG_SHORTER = 1 << 0; 39 /** {@hide} */ 40 public static final int FLAG_CALCULATE_ROUNDED = 1 << 1; 41 42 /** {@hide} */ 43 public static class BytesResult { 44 public final String value; 45 public final String units; 46 public final long roundedBytes; 47 BytesResult(String value, String units, long roundedBytes)48 public BytesResult(String value, String units, long roundedBytes) { 49 this.value = value; 50 this.units = units; 51 this.roundedBytes = roundedBytes; 52 } 53 } 54 55 /* Wraps the source string in bidi formatting characters in RTL locales */ bidiWrap(@onNull Context context, String source)56 private static String bidiWrap(@NonNull Context context, String source) { 57 final Locale locale = context.getResources().getConfiguration().locale; 58 if (TextUtils.getLayoutDirectionFromLocale(locale) == View.LAYOUT_DIRECTION_RTL) { 59 return BidiFormatter.getInstance(true /* RTL*/).unicodeWrap(source); 60 } else { 61 return source; 62 } 63 } 64 65 /** 66 * Formats a content size to be in the form of bytes, kilobytes, megabytes, etc. 67 * 68 * If the context has a right-to-left locale, the returned string is wrapped in bidi formatting 69 * characters to make sure it's displayed correctly if inserted inside a right-to-left string. 70 * (This is useful in cases where the unit strings, like "MB", are left-to-right, but the 71 * locale is right-to-left.) 72 * 73 * @param context Context to use to load the localized units 74 * @param sizeBytes size value to be formatted, in bytes 75 * @return formatted string with the number 76 */ formatFileSize(@ullable Context context, long sizeBytes)77 public static String formatFileSize(@Nullable Context context, long sizeBytes) { 78 if (context == null) { 79 return ""; 80 } 81 final BytesResult res = formatBytes(context.getResources(), sizeBytes, 0); 82 return bidiWrap(context, context.getString(com.android.internal.R.string.fileSizeSuffix, 83 res.value, res.units)); 84 } 85 86 /** 87 * Like {@link #formatFileSize}, but trying to generate shorter numbers 88 * (showing fewer digits of precision). 89 */ formatShortFileSize(@ullable Context context, long sizeBytes)90 public static String formatShortFileSize(@Nullable Context context, long sizeBytes) { 91 if (context == null) { 92 return ""; 93 } 94 final BytesResult res = formatBytes(context.getResources(), sizeBytes, FLAG_SHORTER); 95 return bidiWrap(context, context.getString(com.android.internal.R.string.fileSizeSuffix, 96 res.value, res.units)); 97 } 98 99 /** {@hide} */ formatBytes(Resources res, long sizeBytes, int flags)100 public static BytesResult formatBytes(Resources res, long sizeBytes, int flags) { 101 float result = sizeBytes; 102 int suffix = com.android.internal.R.string.byteShort; 103 long mult = 1; 104 if (result > 900) { 105 suffix = com.android.internal.R.string.kilobyteShort; 106 mult = TrafficStats.KB_IN_BYTES; 107 result = result / 1024; 108 } 109 if (result > 900) { 110 suffix = com.android.internal.R.string.megabyteShort; 111 mult = TrafficStats.MB_IN_BYTES; 112 result = result / 1024; 113 } 114 if (result > 900) { 115 suffix = com.android.internal.R.string.gigabyteShort; 116 mult = TrafficStats.GB_IN_BYTES; 117 result = result / 1024; 118 } 119 if (result > 900) { 120 suffix = com.android.internal.R.string.terabyteShort; 121 mult = TrafficStats.TB_IN_BYTES; 122 result = result / 1024; 123 } 124 if (result > 900) { 125 suffix = com.android.internal.R.string.petabyteShort; 126 mult = TrafficStats.PB_IN_BYTES; 127 result = result / 1024; 128 } 129 // Note we calculate the rounded long by ourselves, but still let String.format() 130 // compute the rounded value. String.format("%f", 0.1) might not return "0.1" due to 131 // floating point errors. 132 final int roundFactor; 133 final String roundFormat; 134 if (result < 1) { 135 roundFactor = 100; 136 roundFormat = "%.2f"; 137 } else if (result < 10) { 138 if ((flags & FLAG_SHORTER) != 0) { 139 roundFactor = 10; 140 roundFormat = "%.1f"; 141 } else { 142 roundFactor = 100; 143 roundFormat = "%.2f"; 144 } 145 } else if (result < 100) { 146 if ((flags & FLAG_SHORTER) != 0) { 147 roundFactor = 1; 148 roundFormat = "%.0f"; 149 } else { 150 roundFactor = 100; 151 roundFormat = "%.2f"; 152 } 153 } else { 154 roundFactor = 1; 155 roundFormat = "%.0f"; 156 } 157 final String roundedString = String.format(roundFormat, result); 158 159 // Note this might overflow if result >= Long.MAX_VALUE / 100, but that's like 80PB so 160 // it's okay (for now)... 161 final long roundedBytes = 162 (flags & FLAG_CALCULATE_ROUNDED) == 0 ? 0 163 : (((long) Math.round(result * roundFactor)) * mult / roundFactor); 164 165 final String units = res.getString(suffix); 166 167 return new BytesResult(roundedString, units, roundedBytes); 168 } 169 170 /** 171 * Returns a string in the canonical IPv4 format ###.###.###.### from a packed integer 172 * containing the IP address. The IPv4 address is expected to be in little-endian 173 * format (LSB first). That is, 0x01020304 will return "4.3.2.1". 174 * 175 * @deprecated Use {@link java.net.InetAddress#getHostAddress()}, which supports both IPv4 and 176 * IPv6 addresses. This method does not support IPv6 addresses. 177 */ 178 @Deprecated formatIpAddress(int ipv4Address)179 public static String formatIpAddress(int ipv4Address) { 180 return NetworkUtils.intToInetAddress(ipv4Address).getHostAddress(); 181 } 182 183 private static final int SECONDS_PER_MINUTE = 60; 184 private static final int SECONDS_PER_HOUR = 60 * 60; 185 private static final int SECONDS_PER_DAY = 24 * 60 * 60; 186 private static final int MILLIS_PER_MINUTE = 1000 * 60; 187 188 /** 189 * Returns elapsed time for the given millis, in the following format: 190 * 1 day 5 hrs; will include at most two units, can go down to seconds precision. 191 * @param context the application context 192 * @param millis the elapsed time in milli seconds 193 * @return the formatted elapsed time 194 * @hide 195 */ formatShortElapsedTime(Context context, long millis)196 public static String formatShortElapsedTime(Context context, long millis) { 197 long secondsLong = millis / 1000; 198 199 int days = 0, hours = 0, minutes = 0; 200 if (secondsLong >= SECONDS_PER_DAY) { 201 days = (int)(secondsLong / SECONDS_PER_DAY); 202 secondsLong -= days * SECONDS_PER_DAY; 203 } 204 if (secondsLong >= SECONDS_PER_HOUR) { 205 hours = (int)(secondsLong / SECONDS_PER_HOUR); 206 secondsLong -= hours * SECONDS_PER_HOUR; 207 } 208 if (secondsLong >= SECONDS_PER_MINUTE) { 209 minutes = (int)(secondsLong / SECONDS_PER_MINUTE); 210 secondsLong -= minutes * SECONDS_PER_MINUTE; 211 } 212 int seconds = (int)secondsLong; 213 214 if (days >= 2) { 215 days += (hours+12)/24; 216 return context.getString(com.android.internal.R.string.durationDays, days); 217 } else if (days > 0) { 218 if (hours == 1) { 219 return context.getString(com.android.internal.R.string.durationDayHour, days, hours); 220 } 221 return context.getString(com.android.internal.R.string.durationDayHours, days, hours); 222 } else if (hours >= 2) { 223 hours += (minutes+30)/60; 224 return context.getString(com.android.internal.R.string.durationHours, hours); 225 } else if (hours > 0) { 226 if (minutes == 1) { 227 return context.getString(com.android.internal.R.string.durationHourMinute, hours, 228 minutes); 229 } 230 return context.getString(com.android.internal.R.string.durationHourMinutes, hours, 231 minutes); 232 } else if (minutes >= 2) { 233 minutes += (seconds+30)/60; 234 return context.getString(com.android.internal.R.string.durationMinutes, minutes); 235 } else if (minutes > 0) { 236 if (seconds == 1) { 237 return context.getString(com.android.internal.R.string.durationMinuteSecond, minutes, 238 seconds); 239 } 240 return context.getString(com.android.internal.R.string.durationMinuteSeconds, minutes, 241 seconds); 242 } else if (seconds == 1) { 243 return context.getString(com.android.internal.R.string.durationSecond, seconds); 244 } else { 245 return context.getString(com.android.internal.R.string.durationSeconds, seconds); 246 } 247 } 248 249 /** 250 * Returns elapsed time for the given millis, in the following format: 251 * 1 day 5 hrs; will include at most two units, can go down to minutes precision. 252 * @param context the application context 253 * @param millis the elapsed time in milli seconds 254 * @return the formatted elapsed time 255 * @hide 256 */ formatShortElapsedTimeRoundingUpToMinutes(Context context, long millis)257 public static String formatShortElapsedTimeRoundingUpToMinutes(Context context, long millis) { 258 long minutesRoundedUp = (millis + MILLIS_PER_MINUTE - 1) / MILLIS_PER_MINUTE; 259 260 if (minutesRoundedUp == 0) { 261 return context.getString(com.android.internal.R.string.durationMinutes, 0); 262 } else if (minutesRoundedUp == 1) { 263 return context.getString(com.android.internal.R.string.durationMinute, 1); 264 } 265 266 return formatShortElapsedTime(context, minutesRoundedUp * MILLIS_PER_MINUTE); 267 } 268 } 269