OSDN Git Service

Make precentage calculation round up by 0.5%
[android-x86/frameworks-base.git] / packages / SettingsLib / src / com / android / settingslib / Utils.java
1 package com.android.settingslib;
2
3 import android.annotation.ColorInt;
4 import android.content.Context;
5 import android.content.Intent;
6 import android.content.pm.PackageInfo;
7 import android.content.pm.PackageManager;
8 import android.content.pm.PackageManager.NameNotFoundException;
9 import android.content.pm.Signature;
10 import android.content.pm.UserInfo;
11 import android.content.res.ColorStateList;
12 import android.content.res.Resources;
13 import android.content.res.TypedArray;
14 import android.graphics.Bitmap;
15 import android.graphics.BitmapFactory;
16 import android.graphics.Color;
17 import android.graphics.drawable.Drawable;
18 import android.graphics.drawable.LayerDrawable;
19 import android.net.ConnectivityManager;
20 import android.net.NetworkBadging;
21 import android.os.BatteryManager;
22 import android.os.UserManager;
23 import android.print.PrintManager;
24 import android.view.View;
25
26 import com.android.internal.util.UserIcons;
27 import com.android.settingslib.drawable.UserIconDrawable;
28
29 import java.text.NumberFormat;
30
31 public class Utils {
32     private static Signature[] sSystemSignature;
33     private static String sPermissionControllerPackageName;
34     private static String sServicesSystemSharedLibPackageName;
35     private static String sSharedSystemSharedLibPackageName;
36
37     public static final int[] WIFI_PIE_FOR_BADGING = {
38           com.android.internal.R.drawable.ic_signal_wifi_badged_0_bars,
39           com.android.internal.R.drawable.ic_signal_wifi_badged_1_bar,
40           com.android.internal.R.drawable.ic_signal_wifi_badged_2_bars,
41           com.android.internal.R.drawable.ic_signal_wifi_badged_3_bars,
42           com.android.internal.R.drawable.ic_signal_wifi_badged_4_bars
43     };
44
45     /**
46      * Return string resource that best describes combination of tethering
47      * options available on this device.
48      */
49     public static int getTetheringLabel(ConnectivityManager cm) {
50         String[] usbRegexs = cm.getTetherableUsbRegexs();
51         String[] wifiRegexs = cm.getTetherableWifiRegexs();
52         String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
53
54         boolean usbAvailable = usbRegexs.length != 0;
55         boolean wifiAvailable = wifiRegexs.length != 0;
56         boolean bluetoothAvailable = bluetoothRegexs.length != 0;
57
58         if (wifiAvailable && usbAvailable && bluetoothAvailable) {
59             return R.string.tether_settings_title_all;
60         } else if (wifiAvailable && usbAvailable) {
61             return R.string.tether_settings_title_all;
62         } else if (wifiAvailable && bluetoothAvailable) {
63             return R.string.tether_settings_title_all;
64         } else if (wifiAvailable) {
65             return R.string.tether_settings_title_wifi;
66         } else if (usbAvailable && bluetoothAvailable) {
67             return R.string.tether_settings_title_usb_bluetooth;
68         } else if (usbAvailable) {
69             return R.string.tether_settings_title_usb;
70         } else {
71             return R.string.tether_settings_title_bluetooth;
72         }
73     }
74
75     /**
76      * Returns a label for the user, in the form of "User: user name" or "Work profile".
77      */
78     public static String getUserLabel(Context context, UserInfo info) {
79         String name = info != null ? info.name : null;
80         if (info.isManagedProfile()) {
81             // We use predefined values for managed profiles
82             return context.getString(R.string.managed_user_title);
83         } else if (info.isGuest()) {
84             name = context.getString(R.string.user_guest);
85         }
86         if (name == null && info != null) {
87             name = Integer.toString(info.id);
88         } else if (info == null) {
89             name = context.getString(R.string.unknown);
90         }
91         return context.getResources().getString(R.string.running_process_item_user_label, name);
92     }
93
94     /**
95      * Returns a circular icon for a user.
96      */
97     public static UserIconDrawable getUserIcon(Context context, UserManager um, UserInfo user) {
98         final int iconSize = UserIconDrawable.getSizeForList(context);
99         if (user.isManagedProfile()) {
100             // We use predefined values for managed profiles
101             Bitmap b = BitmapFactory.decodeResource(context.getResources(),
102                     com.android.internal.R.drawable.ic_corp_icon);
103             return new UserIconDrawable(iconSize).setIcon(b).bake();
104         }
105         if (user.iconPath != null) {
106             Bitmap icon = um.getUserIcon(user.id);
107             if (icon != null) {
108                 return new UserIconDrawable(iconSize).setIcon(icon).bake();
109             }
110         }
111         return new UserIconDrawable(iconSize).setIconDrawable(
112                 UserIcons.getDefaultUserIcon(user.id, /* light= */ false)).bake();
113     }
114
115     /** Formats a double from 0.0..100.0 with an option to round **/
116     public static String formatPercentage(double percentage, boolean round) {
117         final int localPercentage = round ? Math.round((float) percentage) : (int) percentage;
118         return formatPercentage(localPercentage);
119     }
120
121     /** Formats the ratio of amount/total as a percentage. */
122     public static String formatPercentage(long amount, long total) {
123         return formatPercentage(((double) amount) / total);
124     }
125
126     /** Formats an integer from 0..100 as a percentage. */
127     public static String formatPercentage(int percentage) {
128         return formatPercentage(((double) percentage) / 100.0);
129     }
130
131     /** Formats a double from 0.0..1.0 as a percentage. */
132     private static String formatPercentage(double percentage) {
133         return NumberFormat.getPercentInstance().format(percentage);
134     }
135
136     public static int getBatteryLevel(Intent batteryChangedIntent) {
137         int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
138         int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
139         return (level * 100) / scale;
140     }
141
142     public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
143         return Utils.getBatteryStatus(res, batteryChangedIntent, false);
144     }
145
146     public static String getBatteryStatus(Resources res, Intent batteryChangedIntent,
147             boolean shortString) {
148         int plugType = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
149         int status = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_STATUS,
150                 BatteryManager.BATTERY_STATUS_UNKNOWN);
151         String statusString;
152         if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
153             int resId;
154             if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
155                 resId = shortString ? R.string.battery_info_status_charging_ac_short
156                         : R.string.battery_info_status_charging_ac;
157             } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
158                 resId = shortString ? R.string.battery_info_status_charging_usb_short
159                         : R.string.battery_info_status_charging_usb;
160             } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
161                 resId = shortString ? R.string.battery_info_status_charging_wireless_short
162                         : R.string.battery_info_status_charging_wireless;
163             } else {
164                 resId = R.string.battery_info_status_charging;
165             }
166             statusString = res.getString(resId);
167         } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
168             statusString = res.getString(R.string.battery_info_status_discharging);
169         } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
170             statusString = res.getString(R.string.battery_info_status_not_charging);
171         } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
172             statusString = res.getString(R.string.battery_info_status_full);
173         } else {
174             statusString = res.getString(R.string.battery_info_status_unknown);
175         }
176
177         return statusString;
178     }
179
180     @ColorInt
181     public static int getColorAccent(Context context) {
182         return getColorAttr(context, android.R.attr.colorAccent);
183     }
184
185     @ColorInt
186     public static int getColorError(Context context) {
187         TypedArray ta = context.obtainStyledAttributes(new int[]{android.R.attr.textColorError});
188         @ColorInt int colorError = ta.getColor(0, 0);
189         ta.recycle();
190         return colorError;
191     }
192
193     @ColorInt
194     public static int getDefaultColor(Context context, int resId) {
195         final ColorStateList list =
196                 context.getResources().getColorStateList(resId, context.getTheme());
197
198         return list.getDefaultColor();
199     }
200
201     @ColorInt
202     public static int getDisabled(Context context, int inputColor) {
203         return applyAlphaAttr(context, android.R.attr.disabledAlpha, inputColor);
204     }
205
206     @ColorInt
207     public static int applyAlphaAttr(Context context, int attr, int inputColor) {
208         TypedArray ta = context.obtainStyledAttributes(new int[]{attr});
209         float alpha = ta.getFloat(0, 0);
210         ta.recycle();
211         alpha *= Color.alpha(inputColor);
212         return Color.argb((int) (alpha), Color.red(inputColor), Color.green(inputColor),
213                 Color.blue(inputColor));
214     }
215
216     @ColorInt
217     public static int getColorAttr(Context context, int attr) {
218         TypedArray ta = context.obtainStyledAttributes(new int[]{attr});
219         @ColorInt int colorAccent = ta.getColor(0, 0);
220         ta.recycle();
221         return colorAccent;
222     }
223
224     public static Drawable getDrawable(Context context, int attr) {
225         TypedArray ta = context.obtainStyledAttributes(new int[]{attr});
226         Drawable drawable = ta.getDrawable(0);
227         ta.recycle();
228         return drawable;
229     }
230
231     /**
232      * Determine whether a package is a "system package", in which case certain things (like
233      * disabling notifications or disabling the package altogether) should be disallowed.
234      */
235     public static boolean isSystemPackage(Resources resources, PackageManager pm, PackageInfo pkg) {
236         if (sSystemSignature == null) {
237             sSystemSignature = new Signature[]{ getSystemSignature(pm) };
238         }
239         if (sPermissionControllerPackageName == null) {
240             sPermissionControllerPackageName = pm.getPermissionControllerPackageName();
241         }
242         if (sServicesSystemSharedLibPackageName == null) {
243             sServicesSystemSharedLibPackageName = pm.getServicesSystemSharedLibraryPackageName();
244         }
245         if (sSharedSystemSharedLibPackageName == null) {
246             sSharedSystemSharedLibPackageName = pm.getSharedSystemSharedLibraryPackageName();
247         }
248         return (sSystemSignature[0] != null
249                         && sSystemSignature[0].equals(getFirstSignature(pkg)))
250                 || pkg.packageName.equals(sPermissionControllerPackageName)
251                 || pkg.packageName.equals(sServicesSystemSharedLibPackageName)
252                 || pkg.packageName.equals(sSharedSystemSharedLibPackageName)
253                 || pkg.packageName.equals(PrintManager.PRINT_SPOOLER_PACKAGE_NAME)
254                 || isDeviceProvisioningPackage(resources, pkg.packageName);
255     }
256
257     private static Signature getFirstSignature(PackageInfo pkg) {
258         if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
259             return pkg.signatures[0];
260         }
261         return null;
262     }
263
264     private static Signature getSystemSignature(PackageManager pm) {
265         try {
266             final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
267             return getFirstSignature(sys);
268         } catch (NameNotFoundException e) {
269         }
270         return null;
271     }
272
273     /**
274      * Returns {@code true} if the supplied package is the device provisioning app. Otherwise,
275      * returns {@code false}.
276      */
277     public static boolean isDeviceProvisioningPackage(Resources resources, String packageName) {
278         String deviceProvisioningPackage = resources.getString(
279                 com.android.internal.R.string.config_deviceProvisioningPackage);
280         return deviceProvisioningPackage != null && deviceProvisioningPackage.equals(packageName);
281     }
282
283     /**
284      * Returns a badged Wifi icon drawable.
285      *
286      * <p>The first layer contains the Wifi pie and the second layer contains the badge. Callers
287      * should set the drawable to the appropriate size and tint color.
288      *
289      * @param context The caller's context (must have access to internal resources)
290      * @param level The number of bars to show (0-4)
291      * @param badge The badge enum {@see android.net.ScoredNetwork}
292      *
293      * @throws IllegalArgumentException if an invalid badge enum is given
294      *
295      * @deprecated TODO(sghuman): Finalize the form of this method and then move it to a new
296      *         location.
297      */
298     public static LayerDrawable getBadgedWifiIcon(Context context, int level, int badge) {
299         return new LayerDrawable(
300                 new Drawable[] {
301                         context.getDrawable(WIFI_PIE_FOR_BADGING[level]),
302                         context.getDrawable(getWifiBadgeResource(badge))
303                 });
304     }
305
306     /**
307      * Returns the resource id for the given badge or {@link View.NO_ID} if no badge is to be shown.
308      *
309      * @throws IllegalArgumentException if the given badge value is not supported.
310      */
311     public static int getWifiBadgeResource(int badge) {
312         switch (badge) {
313             case NetworkBadging.BADGING_NONE:
314                 return View.NO_ID;
315             case NetworkBadging.BADGING_SD:
316                 return com.android.internal.R.drawable.ic_signal_wifi_badged_sd;
317             case NetworkBadging.BADGING_HD:
318                 return com.android.internal.R.drawable.ic_signal_wifi_badged_hd;
319             case NetworkBadging.BADGING_4K:
320                 return com.android.internal.R.drawable.ic_signal_wifi_badged_4k;
321             default:
322                 throw new IllegalArgumentException(
323                     "No badge resource found for badge value: " + badge);
324         }
325     }
326 }