blob: 4afa1d96fa3bdc378567586d09be7ae7c54c382c [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;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080037import android.content.pm.PackageManager;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070038import android.content.pm.ResolveInfo;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070039import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020040import android.content.res.Resources;
Jason Monkb5aa73f2015-03-31 12:59:33 -040041import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070042import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070043import android.graphics.Bitmap;
44import android.graphics.BitmapFactory;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080045import android.net.ConnectivityManager;
46import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070047import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070048import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020049import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010050import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040051import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010052import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040053import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070054import android.os.UserHandle;
55import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080056import android.os.storage.StorageManager;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070057import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070058import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070059import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070060import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070061import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070062import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070063import android.service.persistentdata.PersistentDataBlockManager;
Jason Monk39b46742015-09-10 15:52:51 -040064import android.support.v7.preference.Preference;
65import android.support.v7.preference.PreferenceGroup;
Amith Yamasani60133dd2010-09-11 14:17:31 -070066import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040067import android.text.Spannable;
68import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020069import android.text.TextUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040070import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070071import android.util.ArraySet;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010072import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000073import android.util.SparseArray;
Jason Monkdb4ed192015-12-11 16:48:31 -050074import android.util.TypedValue;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000075import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070076import android.view.View;
77import android.view.ViewGroup;
Jason Monkb5aa73f2015-03-31 12:59:33 -040078import android.view.animation.Animation;
79import android.view.animation.Animation.AnimationListener;
80import android.view.animation.AnimationUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070081import android.widget.ListView;
82import android.widget.TabWidget;
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010083import com.android.internal.util.UserIcons;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070084
Amith Yamasaniae47ef42012-09-16 17:53:35 -070085import java.io.IOException;
86import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080087import java.net.InetAddress;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010088import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080089import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070090import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090091import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080092
Tony Mantler67cd6ab2015-06-08 14:41:02 -070093import static android.content.Intent.EXTRA_USER;
94
Jason Monk27985e12016-01-08 14:13:05 -050095public final class Utils extends com.android.settingslib.Utils {
96
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010097 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010098
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080099 /**
100 * Set the preference's title to the matching activity's label.
101 */
102 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
103
104 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900105 * The opacity level of a disabled icon.
106 */
107 public static final float DISABLED_ALPHA = 0.4f;
108
109 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700110 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
111 * 1 is most bad (red), the last value is least bad (green).
112 */
113 public static final int[] BADNESS_COLORS = new int[] {
114 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
115 0xfffabf2c, 0xff679e37, 0xff0a7f42
116 };
117
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100118 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
119
Elliott Hughes7253df32014-09-02 17:10:14 -0700120 private static final int SECONDS_PER_MINUTE = 60;
121 private static final int SECONDS_PER_HOUR = 60 * 60;
122 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
123
Jason Monkbeb171d2015-05-21 15:24:37 -0400124 public static final String OS_PKG = "os";
125
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000126 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
127
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200128 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800129 * Finds a matching activity for a preference's intent. If a matching
130 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800131 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800132 * @param context The context.
133 * @param parentPreferenceGroup The preference group that contains the
134 * preference whose intent is being resolved.
135 * @param preferenceKey The key of the preference whose intent is being
136 * resolved.
137 * @param flags 0 or one or more of
138 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
139 * .
140 * @return Whether an activity was found. If false, the preference was
141 * removed.
142 */
143 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
144 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800145
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800146 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
147 if (preference == null) {
148 return false;
149 }
Ying Wanga7188322010-01-04 18:45:10 -0800150
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800151 Intent intent = preference.getIntent();
152 if (intent != null) {
153 // Find the activity that is in the system image
154 PackageManager pm = context.getPackageManager();
155 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
156 int listSize = list.size();
157 for (int i = 0; i < listSize; i++) {
158 ResolveInfo resolveInfo = list.get(i);
159 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
160 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800161
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800162 // Replace the intent with this specific activity
163 preference.setIntent(new Intent().setClassName(
164 resolveInfo.activityInfo.packageName,
165 resolveInfo.activityInfo.name));
166
167 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
168 // Set the preference title to the activity's label
169 preference.setTitle(resolveInfo.loadLabel(pm));
170 }
Ying Wanga7188322010-01-04 18:45:10 -0800171
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800172 return true;
173 }
174 }
175 }
176
177 // Did not find a matching activity, so remove the preference
178 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800179
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900180 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800181 }
Ying Wanga7188322010-01-04 18:45:10 -0800182
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200183 /**
Ying Wanga7188322010-01-04 18:45:10 -0800184 * Returns true if Monkey is running.
185 */
186 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700187 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800188 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700189
190 /**
191 * Returns whether the device is voice-capable (meaning, it is also a phone).
192 */
193 public static boolean isVoiceCapable(Context context) {
194 TelephonyManager telephony =
195 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
196 return telephony != null && telephony.isVoiceCapable();
197 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800198
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700199 public static boolean isWifiOnly(Context context) {
200 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
201 Context.CONNECTIVITY_SERVICE);
202 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800203 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800204
205 /**
206 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
207 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900208 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800209 */
210 public static String getWifiIpAddresses(Context context) {
211 ConnectivityManager cm = (ConnectivityManager)
212 context.getSystemService(Context.CONNECTIVITY_SERVICE);
213 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700214 return formatIpAddresses(prop);
215 }
216
217 /**
218 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
219 * addresses.
220 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900221 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700222 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900223 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700224 LinkProperties prop = cm.getActiveLinkProperties();
225 return formatIpAddresses(prop);
226 }
227
228 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800229 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900230 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800231 // If there are no entries, return null
232 if (!iter.hasNext()) return null;
233 // Concatenate all available addresses, comma separated
234 String addresses = "";
235 while (iter.hasNext()) {
236 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900237 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800238 }
239 return addresses;
240 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900241
242 public static Locale createLocaleFromString(String localeStr) {
243 // TODO: is there a better way to actually construct a locale that will match?
244 // The main problem is, on top of Java specs, locale.toString() and
245 // new Locale(locale.toString()).toString() do not return equal() strings in
246 // many cases, because the constructor takes the only string as the language
247 // code. So : new Locale("en", "US").toString() => "en_US"
248 // And : new Locale("en_US").toString() => "en_us"
249 if (null == localeStr)
250 return Locale.getDefault();
251 String[] brokenDownLocale = localeStr.split("_", 3);
252 // split may not return a 0-length array.
253 if (1 == brokenDownLocale.length) {
254 return new Locale(brokenDownLocale[0]);
255 } else if (2 == brokenDownLocale.length) {
256 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
257 } else {
258 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
259 }
260 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700261
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900262 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
263 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
264 }
265
Amith Yamasania4379d62011-07-22 10:34:58 -0700266 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700267 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700268 }
269
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800270 public static void forcePrepareCustomPreferencesList(
271 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
272 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
273 list.setClipToPadding(false);
274 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
275 }
276
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700277 /**
278 * Prepare a custom preferences layout, moving padding to {@link ListView}
279 * when outside scrollbars are requested. Usually used to display
280 * {@link ListView} and {@link TabWidget} with correct padding.
281 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700282 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800283 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700284 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700285 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700286 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700287 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700288 final int paddingBottom = res.getDimensionPixelSize(
289 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700290
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700291 if (parent instanceof PreferenceFrameLayout) {
292 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
293
294 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
295 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
296 } else {
297 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
298 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700299 }
300 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700301
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700302 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700303 final Resources res = view.getResources();
304 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700305
306 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
307 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700308 final int paddingBottom = res.getDimensionPixelSize(
309 com.android.internal.R.dimen.preference_fragment_padding_bottom);
310
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700311 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700312 }
313
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700314 /* Used by UserSettings as well. Call this on a non-ui thread. */
315 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
316 Uri contactUri = Profile.CONTENT_URI;
317
318 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
319 context.getContentResolver(),
320 contactUri, true);
321 // If there's no profile photo, assign a default avatar
322 if (avatarDataStream == null) {
323 return false;
324 }
325 int userId = user != null ? user.id : UserHandle.myUserId();
326 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700327 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
328 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700329 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700330 avatarDataStream.close();
331 } catch (IOException ioe) { }
332 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700333 }
334
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700335 public static String getMeProfileName(Context context, boolean full) {
336 if (full) {
337 return getProfileDisplayName(context);
338 } else {
339 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700340 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700341 }
342
343 private static String getShorterNameIfPossible(Context context) {
344 final String given = getLocalProfileGivenName(context);
345 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
346 }
347
348 private static String getLocalProfileGivenName(Context context) {
349 final ContentResolver cr = context.getContentResolver();
350
351 // Find the raw contact ID for the local ME profile raw contact.
352 final long localRowProfileId;
353 final Cursor localRawProfile = cr.query(
354 Profile.CONTENT_RAW_CONTACTS_URI,
355 new String[] {RawContacts._ID},
356 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
357 RawContacts.ACCOUNT_NAME + " IS NULL",
358 null, null);
359 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700360
361 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700362 if (!localRawProfile.moveToFirst()) {
363 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700364 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700365 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700366 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700367 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700368 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700369
370 // Find the structured name for the raw contact.
371 final Cursor structuredName = cr.query(
372 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
373 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
374 CommonDataKinds.StructuredName.FAMILY_NAME},
375 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
376 null, null);
377 if (structuredName == null) return null;
378
379 try {
380 if (!structuredName.moveToFirst()) {
381 return null;
382 }
383 String partialName = structuredName.getString(0);
384 if (TextUtils.isEmpty(partialName)) {
385 partialName = structuredName.getString(1);
386 }
387 return partialName;
388 } finally {
389 structuredName.close();
390 }
391 }
392
393 private static final String getProfileDisplayName(Context context) {
394 final ContentResolver cr = context.getContentResolver();
395 final Cursor profile = cr.query(Profile.CONTENT_URI,
396 new String[] {Profile.DISPLAY_NAME}, null, null, null);
397 if (profile == null) return null;
398
399 try {
400 if (!profile.moveToFirst()) {
401 return null;
402 }
403 return profile.getString(0);
404 } finally {
405 profile.close();
406 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700407 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700408
409 /** Not global warming, it's global change warning. */
410 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
411 final Runnable positiveAction) {
412 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
413 builder.setTitle(titleResId);
414 builder.setMessage(R.string.global_change_warning);
415 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
416 @Override
417 public void onClick(DialogInterface dialog, int which) {
418 positiveAction.run();
419 }
420 });
421 builder.setNegativeButton(android.R.string.cancel, null);
422
423 return builder.create();
424 }
425
426 public static boolean hasMultipleUsers(Context context) {
427 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
428 .getUsers().size() > 1;
429 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700430
431 /**
432 * Start a new instance of the activity, showing only the given fragment.
433 * When launched in this mode, the given preference fragment will be instantiated and fill the
434 * entire activity.
435 *
436 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000437 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700438 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700439 * @param resultTo Option fragment that should receive the result of the activity launch.
440 * @param resultRequestCode If resultTo is non-null, this is the request code in which
441 * to report the result.
442 * @param titleResId resource id for the String to display for the title of this set
443 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700444 * @param title String to display for the title of this set of preferences.
445 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000446 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100447 Fragment resultTo, int resultRequestCode, int titleResId,
448 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700449 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100450 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
451 }
452
453 /**
454 * Start a new instance of the activity, showing only the given fragment.
455 * When launched in this mode, the given preference fragment will be instantiated and fill the
456 * entire activity.
457 *
458 * @param context The context.
459 * @param fragmentName The name of the fragment to display.
460 * @param args Optional arguments to supply to the fragment.
461 * @param resultTo Option fragment that should receive the result of the activity launch.
462 * @param resultRequestCode If resultTo is non-null, this is the request code in which
463 * to report the result.
464 * @param titleResPackageName Optional package name for the resource id of the title.
465 * @param titleResId resource id for the String to display for the title of this set
466 * of preferences.
467 * @param title String to display for the title of this set of preferences.
468 */
469 public static void startWithFragment(Context context, String fragmentName, Bundle args,
470 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
471 CharSequence title) {
472 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
473 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700474 }
475
476 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100477 Fragment resultTo, int resultRequestCode, int titleResId,
478 CharSequence title, boolean isShortcut) {
479 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
480 null /* titleResPackageName */, titleResId, title, isShortcut);
481 if (resultTo == null) {
482 context.startActivity(intent);
483 } else {
484 resultTo.startActivityForResult(intent, resultRequestCode);
485 }
486 }
487
488 public static void startWithFragment(Context context, String fragmentName, Bundle args,
489 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
490 CharSequence title, boolean isShortcut) {
491 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
492 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700493 if (resultTo == null) {
494 context.startActivity(intent);
495 } else {
496 resultTo.startActivityForResult(intent, resultRequestCode);
497 }
498 }
499
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100500 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100501 int titleResId, CharSequence title, boolean isShortcut,
502 UserHandle userHandle) {
503 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
504 null /* titleResPackageName */, titleResId, title, isShortcut);
505 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
506 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
507 context.startActivityAsUser(intent, userHandle);
508 }
509
510 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
511 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
512 UserHandle userHandle) {
513 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
514 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100515 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
516 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100517 context.startActivityAsUser(intent, userHandle);
518 }
519
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700520 /**
521 * Build an Intent to launch a new activity showing the selected fragment.
522 * The implementation constructs an Intent that re-launches the current activity with the
523 * appropriate arguments to display the fragment.
524 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700525 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700526 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000527 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700528 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100529 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700530 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700531 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700532 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700533 * @return Returns an Intent that can be launched to display the given
534 * fragment.
535 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000536 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100537 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
538 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700539 Intent intent = new Intent(Intent.ACTION_MAIN);
540 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000541 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700542 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100543 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
544 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700545 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700546 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700547 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700548 return intent;
549 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100550
551 /**
552 * Returns the managed profile of the current user or null if none found.
553 */
554 public static UserHandle getManagedProfile(UserManager userManager) {
555 List<UserHandle> userProfiles = userManager.getUserProfiles();
556 final int count = userProfiles.size();
557 for (int i = 0; i < count; i++) {
558 final UserHandle profile = userProfiles.get(i);
559 if (profile.getIdentifier() == userManager.getUserHandle()) {
560 continue;
561 }
562 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
563 if (userInfo.isManagedProfile()) {
564 return profile;
565 }
566 }
567 return null;
568 }
569
570 /**
571 * Returns true if the current profile is a managed one.
572 */
573 public static boolean isManagedProfile(UserManager userManager) {
574 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
575 return currentUser.isManagedProfile();
576 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100577
578 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100579 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100580 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100581 * The target user can be either the current user, the user that launched this activity or
582 * the user contained as an extra in the arguments or intent extras.
583 *
584 * Note: This is secure in the sense that it only returns a target user different to the current
585 * one if the app launching this activity is the Settings app itself, running in the same user
586 * 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 +0100587 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100588 public static UserHandle getSecureTargetUser(IBinder activityToken,
589 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
590 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
591 IActivityManager am = ActivityManagerNative.getDefault();
592 try {
593 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
594 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
595
596 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
597 am.getLaunchedFromUid(activityToken)));
598 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
599 // Check it's secure
600 if (isProfileOf(um, launchedFromUser)) {
601 return launchedFromUser;
602 }
603 }
604 UserHandle extrasUser = intentExtras != null
605 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
606 if (extrasUser != null && !extrasUser.equals(currentUser)) {
607 // Check it's secure
608 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
609 return extrasUser;
610 }
611 }
612 UserHandle argumentsUser = arguments != null
613 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
614 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
615 // Check it's secure
616 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
617 return argumentsUser;
618 }
619 }
620 } catch (RemoteException e) {
621 // Should not happen
622 Log.v(TAG, "Could not talk to activity manager.", e);
623 }
624 return currentUser;
625 }
626
627 /**
628 * Returns the target user for a Settings activity.
629 *
630 * The target user can be either the current user, the user that launched this activity or
631 * the user contained as an extra in the arguments or intent extras.
632 *
633 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
634 * possible.
635 *
636 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
637 */
638 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
639 @Nullable Bundle intentExtras) {
640 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
641 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100642 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100643 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
644 am.getLaunchedFromUid(activityToken)));
645 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
646 return launchedFromUser;
647 }
648 UserHandle extrasUser = intentExtras != null
649 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
650 if (extrasUser != null && !extrasUser.equals(currentUser)) {
651 return extrasUser;
652 }
653 UserHandle argumentsUser = arguments != null
654 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
655 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
656 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100657 }
658 } catch (RemoteException e) {
659 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100660 Log.v(TAG, "Could not talk to activity manager.", e);
661 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100662 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100663 return currentUser;
664 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100665
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100666 /**
667 * Returns true if the user provided is in the same profiles group as the current user.
668 */
669 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
670 if (um == null || otherUser == null) return false;
671 return (UserHandle.myUserId() == otherUser.getIdentifier())
672 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100673 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530674
Andres Moralesce249fe2014-07-07 16:58:16 -0700675
676 /**
677 * Returns whether or not this device is able to be OEM unlocked.
678 */
679 static boolean isOemUnlockEnabled(Context context) {
680 PersistentDataBlockManager manager =(PersistentDataBlockManager)
681 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
682 return manager.getOemUnlockEnabled();
683 }
684
685 /**
686 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
687 * devices allow users to flash other OSes to them.
688 */
689 static void setOemUnlockEnabled(Context context, boolean enabled) {
690 PersistentDataBlockManager manager =(PersistentDataBlockManager)
691 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
692 manager.setOemUnlockEnabled(enabled);
693 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100694
695 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700696 * Return whether or not the user should have a SIM Cards option in Settings.
697 * TODO: Change back to returning true if count is greater than one after testing.
698 * TODO: See bug 16533525.
699 */
700 public static boolean showSimCardTile(Context context) {
701 final TelephonyManager tm =
702 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
703
PauloftheWestdbd03822014-12-04 11:56:35 -0800704 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700705 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200706
707 /**
Elliott Hughes7253df32014-09-02 17:10:14 -0700708 * Returns elapsed time for the given millis, in the following format:
709 * 2d 5h 40m 29s
710 * @param context the application context
711 * @param millis the elapsed time in milli seconds
712 * @param withSeconds include seconds?
713 * @return the formatted elapsed time
714 */
715 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
716 StringBuilder sb = new StringBuilder();
717 int seconds = (int) Math.floor(millis / 1000);
718 if (!withSeconds) {
719 // Round up.
720 seconds += 30;
721 }
722
723 int days = 0, hours = 0, minutes = 0;
724 if (seconds >= SECONDS_PER_DAY) {
725 days = seconds / SECONDS_PER_DAY;
726 seconds -= days * SECONDS_PER_DAY;
727 }
728 if (seconds >= SECONDS_PER_HOUR) {
729 hours = seconds / SECONDS_PER_HOUR;
730 seconds -= hours * SECONDS_PER_HOUR;
731 }
732 if (seconds >= SECONDS_PER_MINUTE) {
733 minutes = seconds / SECONDS_PER_MINUTE;
734 seconds -= minutes * SECONDS_PER_MINUTE;
735 }
736 if (withSeconds) {
737 if (days > 0) {
738 sb.append(context.getString(R.string.battery_history_days,
739 days, hours, minutes, seconds));
740 } else if (hours > 0) {
741 sb.append(context.getString(R.string.battery_history_hours,
742 hours, minutes, seconds));
743 } else if (minutes > 0) {
744 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
745 } else {
746 sb.append(context.getString(R.string.battery_history_seconds, seconds));
747 }
748 } else {
749 if (days > 0) {
750 sb.append(context.getString(R.string.battery_history_days_no_seconds,
751 days, hours, minutes));
752 } else if (hours > 0) {
753 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
754 hours, minutes));
755 } else {
756 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
757 }
758 }
759 return sb.toString();
760 }
PauloftheWest0a0daca2014-11-06 15:02:58 -0800761
762 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800763 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
764 * @param userManager Instance of UserManager
765 * @param checkUser The user to check the existence of.
766 * @return UserInfo of the user or null for non-existent user.
767 */
768 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
769 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
770 final int checkUserId = checkUser.getIdentifier();
771 for (UserInfo user : users) {
772 if (user.id == checkUserId) {
773 return user;
774 }
775 }
776 return null;
777 }
778
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000779 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
780 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
781 com.android.internal.R.styleable.Preference,
782 com.android.internal.R.attr.preferenceCategoryStyle, 0);
783 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
784 0);
785 a.recycle();
786 return inflater.inflate(resId, parent, false);
787 }
788
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -0800789 /**
790 * Return if we are running low on storage space or not.
791 *
792 * @param context The context
793 * @return true if we are running low on storage space
794 */
795 public static boolean isLowStorage(Context context) {
796 final StorageManager sm = StorageManager.from(context);
797 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
798 }
799
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000800 /**
801 * Returns a default user icon (as a {@link Bitmap}) for the given user.
802 *
803 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
804 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
805 */
806 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
807 Bitmap bitmap = null;
808 // Try finding the corresponding bitmap in the dark bitmap cache
809 bitmap = sDarkDefaultUserBitmapCache.get(userId);
810 if (bitmap == null) {
811 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
812 // Save it to cache
813 sDarkDefaultUserBitmapCache.put(userId, bitmap);
814 }
815 return bitmap;
816 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800817
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800818 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
819 // Get list of preferred activities
820 List<ComponentName> prefActList = new ArrayList<>();
821 // Intent list cannot be null. so pass empty list
822 List<IntentFilter> intentList = new ArrayList<>();
823 pm.getPreferredActivities(intentList, prefActList, packageName);
824 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
825 return prefActList.size() > 0;
826 }
827
Christopher Tatea08a2252015-07-01 16:52:43 -0700828 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
829 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
830 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
831
832 ArraySet<String> result = new ArraySet<>();
833 if (iviList.size() > 0) {
834 for (IntentFilterVerificationInfo ivi : iviList) {
835 for (String host : ivi.getDomains()) {
836 result.add(host);
837 }
838 }
839 }
840 if (filters != null && filters.size() > 0) {
841 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700842 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
843 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
844 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700845 result.addAll(filter.getHostsList());
846 }
847 }
848 }
849 return result;
850 }
851
Jason Monkb5aa73f2015-03-31 12:59:33 -0400852 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
853 boolean animate) {
854 setViewShown(loading, !done, animate);
855 setViewShown(doneLoading, done, animate);
856 }
857
858 private static void setViewShown(final View view, boolean shown, boolean animate) {
859 if (animate) {
860 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
861 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
862 if (shown) {
863 view.setVisibility(View.VISIBLE);
864 } else {
865 animation.setAnimationListener(new AnimationListener() {
866 @Override
867 public void onAnimationStart(Animation animation) {
868 }
869
870 @Override
871 public void onAnimationRepeat(Animation animation) {
872 }
873
874 @Override
875 public void onAnimationEnd(Animation animation) {
876 view.setVisibility(View.INVISIBLE);
877 }
878 });
879 }
880 view.startAnimation(animation);
881 } else {
882 view.clearAnimation();
883 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
884 }
885 }
Sudheer Shankabc956302015-04-09 12:19:53 +0100886
887 /**
888 * Returns the application info of the currently installed MDM package.
889 */
890 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
891 DevicePolicyManager dpm =
892 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
893 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
894 if (mdmPackage == null) {
895 return null;
896 }
897 String mdmPackageName = mdmPackage.getPackageName();
898 try {
899 IPackageManager ipm = AppGlobals.getPackageManager();
900 ApplicationInfo mdmApplicationInfo =
901 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
902 return mdmApplicationInfo;
903 } catch (RemoteException e) {
904 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
905 + ", userId " + profileId, e);
906 return null;
907 }
908 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400909
910 public static boolean isBandwidthControlEnabled() {
911 final INetworkManagementService netManager = INetworkManagementService.Stub
912 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
913 try {
914 return netManager.isBandwidthControlEnabled();
915 } catch (RemoteException e) {
916 return false;
917 }
918 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400919
920 /**
921 * Returns an accessible SpannableString.
922 * @param displayText the text to display
923 * @param accessibileText the text text-to-speech engines should read
924 */
925 public static SpannableString createAccessibleSequence(CharSequence displayText,
926 String accessibileText) {
927 SpannableString str = new SpannableString(displayText);
928 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
929 displayText.length(),
930 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
931 return str;
932 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700933
Clara Bayarrife432e82015-10-12 12:07:02 +0100934 /**
935 * Returns the user id present in the bundle with {@link ChooseLockGeneric#KEY_USER_ID} if it
936 * belongs to the current user.
937 *
938 * @throws SecurityException if the given userId does not belong to the current user group.
939 */
940 public static int getSameOwnerUserId(Context context, Bundle bundle) {
941 if (bundle == null) {
942 return getEffectiveUserId(context);
943 }
Clara Bayarri6934a042015-10-14 11:07:35 +0100944 int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100945 return getSameOwnerUserId(context, userId);
946 }
947
948 /**
949 * Returns the given user id if it belongs to the current user.
950 *
951 * @throws SecurityException if the given userId does not belong to the current user group.
952 */
953 public static int getSameOwnerUserId(Context context, int userId) {
954 UserManager um = UserManager.get(context);
955 if (um != null) {
956 if (um.getUserProfiles().contains(new UserHandle(userId))) {
957 return userId;
958 } else {
959 throw new SecurityException("Given user id " + userId + " does not belong to user "
960 + UserHandle.myUserId());
961 }
962 }
963 return getEffectiveUserId(context);
964 }
965
Andres Morales7bdffd82015-08-04 16:55:00 -0700966 public static int getEffectiveUserId(Context context) {
967 UserManager um = UserManager.get(context);
968 if (um != null) {
969 return um.getCredentialOwnerProfile(UserHandle.myUserId());
970 } else {
971 Log.e(TAG, "Unable to acquire UserManager");
972 return UserHandle.myUserId();
973 }
974 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500975
976 public static int resolveResource(Context context, int attr) {
977 TypedValue value = new TypedValue();
978 context.getTheme().resolveAttribute(attr, value, true);
979 return value.resourceId;
980 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700981}
982