blob: 5a54ba401177ce0af214d2cd85977dd345b4d17b [file] [log] [blame]
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -08001/**
2 * Copyright (C) 2007 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy
6 * 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, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16
17package com.android.settings;
18
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010019import android.annotation.Nullable;
Amith Yamasaniae697552011-09-27 11:33:17 -070020import android.app.ActivityManager;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010021import android.app.ActivityManagerNative;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070022import android.app.AlertDialog;
Sudheer Shankabc956302015-04-09 12:19:53 +010023import android.app.AppGlobals;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070024import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070025import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010026import android.app.IActivityManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010027import android.app.admin.DevicePolicyManager;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080028import android.content.ComponentName;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070029import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080030import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070031import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080032import android.content.Intent;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080033import android.content.IntentFilter;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080034import android.content.pm.ApplicationInfo;
Sudheer Shankabc956302015-04-09 12:19:53 +010035import android.content.pm.IPackageManager;
Christopher Tatea08a2252015-07-01 16:52:43 -070036import android.content.pm.IntentFilterVerificationInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020037import android.content.pm.PackageInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080038import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070039import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070040import android.content.pm.ResolveInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020041import android.content.pm.Signature;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070042import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020043import android.content.res.Resources;
Jason Monkb5aa73f2015-03-31 12:59:33 -040044import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070045import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070046import android.graphics.Bitmap;
47import android.graphics.BitmapFactory;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080048import android.net.ConnectivityManager;
49import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070050import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070051import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020052import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010053import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040054import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010055import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040056import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070057import android.os.UserHandle;
58import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080059import android.os.storage.StorageManager;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070060import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070061import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070062import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070063import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070064import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070065import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070066import android.service.persistentdata.PersistentDataBlockManager;
Jason Monk39b46742015-09-10 15:52:51 -040067import android.support.v7.preference.Preference;
68import android.support.v7.preference.PreferenceGroup;
Amith Yamasani60133dd2010-09-11 14:17:31 -070069import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040070import android.text.Spannable;
71import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020072import android.text.TextUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040073import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070074import android.util.ArraySet;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010075import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000076import android.util.SparseArray;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000077import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070078import android.view.View;
79import android.view.ViewGroup;
Jason Monkb5aa73f2015-03-31 12:59:33 -040080import android.view.animation.Animation;
81import android.view.animation.Animation.AnimationListener;
82import android.view.animation.AnimationUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070083import android.widget.ListView;
84import android.widget.TabWidget;
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010085import com.android.internal.util.UserIcons;
Jason Monkaf001092015-11-04 13:16:18 -050086import com.android.settingslib.drawer.UserAdapter;
87import com.android.settingslib.drawer.UserAdapter.UserDetails;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070088
Amith Yamasaniae47ef42012-09-16 17:53:35 -070089import java.io.IOException;
90import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080091import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070092import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010093import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080094import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070095import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090096import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080097
Tony Mantler67cd6ab2015-06-08 14:41:02 -070098import static android.content.Intent.EXTRA_USER;
99
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -0700100public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100101 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100102
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800103 /**
104 * Set the preference's title to the matching activity's label.
105 */
106 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
107
108 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900109 * The opacity level of a disabled icon.
110 */
111 public static final float DISABLED_ALPHA = 0.4f;
112
113 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700114 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
115 * 1 is most bad (red), the last value is least bad (green).
116 */
117 public static final int[] BADNESS_COLORS = new int[] {
118 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
119 0xfffabf2c, 0xff679e37, 0xff0a7f42
120 };
121
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100122 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
123
Elliott Hughes7253df32014-09-02 17:10:14 -0700124 private static final int SECONDS_PER_MINUTE = 60;
125 private static final int SECONDS_PER_HOUR = 60 * 60;
126 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
127
Jason Monkbeb171d2015-05-21 15:24:37 -0400128 public static final String OS_PKG = "os";
129
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000130 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
131
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200132 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800133 * Finds a matching activity for a preference's intent. If a matching
134 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800135 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800136 * @param context The context.
137 * @param parentPreferenceGroup The preference group that contains the
138 * preference whose intent is being resolved.
139 * @param preferenceKey The key of the preference whose intent is being
140 * resolved.
141 * @param flags 0 or one or more of
142 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
143 * .
144 * @return Whether an activity was found. If false, the preference was
145 * removed.
146 */
147 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
148 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800149
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800150 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
151 if (preference == null) {
152 return false;
153 }
Ying Wanga7188322010-01-04 18:45:10 -0800154
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800155 Intent intent = preference.getIntent();
156 if (intent != null) {
157 // Find the activity that is in the system image
158 PackageManager pm = context.getPackageManager();
159 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
160 int listSize = list.size();
161 for (int i = 0; i < listSize; i++) {
162 ResolveInfo resolveInfo = list.get(i);
163 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
164 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800165
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800166 // Replace the intent with this specific activity
167 preference.setIntent(new Intent().setClassName(
168 resolveInfo.activityInfo.packageName,
169 resolveInfo.activityInfo.name));
170
171 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
172 // Set the preference title to the activity's label
173 preference.setTitle(resolveInfo.loadLabel(pm));
174 }
Ying Wanga7188322010-01-04 18:45:10 -0800175
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800176 return true;
177 }
178 }
179 }
180
181 // Did not find a matching activity, so remove the preference
182 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800183
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900184 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800185 }
Ying Wanga7188322010-01-04 18:45:10 -0800186
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200187 /**
Ying Wanga7188322010-01-04 18:45:10 -0800188 * Returns true if Monkey is running.
189 */
190 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700191 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800192 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700193
194 /**
195 * Returns whether the device is voice-capable (meaning, it is also a phone).
196 */
197 public static boolean isVoiceCapable(Context context) {
198 TelephonyManager telephony =
199 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
200 return telephony != null && telephony.isVoiceCapable();
201 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800202
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700203 public static boolean isWifiOnly(Context context) {
204 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
205 Context.CONNECTIVITY_SERVICE);
206 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800207 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800208
209 /**
210 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
211 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900212 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800213 */
214 public static String getWifiIpAddresses(Context context) {
215 ConnectivityManager cm = (ConnectivityManager)
216 context.getSystemService(Context.CONNECTIVITY_SERVICE);
217 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700218 return formatIpAddresses(prop);
219 }
220
221 /**
222 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
223 * addresses.
224 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900225 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700226 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900227 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700228 LinkProperties prop = cm.getActiveLinkProperties();
229 return formatIpAddresses(prop);
230 }
231
232 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800233 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900234 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800235 // If there are no entries, return null
236 if (!iter.hasNext()) return null;
237 // Concatenate all available addresses, comma separated
238 String addresses = "";
239 while (iter.hasNext()) {
240 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900241 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800242 }
243 return addresses;
244 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900245
246 public static Locale createLocaleFromString(String localeStr) {
247 // TODO: is there a better way to actually construct a locale that will match?
248 // The main problem is, on top of Java specs, locale.toString() and
249 // new Locale(locale.toString()).toString() do not return equal() strings in
250 // many cases, because the constructor takes the only string as the language
251 // code. So : new Locale("en", "US").toString() => "en_US"
252 // And : new Locale("en_US").toString() => "en_us"
253 if (null == localeStr)
254 return Locale.getDefault();
255 String[] brokenDownLocale = localeStr.split("_", 3);
256 // split may not return a 0-length array.
257 if (1 == brokenDownLocale.length) {
258 return new Locale(brokenDownLocale[0]);
259 } else if (2 == brokenDownLocale.length) {
260 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
261 } else {
262 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
263 }
264 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700265
Elliott Hughes7253df32014-09-02 17:10:14 -0700266 /** Formats the ratio of amount/total as a percentage. */
267 public static String formatPercentage(long amount, long total) {
268 return formatPercentage(((double) amount) / total);
269 }
270
271 /** Formats an integer from 0..100 as a percentage. */
272 public static String formatPercentage(int percentage) {
273 return formatPercentage(((double) percentage) / 100.0);
274 }
275
276 /** Formats a double from 0.0..1.0 as a percentage. */
277 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700278 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700279 }
280
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900281 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
282 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
283 }
284
Amith Yamasania4379d62011-07-22 10:34:58 -0700285 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700286 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700287 }
288
289 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900290 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
291 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700292 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700293 }
294
295 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
296 final Intent intent = batteryChangedIntent;
297
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900298 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
299 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
300 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700301 String statusString;
302 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700303 int resId;
304 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
305 resId = R.string.battery_info_status_charging_ac;
306 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
307 resId = R.string.battery_info_status_charging_usb;
308 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
309 resId = R.string.battery_info_status_charging_wireless;
310 } else {
311 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700312 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700313 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700314 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
315 statusString = res.getString(R.string.battery_info_status_discharging);
316 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
317 statusString = res.getString(R.string.battery_info_status_not_charging);
318 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
319 statusString = res.getString(R.string.battery_info_status_full);
320 } else {
321 statusString = res.getString(R.string.battery_info_status_unknown);
322 }
323
324 return statusString;
325 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700326
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800327 public static void forcePrepareCustomPreferencesList(
328 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
329 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
330 list.setClipToPadding(false);
331 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
332 }
333
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700334 /**
335 * Prepare a custom preferences layout, moving padding to {@link ListView}
336 * when outside scrollbars are requested. Usually used to display
337 * {@link ListView} and {@link TabWidget} with correct padding.
338 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700339 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800340 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700341 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700342 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700343 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700344 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700345 final int paddingBottom = res.getDimensionPixelSize(
346 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700347
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700348 if (parent instanceof PreferenceFrameLayout) {
349 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
350
351 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
352 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
353 } else {
354 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
355 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700356 }
357 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700358
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700359 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700360 final Resources res = view.getResources();
361 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700362
363 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
364 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700365 final int paddingBottom = res.getDimensionPixelSize(
366 com.android.internal.R.dimen.preference_fragment_padding_bottom);
367
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700368 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700369 }
370
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700371 /* Used by UserSettings as well. Call this on a non-ui thread. */
372 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
373 Uri contactUri = Profile.CONTENT_URI;
374
375 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
376 context.getContentResolver(),
377 contactUri, true);
378 // If there's no profile photo, assign a default avatar
379 if (avatarDataStream == null) {
380 return false;
381 }
382 int userId = user != null ? user.id : UserHandle.myUserId();
383 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700384 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
385 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700386 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700387 avatarDataStream.close();
388 } catch (IOException ioe) { }
389 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700390 }
391
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700392 public static String getMeProfileName(Context context, boolean full) {
393 if (full) {
394 return getProfileDisplayName(context);
395 } else {
396 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700397 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700398 }
399
400 private static String getShorterNameIfPossible(Context context) {
401 final String given = getLocalProfileGivenName(context);
402 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
403 }
404
405 private static String getLocalProfileGivenName(Context context) {
406 final ContentResolver cr = context.getContentResolver();
407
408 // Find the raw contact ID for the local ME profile raw contact.
409 final long localRowProfileId;
410 final Cursor localRawProfile = cr.query(
411 Profile.CONTENT_RAW_CONTACTS_URI,
412 new String[] {RawContacts._ID},
413 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
414 RawContacts.ACCOUNT_NAME + " IS NULL",
415 null, null);
416 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700417
418 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700419 if (!localRawProfile.moveToFirst()) {
420 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700421 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700422 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700423 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700424 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700425 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700426
427 // Find the structured name for the raw contact.
428 final Cursor structuredName = cr.query(
429 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
430 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
431 CommonDataKinds.StructuredName.FAMILY_NAME},
432 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
433 null, null);
434 if (structuredName == null) return null;
435
436 try {
437 if (!structuredName.moveToFirst()) {
438 return null;
439 }
440 String partialName = structuredName.getString(0);
441 if (TextUtils.isEmpty(partialName)) {
442 partialName = structuredName.getString(1);
443 }
444 return partialName;
445 } finally {
446 structuredName.close();
447 }
448 }
449
450 private static final String getProfileDisplayName(Context context) {
451 final ContentResolver cr = context.getContentResolver();
452 final Cursor profile = cr.query(Profile.CONTENT_URI,
453 new String[] {Profile.DISPLAY_NAME}, null, null, null);
454 if (profile == null) return null;
455
456 try {
457 if (!profile.moveToFirst()) {
458 return null;
459 }
460 return profile.getString(0);
461 } finally {
462 profile.close();
463 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700464 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700465
466 /** Not global warming, it's global change warning. */
467 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
468 final Runnable positiveAction) {
469 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
470 builder.setTitle(titleResId);
471 builder.setMessage(R.string.global_change_warning);
472 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
473 @Override
474 public void onClick(DialogInterface dialog, int which) {
475 positiveAction.run();
476 }
477 });
478 builder.setNegativeButton(android.R.string.cancel, null);
479
480 return builder.create();
481 }
482
483 public static boolean hasMultipleUsers(Context context) {
484 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
485 .getUsers().size() > 1;
486 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700487
488 /**
489 * Start a new instance of the activity, showing only the given fragment.
490 * When launched in this mode, the given preference fragment will be instantiated and fill the
491 * entire activity.
492 *
493 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000494 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700495 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700496 * @param resultTo Option fragment that should receive the result of the activity launch.
497 * @param resultRequestCode If resultTo is non-null, this is the request code in which
498 * to report the result.
499 * @param titleResId resource id for the String to display for the title of this set
500 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700501 * @param title String to display for the title of this set of preferences.
502 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000503 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100504 Fragment resultTo, int resultRequestCode, int titleResId,
505 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700506 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100507 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
508 }
509
510 /**
511 * Start a new instance of the activity, showing only the given fragment.
512 * When launched in this mode, the given preference fragment will be instantiated and fill the
513 * entire activity.
514 *
515 * @param context The context.
516 * @param fragmentName The name of the fragment to display.
517 * @param args Optional arguments to supply to the fragment.
518 * @param resultTo Option fragment that should receive the result of the activity launch.
519 * @param resultRequestCode If resultTo is non-null, this is the request code in which
520 * to report the result.
521 * @param titleResPackageName Optional package name for the resource id of the title.
522 * @param titleResId resource id for the String to display for the title of this set
523 * of preferences.
524 * @param title String to display for the title of this set of preferences.
525 */
526 public static void startWithFragment(Context context, String fragmentName, Bundle args,
527 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
528 CharSequence title) {
529 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
530 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700531 }
532
533 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100534 Fragment resultTo, int resultRequestCode, int titleResId,
535 CharSequence title, boolean isShortcut) {
536 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
537 null /* titleResPackageName */, titleResId, title, isShortcut);
538 if (resultTo == null) {
539 context.startActivity(intent);
540 } else {
541 resultTo.startActivityForResult(intent, resultRequestCode);
542 }
543 }
544
545 public static void startWithFragment(Context context, String fragmentName, Bundle args,
546 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
547 CharSequence title, boolean isShortcut) {
548 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
549 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700550 if (resultTo == null) {
551 context.startActivity(intent);
552 } else {
553 resultTo.startActivityForResult(intent, resultRequestCode);
554 }
555 }
556
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100557 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100558 int titleResId, CharSequence title, boolean isShortcut,
559 UserHandle userHandle) {
560 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
561 null /* titleResPackageName */, titleResId, title, isShortcut);
562 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
563 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
564 context.startActivityAsUser(intent, userHandle);
565 }
566
567 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
568 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
569 UserHandle userHandle) {
570 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
571 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100572 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
573 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100574 context.startActivityAsUser(intent, userHandle);
575 }
576
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700577 /**
578 * Build an Intent to launch a new activity showing the selected fragment.
579 * The implementation constructs an Intent that re-launches the current activity with the
580 * appropriate arguments to display the fragment.
581 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700582 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700583 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000584 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700585 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100586 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700587 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700588 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700589 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700590 * @return Returns an Intent that can be launched to display the given
591 * fragment.
592 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000593 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100594 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
595 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700596 Intent intent = new Intent(Intent.ACTION_MAIN);
597 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000598 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700599 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100600 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
601 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700602 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700603 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700604 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700605 return intent;
606 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100607
608 /**
609 * Returns the managed profile of the current user or null if none found.
610 */
611 public static UserHandle getManagedProfile(UserManager userManager) {
612 List<UserHandle> userProfiles = userManager.getUserProfiles();
613 final int count = userProfiles.size();
614 for (int i = 0; i < count; i++) {
615 final UserHandle profile = userProfiles.get(i);
616 if (profile.getIdentifier() == userManager.getUserHandle()) {
617 continue;
618 }
619 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
620 if (userInfo.isManagedProfile()) {
621 return profile;
622 }
623 }
624 return null;
625 }
626
627 /**
628 * Returns true if the current profile is a managed one.
629 */
630 public static boolean isManagedProfile(UserManager userManager) {
631 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
632 return currentUser.isManagedProfile();
633 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100634
635 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100636 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100637 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100638 * The target user can be either the current user, the user that launched this activity or
639 * the user contained as an extra in the arguments or intent extras.
640 *
641 * Note: This is secure in the sense that it only returns a target user different to the current
642 * one if the app launching this activity is the Settings app itself, running in the same user
643 * or in one that is in the same profile group, or if the user id is provided by the system.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100644 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100645 public static UserHandle getSecureTargetUser(IBinder activityToken,
646 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
647 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
648 IActivityManager am = ActivityManagerNative.getDefault();
649 try {
650 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
651 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
652
653 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
654 am.getLaunchedFromUid(activityToken)));
655 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
656 // Check it's secure
657 if (isProfileOf(um, launchedFromUser)) {
658 return launchedFromUser;
659 }
660 }
661 UserHandle extrasUser = intentExtras != null
662 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
663 if (extrasUser != null && !extrasUser.equals(currentUser)) {
664 // Check it's secure
665 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
666 return extrasUser;
667 }
668 }
669 UserHandle argumentsUser = arguments != null
670 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
671 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
672 // Check it's secure
673 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
674 return argumentsUser;
675 }
676 }
677 } catch (RemoteException e) {
678 // Should not happen
679 Log.v(TAG, "Could not talk to activity manager.", e);
680 }
681 return currentUser;
682 }
683
684 /**
685 * Returns the target user for a Settings activity.
686 *
687 * The target user can be either the current user, the user that launched this activity or
688 * the user contained as an extra in the arguments or intent extras.
689 *
690 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
691 * possible.
692 *
693 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
694 */
695 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
696 @Nullable Bundle intentExtras) {
697 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
698 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100699 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100700 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
701 am.getLaunchedFromUid(activityToken)));
702 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
703 return launchedFromUser;
704 }
705 UserHandle extrasUser = intentExtras != null
706 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
707 if (extrasUser != null && !extrasUser.equals(currentUser)) {
708 return extrasUser;
709 }
710 UserHandle argumentsUser = arguments != null
711 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
712 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
713 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100714 }
715 } catch (RemoteException e) {
716 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100717 Log.v(TAG, "Could not talk to activity manager.", e);
718 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100719 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100720 return currentUser;
721 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100722
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100723 /**
724 * Returns true if the user provided is in the same profiles group as the current user.
725 */
726 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
727 if (um == null || otherUser == null) return false;
728 return (UserHandle.myUserId() == otherUser.getIdentifier())
729 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100730 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530731
Andres Moralesce249fe2014-07-07 16:58:16 -0700732
733 /**
734 * Returns whether or not this device is able to be OEM unlocked.
735 */
736 static boolean isOemUnlockEnabled(Context context) {
737 PersistentDataBlockManager manager =(PersistentDataBlockManager)
738 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
739 return manager.getOemUnlockEnabled();
740 }
741
742 /**
743 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
744 * devices allow users to flash other OSes to them.
745 */
746 static void setOemUnlockEnabled(Context context, boolean enabled) {
747 PersistentDataBlockManager manager =(PersistentDataBlockManager)
748 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
749 manager.setOemUnlockEnabled(enabled);
750 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100751
752 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700753 * Return whether or not the user should have a SIM Cards option in Settings.
754 * TODO: Change back to returning true if count is greater than one after testing.
755 * TODO: See bug 16533525.
756 */
757 public static boolean showSimCardTile(Context context) {
758 final TelephonyManager tm =
759 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
760
PauloftheWestdbd03822014-12-04 11:56:35 -0800761 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700762 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200763
764 /**
765 * Determine whether a package is a "system package", in which case certain things (like
766 * disabling notifications or disabling the package altogether) should be disallowed.
767 */
768 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
769 if (sSystemSignature == null) {
770 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
771 }
772 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
773 }
774
775 private static Signature[] sSystemSignature;
776
777 private static Signature getFirstSignature(PackageInfo pkg) {
778 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
779 return pkg.signatures[0];
780 }
781 return null;
782 }
783
784 private static Signature getSystemSignature(PackageManager pm) {
785 try {
786 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
787 return getFirstSignature(sys);
788 } catch (NameNotFoundException e) {
789 }
790 return null;
791 }
792
Elliott Hughes7253df32014-09-02 17:10:14 -0700793 /**
794 * Returns elapsed time for the given millis, in the following format:
795 * 2d 5h 40m 29s
796 * @param context the application context
797 * @param millis the elapsed time in milli seconds
798 * @param withSeconds include seconds?
799 * @return the formatted elapsed time
800 */
801 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
802 StringBuilder sb = new StringBuilder();
803 int seconds = (int) Math.floor(millis / 1000);
804 if (!withSeconds) {
805 // Round up.
806 seconds += 30;
807 }
808
809 int days = 0, hours = 0, minutes = 0;
810 if (seconds >= SECONDS_PER_DAY) {
811 days = seconds / SECONDS_PER_DAY;
812 seconds -= days * SECONDS_PER_DAY;
813 }
814 if (seconds >= SECONDS_PER_HOUR) {
815 hours = seconds / SECONDS_PER_HOUR;
816 seconds -= hours * SECONDS_PER_HOUR;
817 }
818 if (seconds >= SECONDS_PER_MINUTE) {
819 minutes = seconds / SECONDS_PER_MINUTE;
820 seconds -= minutes * SECONDS_PER_MINUTE;
821 }
822 if (withSeconds) {
823 if (days > 0) {
824 sb.append(context.getString(R.string.battery_history_days,
825 days, hours, minutes, seconds));
826 } else if (hours > 0) {
827 sb.append(context.getString(R.string.battery_history_hours,
828 hours, minutes, seconds));
829 } else if (minutes > 0) {
830 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
831 } else {
832 sb.append(context.getString(R.string.battery_history_seconds, seconds));
833 }
834 } else {
835 if (days > 0) {
836 sb.append(context.getString(R.string.battery_history_days_no_seconds,
837 days, hours, minutes));
838 } else if (hours > 0) {
839 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
840 hours, minutes));
841 } else {
842 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
843 }
844 }
845 return sb.toString();
846 }
PauloftheWest0a0daca2014-11-06 15:02:58 -0800847
848 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800849 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
850 * @param userManager Instance of UserManager
851 * @param checkUser The user to check the existence of.
852 * @return UserInfo of the user or null for non-existent user.
853 */
854 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
855 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
856 final int checkUserId = checkUser.getIdentifier();
857 for (UserInfo user : users) {
858 if (user.id == checkUserId) {
859 return user;
860 }
861 }
862 return null;
863 }
864
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000865 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
866 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
867 com.android.internal.R.styleable.Preference,
868 com.android.internal.R.attr.preferenceCategoryStyle, 0);
869 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
870 0);
871 a.recycle();
872 return inflater.inflate(resId, parent, false);
873 }
874
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -0800875 /**
876 * Return if we are running low on storage space or not.
877 *
878 * @param context The context
879 * @return true if we are running low on storage space
880 */
881 public static boolean isLowStorage(Context context) {
882 final StorageManager sm = StorageManager.from(context);
883 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
884 }
885
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000886 /**
887 * Returns a default user icon (as a {@link Bitmap}) for the given user.
888 *
889 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
890 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
891 */
892 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
893 Bitmap bitmap = null;
894 // Try finding the corresponding bitmap in the dark bitmap cache
895 bitmap = sDarkDefaultUserBitmapCache.get(userId);
896 if (bitmap == null) {
897 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
898 // Save it to cache
899 sDarkDefaultUserBitmapCache.put(userId, bitmap);
900 }
901 return bitmap;
902 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800903
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800904 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
905 // Get list of preferred activities
906 List<ComponentName> prefActList = new ArrayList<>();
907 // Intent list cannot be null. so pass empty list
908 List<IntentFilter> intentList = new ArrayList<>();
909 pm.getPreferredActivities(intentList, prefActList, packageName);
910 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
911 return prefActList.size() > 0;
912 }
913
Christopher Tatea08a2252015-07-01 16:52:43 -0700914 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
915 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
916 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
917
918 ArraySet<String> result = new ArraySet<>();
919 if (iviList.size() > 0) {
920 for (IntentFilterVerificationInfo ivi : iviList) {
921 for (String host : ivi.getDomains()) {
922 result.add(host);
923 }
924 }
925 }
926 if (filters != null && filters.size() > 0) {
927 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700928 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
929 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
930 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700931 result.addAll(filter.getHostsList());
932 }
933 }
934 }
935 return result;
936 }
937
Jason Monkb5aa73f2015-03-31 12:59:33 -0400938 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
939 boolean animate) {
940 setViewShown(loading, !done, animate);
941 setViewShown(doneLoading, done, animate);
942 }
943
944 private static void setViewShown(final View view, boolean shown, boolean animate) {
945 if (animate) {
946 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
947 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
948 if (shown) {
949 view.setVisibility(View.VISIBLE);
950 } else {
951 animation.setAnimationListener(new AnimationListener() {
952 @Override
953 public void onAnimationStart(Animation animation) {
954 }
955
956 @Override
957 public void onAnimationRepeat(Animation animation) {
958 }
959
960 @Override
961 public void onAnimationEnd(Animation animation) {
962 view.setVisibility(View.INVISIBLE);
963 }
964 });
965 }
966 view.startAnimation(animation);
967 } else {
968 view.clearAnimation();
969 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
970 }
971 }
Sudheer Shankabc956302015-04-09 12:19:53 +0100972
973 /**
974 * Returns the application info of the currently installed MDM package.
975 */
976 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
977 DevicePolicyManager dpm =
978 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
979 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
980 if (mdmPackage == null) {
981 return null;
982 }
983 String mdmPackageName = mdmPackage.getPackageName();
984 try {
985 IPackageManager ipm = AppGlobals.getPackageManager();
986 ApplicationInfo mdmApplicationInfo =
987 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
988 return mdmApplicationInfo;
989 } catch (RemoteException e) {
990 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
991 + ", userId " + profileId, e);
992 return null;
993 }
994 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400995
996 public static boolean isBandwidthControlEnabled() {
997 final INetworkManagementService netManager = INetworkManagementService.Stub
998 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
999 try {
1000 return netManager.isBandwidthControlEnabled();
1001 } catch (RemoteException e) {
1002 return false;
1003 }
1004 }
Julia Reynoldsce25af42015-07-08 16:56:31 -04001005
1006 /**
1007 * Returns an accessible SpannableString.
1008 * @param displayText the text to display
1009 * @param accessibileText the text text-to-speech engines should read
1010 */
1011 public static SpannableString createAccessibleSequence(CharSequence displayText,
1012 String accessibileText) {
1013 SpannableString str = new SpannableString(displayText);
1014 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
1015 displayText.length(),
1016 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1017 return str;
1018 }
Andres Morales7bdffd82015-08-04 16:55:00 -07001019
Clara Bayarrife432e82015-10-12 12:07:02 +01001020 /**
1021 * Returns the user id present in the bundle with {@link ChooseLockGeneric#KEY_USER_ID} if it
1022 * belongs to the current user.
1023 *
1024 * @throws SecurityException if the given userId does not belong to the current user group.
1025 */
1026 public static int getSameOwnerUserId(Context context, Bundle bundle) {
1027 if (bundle == null) {
1028 return getEffectiveUserId(context);
1029 }
1030 int userId = bundle.getInt(ChooseLockGeneric.KEY_USER_ID, UserHandle.myUserId());
1031 return getSameOwnerUserId(context, userId);
1032 }
1033
1034 /**
1035 * Returns the given user id if it belongs to the current user.
1036 *
1037 * @throws SecurityException if the given userId does not belong to the current user group.
1038 */
1039 public static int getSameOwnerUserId(Context context, int userId) {
1040 UserManager um = UserManager.get(context);
1041 if (um != null) {
1042 if (um.getUserProfiles().contains(new UserHandle(userId))) {
1043 return userId;
1044 } else {
1045 throw new SecurityException("Given user id " + userId + " does not belong to user "
1046 + UserHandle.myUserId());
1047 }
1048 }
1049 return getEffectiveUserId(context);
1050 }
1051
Andres Morales7bdffd82015-08-04 16:55:00 -07001052 public static int getEffectiveUserId(Context context) {
1053 UserManager um = UserManager.get(context);
1054 if (um != null) {
1055 return um.getCredentialOwnerProfile(UserHandle.myUserId());
1056 } else {
1057 Log.e(TAG, "Unable to acquire UserManager");
1058 return UserHandle.myUserId();
1059 }
1060 }
1061}
1062