blob: ddea92b24be77c53fb0efe573456c588b9642c38 [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;
Jason Monkdb4ed192015-12-11 16:48:31 -050077import android.util.TypedValue;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000078import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070079import android.view.View;
80import android.view.ViewGroup;
Jason Monkb5aa73f2015-03-31 12:59:33 -040081import android.view.animation.Animation;
82import android.view.animation.Animation.AnimationListener;
83import android.view.animation.AnimationUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070084import android.widget.ListView;
85import android.widget.TabWidget;
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010086import com.android.internal.util.UserIcons;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070087
Amith Yamasaniae47ef42012-09-16 17:53:35 -070088import java.io.IOException;
89import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080090import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070091import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010092import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080093import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070094import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090095import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080096
Tony Mantler67cd6ab2015-06-08 14:41:02 -070097import static android.content.Intent.EXTRA_USER;
98
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070099public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100100 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100101
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800102 /**
103 * Set the preference's title to the matching activity's label.
104 */
105 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
106
107 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900108 * The opacity level of a disabled icon.
109 */
110 public static final float DISABLED_ALPHA = 0.4f;
111
112 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700113 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
114 * 1 is most bad (red), the last value is least bad (green).
115 */
116 public static final int[] BADNESS_COLORS = new int[] {
117 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
118 0xfffabf2c, 0xff679e37, 0xff0a7f42
119 };
120
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100121 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
122
Elliott Hughes7253df32014-09-02 17:10:14 -0700123 private static final int SECONDS_PER_MINUTE = 60;
124 private static final int SECONDS_PER_HOUR = 60 * 60;
125 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
126
Jason Monkbeb171d2015-05-21 15:24:37 -0400127 public static final String OS_PKG = "os";
128
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000129 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
130
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200131 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800132 * Finds a matching activity for a preference's intent. If a matching
133 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800134 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800135 * @param context The context.
136 * @param parentPreferenceGroup The preference group that contains the
137 * preference whose intent is being resolved.
138 * @param preferenceKey The key of the preference whose intent is being
139 * resolved.
140 * @param flags 0 or one or more of
141 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
142 * .
143 * @return Whether an activity was found. If false, the preference was
144 * removed.
145 */
146 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
147 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800148
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800149 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
150 if (preference == null) {
151 return false;
152 }
Ying Wanga7188322010-01-04 18:45:10 -0800153
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800154 Intent intent = preference.getIntent();
155 if (intent != null) {
156 // Find the activity that is in the system image
157 PackageManager pm = context.getPackageManager();
158 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
159 int listSize = list.size();
160 for (int i = 0; i < listSize; i++) {
161 ResolveInfo resolveInfo = list.get(i);
162 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
163 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800164
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800165 // Replace the intent with this specific activity
166 preference.setIntent(new Intent().setClassName(
167 resolveInfo.activityInfo.packageName,
168 resolveInfo.activityInfo.name));
169
170 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
171 // Set the preference title to the activity's label
172 preference.setTitle(resolveInfo.loadLabel(pm));
173 }
Ying Wanga7188322010-01-04 18:45:10 -0800174
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800175 return true;
176 }
177 }
178 }
179
180 // Did not find a matching activity, so remove the preference
181 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800182
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900183 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800184 }
Ying Wanga7188322010-01-04 18:45:10 -0800185
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200186 /**
Ying Wanga7188322010-01-04 18:45:10 -0800187 * Returns true if Monkey is running.
188 */
189 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700190 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800191 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700192
193 /**
194 * Returns whether the device is voice-capable (meaning, it is also a phone).
195 */
196 public static boolean isVoiceCapable(Context context) {
197 TelephonyManager telephony =
198 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
199 return telephony != null && telephony.isVoiceCapable();
200 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800201
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700202 public static boolean isWifiOnly(Context context) {
203 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
204 Context.CONNECTIVITY_SERVICE);
205 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800206 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800207
208 /**
209 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
210 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900211 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800212 */
213 public static String getWifiIpAddresses(Context context) {
214 ConnectivityManager cm = (ConnectivityManager)
215 context.getSystemService(Context.CONNECTIVITY_SERVICE);
216 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700217 return formatIpAddresses(prop);
218 }
219
220 /**
221 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
222 * addresses.
223 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900224 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700225 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900226 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700227 LinkProperties prop = cm.getActiveLinkProperties();
228 return formatIpAddresses(prop);
229 }
230
231 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800232 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900233 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800234 // If there are no entries, return null
235 if (!iter.hasNext()) return null;
236 // Concatenate all available addresses, comma separated
237 String addresses = "";
238 while (iter.hasNext()) {
239 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900240 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800241 }
242 return addresses;
243 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900244
245 public static Locale createLocaleFromString(String localeStr) {
246 // TODO: is there a better way to actually construct a locale that will match?
247 // The main problem is, on top of Java specs, locale.toString() and
248 // new Locale(locale.toString()).toString() do not return equal() strings in
249 // many cases, because the constructor takes the only string as the language
250 // code. So : new Locale("en", "US").toString() => "en_US"
251 // And : new Locale("en_US").toString() => "en_us"
252 if (null == localeStr)
253 return Locale.getDefault();
254 String[] brokenDownLocale = localeStr.split("_", 3);
255 // split may not return a 0-length array.
256 if (1 == brokenDownLocale.length) {
257 return new Locale(brokenDownLocale[0]);
258 } else if (2 == brokenDownLocale.length) {
259 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
260 } else {
261 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
262 }
263 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700264
Elliott Hughes7253df32014-09-02 17:10:14 -0700265 /** Formats the ratio of amount/total as a percentage. */
266 public static String formatPercentage(long amount, long total) {
267 return formatPercentage(((double) amount) / total);
268 }
269
270 /** Formats an integer from 0..100 as a percentage. */
271 public static String formatPercentage(int percentage) {
272 return formatPercentage(((double) percentage) / 100.0);
273 }
274
275 /** Formats a double from 0.0..1.0 as a percentage. */
276 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700277 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700278 }
279
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900280 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
281 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
282 }
283
Amith Yamasania4379d62011-07-22 10:34:58 -0700284 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700285 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700286 }
287
288 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900289 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
290 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700291 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700292 }
293
294 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
295 final Intent intent = batteryChangedIntent;
296
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900297 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
298 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
299 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700300 String statusString;
301 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700302 int resId;
303 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
304 resId = R.string.battery_info_status_charging_ac;
305 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
306 resId = R.string.battery_info_status_charging_usb;
307 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
308 resId = R.string.battery_info_status_charging_wireless;
309 } else {
310 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700311 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700312 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700313 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
314 statusString = res.getString(R.string.battery_info_status_discharging);
315 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
316 statusString = res.getString(R.string.battery_info_status_not_charging);
317 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
318 statusString = res.getString(R.string.battery_info_status_full);
319 } else {
320 statusString = res.getString(R.string.battery_info_status_unknown);
321 }
322
323 return statusString;
324 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700325
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800326 public static void forcePrepareCustomPreferencesList(
327 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
328 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
329 list.setClipToPadding(false);
330 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
331 }
332
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700333 /**
334 * Prepare a custom preferences layout, moving padding to {@link ListView}
335 * when outside scrollbars are requested. Usually used to display
336 * {@link ListView} and {@link TabWidget} with correct padding.
337 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700338 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800339 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700340 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700341 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700342 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700343 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700344 final int paddingBottom = res.getDimensionPixelSize(
345 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700346
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700347 if (parent instanceof PreferenceFrameLayout) {
348 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
349
350 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
351 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
352 } else {
353 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
354 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700355 }
356 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700357
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700358 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700359 final Resources res = view.getResources();
360 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700361
362 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
363 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700364 final int paddingBottom = res.getDimensionPixelSize(
365 com.android.internal.R.dimen.preference_fragment_padding_bottom);
366
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700367 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700368 }
369
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700370 /* Used by UserSettings as well. Call this on a non-ui thread. */
371 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
372 Uri contactUri = Profile.CONTENT_URI;
373
374 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
375 context.getContentResolver(),
376 contactUri, true);
377 // If there's no profile photo, assign a default avatar
378 if (avatarDataStream == null) {
379 return false;
380 }
381 int userId = user != null ? user.id : UserHandle.myUserId();
382 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700383 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
384 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700385 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700386 avatarDataStream.close();
387 } catch (IOException ioe) { }
388 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700389 }
390
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700391 public static String getMeProfileName(Context context, boolean full) {
392 if (full) {
393 return getProfileDisplayName(context);
394 } else {
395 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700396 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700397 }
398
399 private static String getShorterNameIfPossible(Context context) {
400 final String given = getLocalProfileGivenName(context);
401 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
402 }
403
404 private static String getLocalProfileGivenName(Context context) {
405 final ContentResolver cr = context.getContentResolver();
406
407 // Find the raw contact ID for the local ME profile raw contact.
408 final long localRowProfileId;
409 final Cursor localRawProfile = cr.query(
410 Profile.CONTENT_RAW_CONTACTS_URI,
411 new String[] {RawContacts._ID},
412 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
413 RawContacts.ACCOUNT_NAME + " IS NULL",
414 null, null);
415 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700416
417 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700418 if (!localRawProfile.moveToFirst()) {
419 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700420 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700421 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700422 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700423 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700424 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700425
426 // Find the structured name for the raw contact.
427 final Cursor structuredName = cr.query(
428 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
429 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
430 CommonDataKinds.StructuredName.FAMILY_NAME},
431 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
432 null, null);
433 if (structuredName == null) return null;
434
435 try {
436 if (!structuredName.moveToFirst()) {
437 return null;
438 }
439 String partialName = structuredName.getString(0);
440 if (TextUtils.isEmpty(partialName)) {
441 partialName = structuredName.getString(1);
442 }
443 return partialName;
444 } finally {
445 structuredName.close();
446 }
447 }
448
449 private static final String getProfileDisplayName(Context context) {
450 final ContentResolver cr = context.getContentResolver();
451 final Cursor profile = cr.query(Profile.CONTENT_URI,
452 new String[] {Profile.DISPLAY_NAME}, null, null, null);
453 if (profile == null) return null;
454
455 try {
456 if (!profile.moveToFirst()) {
457 return null;
458 }
459 return profile.getString(0);
460 } finally {
461 profile.close();
462 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700463 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700464
465 /** Not global warming, it's global change warning. */
466 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
467 final Runnable positiveAction) {
468 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
469 builder.setTitle(titleResId);
470 builder.setMessage(R.string.global_change_warning);
471 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
472 @Override
473 public void onClick(DialogInterface dialog, int which) {
474 positiveAction.run();
475 }
476 });
477 builder.setNegativeButton(android.R.string.cancel, null);
478
479 return builder.create();
480 }
481
482 public static boolean hasMultipleUsers(Context context) {
483 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
484 .getUsers().size() > 1;
485 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700486
487 /**
488 * Start a new instance of the activity, showing only the given fragment.
489 * When launched in this mode, the given preference fragment will be instantiated and fill the
490 * entire activity.
491 *
492 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000493 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700494 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700495 * @param resultTo Option fragment that should receive the result of the activity launch.
496 * @param resultRequestCode If resultTo is non-null, this is the request code in which
497 * to report the result.
498 * @param titleResId resource id for the String to display for the title of this set
499 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700500 * @param title String to display for the title of this set of preferences.
501 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000502 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100503 Fragment resultTo, int resultRequestCode, int titleResId,
504 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700505 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100506 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
507 }
508
509 /**
510 * Start a new instance of the activity, showing only the given fragment.
511 * When launched in this mode, the given preference fragment will be instantiated and fill the
512 * entire activity.
513 *
514 * @param context The context.
515 * @param fragmentName The name of the fragment to display.
516 * @param args Optional arguments to supply to the fragment.
517 * @param resultTo Option fragment that should receive the result of the activity launch.
518 * @param resultRequestCode If resultTo is non-null, this is the request code in which
519 * to report the result.
520 * @param titleResPackageName Optional package name for the resource id of the title.
521 * @param titleResId resource id for the String to display for the title of this set
522 * of preferences.
523 * @param title String to display for the title of this set of preferences.
524 */
525 public static void startWithFragment(Context context, String fragmentName, Bundle args,
526 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
527 CharSequence title) {
528 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
529 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700530 }
531
532 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100533 Fragment resultTo, int resultRequestCode, int titleResId,
534 CharSequence title, boolean isShortcut) {
535 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
536 null /* titleResPackageName */, titleResId, title, isShortcut);
537 if (resultTo == null) {
538 context.startActivity(intent);
539 } else {
540 resultTo.startActivityForResult(intent, resultRequestCode);
541 }
542 }
543
544 public static void startWithFragment(Context context, String fragmentName, Bundle args,
545 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
546 CharSequence title, boolean isShortcut) {
547 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
548 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700549 if (resultTo == null) {
550 context.startActivity(intent);
551 } else {
552 resultTo.startActivityForResult(intent, resultRequestCode);
553 }
554 }
555
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100556 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100557 int titleResId, CharSequence title, boolean isShortcut,
558 UserHandle userHandle) {
559 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
560 null /* titleResPackageName */, titleResId, title, isShortcut);
561 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
562 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
563 context.startActivityAsUser(intent, userHandle);
564 }
565
566 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
567 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
568 UserHandle userHandle) {
569 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
570 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100571 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
572 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100573 context.startActivityAsUser(intent, userHandle);
574 }
575
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700576 /**
577 * Build an Intent to launch a new activity showing the selected fragment.
578 * The implementation constructs an Intent that re-launches the current activity with the
579 * appropriate arguments to display the fragment.
580 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700581 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700582 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000583 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700584 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100585 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700586 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700587 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700588 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700589 * @return Returns an Intent that can be launched to display the given
590 * fragment.
591 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000592 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100593 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
594 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700595 Intent intent = new Intent(Intent.ACTION_MAIN);
596 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000597 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700598 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100599 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
600 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700601 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700602 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700603 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700604 return intent;
605 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100606
607 /**
608 * Returns the managed profile of the current user or null if none found.
609 */
610 public static UserHandle getManagedProfile(UserManager userManager) {
611 List<UserHandle> userProfiles = userManager.getUserProfiles();
612 final int count = userProfiles.size();
613 for (int i = 0; i < count; i++) {
614 final UserHandle profile = userProfiles.get(i);
615 if (profile.getIdentifier() == userManager.getUserHandle()) {
616 continue;
617 }
618 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
619 if (userInfo.isManagedProfile()) {
620 return profile;
621 }
622 }
623 return null;
624 }
625
626 /**
627 * Returns true if the current profile is a managed one.
628 */
629 public static boolean isManagedProfile(UserManager userManager) {
630 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
631 return currentUser.isManagedProfile();
632 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100633
634 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100635 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100636 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100637 * The target user can be either the current user, the user that launched this activity or
638 * the user contained as an extra in the arguments or intent extras.
639 *
640 * Note: This is secure in the sense that it only returns a target user different to the current
641 * one if the app launching this activity is the Settings app itself, running in the same user
642 * 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 +0100643 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100644 public static UserHandle getSecureTargetUser(IBinder activityToken,
645 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
646 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
647 IActivityManager am = ActivityManagerNative.getDefault();
648 try {
649 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
650 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
651
652 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
653 am.getLaunchedFromUid(activityToken)));
654 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
655 // Check it's secure
656 if (isProfileOf(um, launchedFromUser)) {
657 return launchedFromUser;
658 }
659 }
660 UserHandle extrasUser = intentExtras != null
661 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
662 if (extrasUser != null && !extrasUser.equals(currentUser)) {
663 // Check it's secure
664 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
665 return extrasUser;
666 }
667 }
668 UserHandle argumentsUser = arguments != null
669 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
670 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
671 // Check it's secure
672 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
673 return argumentsUser;
674 }
675 }
676 } catch (RemoteException e) {
677 // Should not happen
678 Log.v(TAG, "Could not talk to activity manager.", e);
679 }
680 return currentUser;
681 }
682
683 /**
684 * Returns the target user for a Settings activity.
685 *
686 * The target user can be either the current user, the user that launched this activity or
687 * the user contained as an extra in the arguments or intent extras.
688 *
689 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
690 * possible.
691 *
692 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
693 */
694 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
695 @Nullable Bundle intentExtras) {
696 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
697 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100698 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100699 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
700 am.getLaunchedFromUid(activityToken)));
701 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
702 return launchedFromUser;
703 }
704 UserHandle extrasUser = intentExtras != null
705 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
706 if (extrasUser != null && !extrasUser.equals(currentUser)) {
707 return extrasUser;
708 }
709 UserHandle argumentsUser = arguments != null
710 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
711 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
712 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100713 }
714 } catch (RemoteException e) {
715 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100716 Log.v(TAG, "Could not talk to activity manager.", e);
717 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100718 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100719 return currentUser;
720 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100721
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100722 /**
723 * Returns true if the user provided is in the same profiles group as the current user.
724 */
725 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
726 if (um == null || otherUser == null) return false;
727 return (UserHandle.myUserId() == otherUser.getIdentifier())
728 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100729 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530730
Andres Moralesce249fe2014-07-07 16:58:16 -0700731
732 /**
733 * Returns whether or not this device is able to be OEM unlocked.
734 */
735 static boolean isOemUnlockEnabled(Context context) {
736 PersistentDataBlockManager manager =(PersistentDataBlockManager)
737 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
738 return manager.getOemUnlockEnabled();
739 }
740
741 /**
742 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
743 * devices allow users to flash other OSes to them.
744 */
745 static void setOemUnlockEnabled(Context context, boolean enabled) {
746 PersistentDataBlockManager manager =(PersistentDataBlockManager)
747 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
748 manager.setOemUnlockEnabled(enabled);
749 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100750
751 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700752 * Return whether or not the user should have a SIM Cards option in Settings.
753 * TODO: Change back to returning true if count is greater than one after testing.
754 * TODO: See bug 16533525.
755 */
756 public static boolean showSimCardTile(Context context) {
757 final TelephonyManager tm =
758 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
759
PauloftheWestdbd03822014-12-04 11:56:35 -0800760 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700761 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200762
763 /**
764 * Determine whether a package is a "system package", in which case certain things (like
765 * disabling notifications or disabling the package altogether) should be disallowed.
766 */
767 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
768 if (sSystemSignature == null) {
769 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
770 }
771 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
772 }
773
774 private static Signature[] sSystemSignature;
775
776 private static Signature getFirstSignature(PackageInfo pkg) {
777 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
778 return pkg.signatures[0];
779 }
780 return null;
781 }
782
783 private static Signature getSystemSignature(PackageManager pm) {
784 try {
785 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
786 return getFirstSignature(sys);
787 } catch (NameNotFoundException e) {
788 }
789 return null;
790 }
791
Elliott Hughes7253df32014-09-02 17:10:14 -0700792 /**
793 * Returns elapsed time for the given millis, in the following format:
794 * 2d 5h 40m 29s
795 * @param context the application context
796 * @param millis the elapsed time in milli seconds
797 * @param withSeconds include seconds?
798 * @return the formatted elapsed time
799 */
800 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
801 StringBuilder sb = new StringBuilder();
802 int seconds = (int) Math.floor(millis / 1000);
803 if (!withSeconds) {
804 // Round up.
805 seconds += 30;
806 }
807
808 int days = 0, hours = 0, minutes = 0;
809 if (seconds >= SECONDS_PER_DAY) {
810 days = seconds / SECONDS_PER_DAY;
811 seconds -= days * SECONDS_PER_DAY;
812 }
813 if (seconds >= SECONDS_PER_HOUR) {
814 hours = seconds / SECONDS_PER_HOUR;
815 seconds -= hours * SECONDS_PER_HOUR;
816 }
817 if (seconds >= SECONDS_PER_MINUTE) {
818 minutes = seconds / SECONDS_PER_MINUTE;
819 seconds -= minutes * SECONDS_PER_MINUTE;
820 }
821 if (withSeconds) {
822 if (days > 0) {
823 sb.append(context.getString(R.string.battery_history_days,
824 days, hours, minutes, seconds));
825 } else if (hours > 0) {
826 sb.append(context.getString(R.string.battery_history_hours,
827 hours, minutes, seconds));
828 } else if (minutes > 0) {
829 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
830 } else {
831 sb.append(context.getString(R.string.battery_history_seconds, seconds));
832 }
833 } else {
834 if (days > 0) {
835 sb.append(context.getString(R.string.battery_history_days_no_seconds,
836 days, hours, minutes));
837 } else if (hours > 0) {
838 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
839 hours, minutes));
840 } else {
841 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
842 }
843 }
844 return sb.toString();
845 }
PauloftheWest0a0daca2014-11-06 15:02:58 -0800846
847 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800848 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
849 * @param userManager Instance of UserManager
850 * @param checkUser The user to check the existence of.
851 * @return UserInfo of the user or null for non-existent user.
852 */
853 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
854 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
855 final int checkUserId = checkUser.getIdentifier();
856 for (UserInfo user : users) {
857 if (user.id == checkUserId) {
858 return user;
859 }
860 }
861 return null;
862 }
863
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000864 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
865 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
866 com.android.internal.R.styleable.Preference,
867 com.android.internal.R.attr.preferenceCategoryStyle, 0);
868 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
869 0);
870 a.recycle();
871 return inflater.inflate(resId, parent, false);
872 }
873
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -0800874 /**
875 * Return if we are running low on storage space or not.
876 *
877 * @param context The context
878 * @return true if we are running low on storage space
879 */
880 public static boolean isLowStorage(Context context) {
881 final StorageManager sm = StorageManager.from(context);
882 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
883 }
884
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000885 /**
886 * Returns a default user icon (as a {@link Bitmap}) for the given user.
887 *
888 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
889 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
890 */
891 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
892 Bitmap bitmap = null;
893 // Try finding the corresponding bitmap in the dark bitmap cache
894 bitmap = sDarkDefaultUserBitmapCache.get(userId);
895 if (bitmap == null) {
896 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
897 // Save it to cache
898 sDarkDefaultUserBitmapCache.put(userId, bitmap);
899 }
900 return bitmap;
901 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800902
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800903 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
904 // Get list of preferred activities
905 List<ComponentName> prefActList = new ArrayList<>();
906 // Intent list cannot be null. so pass empty list
907 List<IntentFilter> intentList = new ArrayList<>();
908 pm.getPreferredActivities(intentList, prefActList, packageName);
909 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
910 return prefActList.size() > 0;
911 }
912
Christopher Tatea08a2252015-07-01 16:52:43 -0700913 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
914 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
915 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
916
917 ArraySet<String> result = new ArraySet<>();
918 if (iviList.size() > 0) {
919 for (IntentFilterVerificationInfo ivi : iviList) {
920 for (String host : ivi.getDomains()) {
921 result.add(host);
922 }
923 }
924 }
925 if (filters != null && filters.size() > 0) {
926 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700927 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
928 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
929 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700930 result.addAll(filter.getHostsList());
931 }
932 }
933 }
934 return result;
935 }
936
Jason Monkb5aa73f2015-03-31 12:59:33 -0400937 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
938 boolean animate) {
939 setViewShown(loading, !done, animate);
940 setViewShown(doneLoading, done, animate);
941 }
942
943 private static void setViewShown(final View view, boolean shown, boolean animate) {
944 if (animate) {
945 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
946 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
947 if (shown) {
948 view.setVisibility(View.VISIBLE);
949 } else {
950 animation.setAnimationListener(new AnimationListener() {
951 @Override
952 public void onAnimationStart(Animation animation) {
953 }
954
955 @Override
956 public void onAnimationRepeat(Animation animation) {
957 }
958
959 @Override
960 public void onAnimationEnd(Animation animation) {
961 view.setVisibility(View.INVISIBLE);
962 }
963 });
964 }
965 view.startAnimation(animation);
966 } else {
967 view.clearAnimation();
968 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
969 }
970 }
Sudheer Shankabc956302015-04-09 12:19:53 +0100971
972 /**
973 * Returns the application info of the currently installed MDM package.
974 */
975 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
976 DevicePolicyManager dpm =
977 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
978 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
979 if (mdmPackage == null) {
980 return null;
981 }
982 String mdmPackageName = mdmPackage.getPackageName();
983 try {
984 IPackageManager ipm = AppGlobals.getPackageManager();
985 ApplicationInfo mdmApplicationInfo =
986 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
987 return mdmApplicationInfo;
988 } catch (RemoteException e) {
989 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
990 + ", userId " + profileId, e);
991 return null;
992 }
993 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400994
995 public static boolean isBandwidthControlEnabled() {
996 final INetworkManagementService netManager = INetworkManagementService.Stub
997 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
998 try {
999 return netManager.isBandwidthControlEnabled();
1000 } catch (RemoteException e) {
1001 return false;
1002 }
1003 }
Julia Reynoldsce25af42015-07-08 16:56:31 -04001004
1005 /**
1006 * Returns an accessible SpannableString.
1007 * @param displayText the text to display
1008 * @param accessibileText the text text-to-speech engines should read
1009 */
1010 public static SpannableString createAccessibleSequence(CharSequence displayText,
1011 String accessibileText) {
1012 SpannableString str = new SpannableString(displayText);
1013 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
1014 displayText.length(),
1015 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1016 return str;
1017 }
Andres Morales7bdffd82015-08-04 16:55:00 -07001018
Clara Bayarrife432e82015-10-12 12:07:02 +01001019 /**
1020 * Returns the user id present in the bundle with {@link ChooseLockGeneric#KEY_USER_ID} if it
1021 * belongs to the current user.
1022 *
1023 * @throws SecurityException if the given userId does not belong to the current user group.
1024 */
1025 public static int getSameOwnerUserId(Context context, Bundle bundle) {
1026 if (bundle == null) {
1027 return getEffectiveUserId(context);
1028 }
1029 int userId = bundle.getInt(ChooseLockGeneric.KEY_USER_ID, UserHandle.myUserId());
1030 return getSameOwnerUserId(context, userId);
1031 }
1032
1033 /**
1034 * Returns the given user id if it belongs to the current user.
1035 *
1036 * @throws SecurityException if the given userId does not belong to the current user group.
1037 */
1038 public static int getSameOwnerUserId(Context context, int userId) {
1039 UserManager um = UserManager.get(context);
1040 if (um != null) {
1041 if (um.getUserProfiles().contains(new UserHandle(userId))) {
1042 return userId;
1043 } else {
1044 throw new SecurityException("Given user id " + userId + " does not belong to user "
1045 + UserHandle.myUserId());
1046 }
1047 }
1048 return getEffectiveUserId(context);
1049 }
1050
Andres Morales7bdffd82015-08-04 16:55:00 -07001051 public static int getEffectiveUserId(Context context) {
1052 UserManager um = UserManager.get(context);
1053 if (um != null) {
1054 return um.getCredentialOwnerProfile(UserHandle.myUserId());
1055 } else {
1056 Log.e(TAG, "Unable to acquire UserManager");
1057 return UserHandle.myUserId();
1058 }
1059 }
Jason Monkdb4ed192015-12-11 16:48:31 -05001060
1061 public static int resolveResource(Context context, int attr) {
1062 TypedValue value = new TypedValue();
1063 context.getTheme().resolveAttribute(attr, value, true);
1064 return value.resourceId;
1065 }
Andres Morales7bdffd82015-08-04 16:55:00 -07001066}
1067