blob: 96d0a37a60223945078aa3b6011b75a10bf30ee3 [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;
Jason Monkb37e2882016-01-11 14:27:20 -050070import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040071import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070072import android.util.ArraySet;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010073import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000074import android.util.SparseArray;
Jason Monkdb4ed192015-12-11 16:48:31 -050075import android.util.TypedValue;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000076import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070077import android.view.View;
78import android.view.ViewGroup;
Jason Monkb5aa73f2015-03-31 12:59:33 -040079import android.view.animation.Animation;
80import android.view.animation.Animation.AnimationListener;
81import android.view.animation.AnimationUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070082import android.widget.ListView;
83import android.widget.TabWidget;
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010084import com.android.internal.util.UserIcons;
Jason Monkb37e2882016-01-11 14:27:20 -050085import com.android.settings.datausage.DataUsageList;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070086
Amith Yamasaniae47ef42012-09-16 17:53:35 -070087import java.io.IOException;
88import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080089import java.net.InetAddress;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010090import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080091import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070092import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090093import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080094
Tony Mantler67cd6ab2015-06-08 14:41:02 -070095import static android.content.Intent.EXTRA_USER;
Jason Monkb37e2882016-01-11 14:27:20 -050096import static android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
97import static android.text.format.DateUtils.FORMAT_SHOW_DATE;
Tony Mantler67cd6ab2015-06-08 14:41:02 -070098
Jason Monk27985e12016-01-08 14:13:05 -050099public final class Utils extends com.android.settingslib.Utils {
100
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100101 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100102
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800103 /**
104 * Set the preference's title to the matching activity's label.
105 */
106 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
107
108 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900109 * The opacity level of a disabled icon.
110 */
111 public static final float DISABLED_ALPHA = 0.4f;
112
113 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700114 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
115 * 1 is most bad (red), the last value is least bad (green).
116 */
117 public static final int[] BADNESS_COLORS = new int[] {
118 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
119 0xfffabf2c, 0xff679e37, 0xff0a7f42
120 };
121
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100122 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
123
Elliott Hughes7253df32014-09-02 17:10:14 -0700124 private static final int SECONDS_PER_MINUTE = 60;
125 private static final int SECONDS_PER_HOUR = 60 * 60;
126 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
127
Jason Monkbeb171d2015-05-21 15:24:37 -0400128 public static final String OS_PKG = "os";
129
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000130 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
131
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200132 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800133 * Finds a matching activity for a preference's intent. If a matching
134 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800135 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800136 * @param context The context.
137 * @param parentPreferenceGroup The preference group that contains the
138 * preference whose intent is being resolved.
139 * @param preferenceKey The key of the preference whose intent is being
140 * resolved.
141 * @param flags 0 or one or more of
142 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
143 * .
144 * @return Whether an activity was found. If false, the preference was
145 * removed.
146 */
147 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
148 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800149
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800150 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
151 if (preference == null) {
152 return false;
153 }
Ying Wanga7188322010-01-04 18:45:10 -0800154
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800155 Intent intent = preference.getIntent();
156 if (intent != null) {
157 // Find the activity that is in the system image
158 PackageManager pm = context.getPackageManager();
159 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
160 int listSize = list.size();
161 for (int i = 0; i < listSize; i++) {
162 ResolveInfo resolveInfo = list.get(i);
163 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
164 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800165
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800166 // Replace the intent with this specific activity
167 preference.setIntent(new Intent().setClassName(
168 resolveInfo.activityInfo.packageName,
169 resolveInfo.activityInfo.name));
170
171 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
172 // Set the preference title to the activity's label
173 preference.setTitle(resolveInfo.loadLabel(pm));
174 }
Ying Wanga7188322010-01-04 18:45:10 -0800175
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800176 return true;
177 }
178 }
179 }
180
181 // Did not find a matching activity, so remove the preference
182 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800183
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900184 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800185 }
Ying Wanga7188322010-01-04 18:45:10 -0800186
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200187 /**
Ying Wanga7188322010-01-04 18:45:10 -0800188 * Returns true if Monkey is running.
189 */
190 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700191 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800192 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700193
194 /**
195 * Returns whether the device is voice-capable (meaning, it is also a phone).
196 */
197 public static boolean isVoiceCapable(Context context) {
198 TelephonyManager telephony =
199 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
200 return telephony != null && telephony.isVoiceCapable();
201 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800202
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700203 public static boolean isWifiOnly(Context context) {
204 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
205 Context.CONNECTIVITY_SERVICE);
206 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800207 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800208
209 /**
210 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
211 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900212 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800213 */
214 public static String getWifiIpAddresses(Context context) {
215 ConnectivityManager cm = (ConnectivityManager)
216 context.getSystemService(Context.CONNECTIVITY_SERVICE);
217 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700218 return formatIpAddresses(prop);
219 }
220
221 /**
222 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
223 * addresses.
224 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900225 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700226 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900227 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700228 LinkProperties prop = cm.getActiveLinkProperties();
229 return formatIpAddresses(prop);
230 }
231
232 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800233 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900234 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800235 // If there are no entries, return null
236 if (!iter.hasNext()) return null;
237 // Concatenate all available addresses, comma separated
238 String addresses = "";
239 while (iter.hasNext()) {
240 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900241 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800242 }
243 return addresses;
244 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900245
246 public static Locale createLocaleFromString(String localeStr) {
247 // TODO: is there a better way to actually construct a locale that will match?
248 // The main problem is, on top of Java specs, locale.toString() and
249 // new Locale(locale.toString()).toString() do not return equal() strings in
250 // many cases, because the constructor takes the only string as the language
251 // code. So : new Locale("en", "US").toString() => "en_US"
252 // And : new Locale("en_US").toString() => "en_us"
253 if (null == localeStr)
254 return Locale.getDefault();
255 String[] brokenDownLocale = localeStr.split("_", 3);
256 // split may not return a 0-length array.
257 if (1 == brokenDownLocale.length) {
258 return new Locale(brokenDownLocale[0]);
259 } else if (2 == brokenDownLocale.length) {
260 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
261 } else {
262 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
263 }
264 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700265
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900266 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
267 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
268 }
269
Amith Yamasania4379d62011-07-22 10:34:58 -0700270 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700271 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700272 }
273
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800274 public static void forcePrepareCustomPreferencesList(
275 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
276 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
277 list.setClipToPadding(false);
278 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
279 }
280
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700281 /**
282 * Prepare a custom preferences layout, moving padding to {@link ListView}
283 * when outside scrollbars are requested. Usually used to display
284 * {@link ListView} and {@link TabWidget} with correct padding.
285 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700286 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800287 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700288 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700289 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700290 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700291 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700292 final int paddingBottom = res.getDimensionPixelSize(
293 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700294
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700295 if (parent instanceof PreferenceFrameLayout) {
296 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
297
298 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
299 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
300 } else {
301 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
302 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700303 }
304 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700305
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700306 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700307 final Resources res = view.getResources();
308 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700309
310 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
311 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700312 final int paddingBottom = res.getDimensionPixelSize(
313 com.android.internal.R.dimen.preference_fragment_padding_bottom);
314
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700315 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700316 }
317
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700318 /* Used by UserSettings as well. Call this on a non-ui thread. */
319 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
320 Uri contactUri = Profile.CONTENT_URI;
321
322 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
323 context.getContentResolver(),
324 contactUri, true);
325 // If there's no profile photo, assign a default avatar
326 if (avatarDataStream == null) {
327 return false;
328 }
329 int userId = user != null ? user.id : UserHandle.myUserId();
330 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700331 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
332 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700333 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700334 avatarDataStream.close();
335 } catch (IOException ioe) { }
336 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700337 }
338
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700339 public static String getMeProfileName(Context context, boolean full) {
340 if (full) {
341 return getProfileDisplayName(context);
342 } else {
343 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700344 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700345 }
346
347 private static String getShorterNameIfPossible(Context context) {
348 final String given = getLocalProfileGivenName(context);
349 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
350 }
351
352 private static String getLocalProfileGivenName(Context context) {
353 final ContentResolver cr = context.getContentResolver();
354
355 // Find the raw contact ID for the local ME profile raw contact.
356 final long localRowProfileId;
357 final Cursor localRawProfile = cr.query(
358 Profile.CONTENT_RAW_CONTACTS_URI,
359 new String[] {RawContacts._ID},
360 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
361 RawContacts.ACCOUNT_NAME + " IS NULL",
362 null, null);
363 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700364
365 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700366 if (!localRawProfile.moveToFirst()) {
367 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700368 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700369 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700370 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700371 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700372 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700373
374 // Find the structured name for the raw contact.
375 final Cursor structuredName = cr.query(
376 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
377 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
378 CommonDataKinds.StructuredName.FAMILY_NAME},
379 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
380 null, null);
381 if (structuredName == null) return null;
382
383 try {
384 if (!structuredName.moveToFirst()) {
385 return null;
386 }
387 String partialName = structuredName.getString(0);
388 if (TextUtils.isEmpty(partialName)) {
389 partialName = structuredName.getString(1);
390 }
391 return partialName;
392 } finally {
393 structuredName.close();
394 }
395 }
396
397 private static final String getProfileDisplayName(Context context) {
398 final ContentResolver cr = context.getContentResolver();
399 final Cursor profile = cr.query(Profile.CONTENT_URI,
400 new String[] {Profile.DISPLAY_NAME}, null, null, null);
401 if (profile == null) return null;
402
403 try {
404 if (!profile.moveToFirst()) {
405 return null;
406 }
407 return profile.getString(0);
408 } finally {
409 profile.close();
410 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700411 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700412
413 /** Not global warming, it's global change warning. */
414 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
415 final Runnable positiveAction) {
416 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
417 builder.setTitle(titleResId);
418 builder.setMessage(R.string.global_change_warning);
419 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
420 @Override
421 public void onClick(DialogInterface dialog, int which) {
422 positiveAction.run();
423 }
424 });
425 builder.setNegativeButton(android.R.string.cancel, null);
426
427 return builder.create();
428 }
429
430 public static boolean hasMultipleUsers(Context context) {
431 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
432 .getUsers().size() > 1;
433 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700434
435 /**
436 * Start a new instance of the activity, showing only the given fragment.
437 * When launched in this mode, the given preference fragment will be instantiated and fill the
438 * entire activity.
439 *
440 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000441 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700442 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700443 * @param resultTo Option fragment that should receive the result of the activity launch.
444 * @param resultRequestCode If resultTo is non-null, this is the request code in which
445 * to report the result.
446 * @param titleResId resource id for the String to display for the title of this set
447 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700448 * @param title String to display for the title of this set of preferences.
449 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000450 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100451 Fragment resultTo, int resultRequestCode, int titleResId,
452 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700453 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100454 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
455 }
456
457 /**
458 * Start a new instance of the activity, showing only the given fragment.
459 * When launched in this mode, the given preference fragment will be instantiated and fill the
460 * entire activity.
461 *
462 * @param context The context.
463 * @param fragmentName The name of the fragment to display.
464 * @param args Optional arguments to supply to the fragment.
465 * @param resultTo Option fragment that should receive the result of the activity launch.
466 * @param resultRequestCode If resultTo is non-null, this is the request code in which
467 * to report the result.
468 * @param titleResPackageName Optional package name for the resource id of the title.
469 * @param titleResId resource id for the String to display for the title of this set
470 * of preferences.
471 * @param title String to display for the title of this set of preferences.
472 */
473 public static void startWithFragment(Context context, String fragmentName, Bundle args,
474 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
475 CharSequence title) {
476 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
477 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700478 }
479
480 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100481 Fragment resultTo, int resultRequestCode, int titleResId,
482 CharSequence title, boolean isShortcut) {
483 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
484 null /* titleResPackageName */, titleResId, title, isShortcut);
485 if (resultTo == null) {
486 context.startActivity(intent);
487 } else {
488 resultTo.startActivityForResult(intent, resultRequestCode);
489 }
490 }
491
492 public static void startWithFragment(Context context, String fragmentName, Bundle args,
493 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
494 CharSequence title, boolean isShortcut) {
495 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
496 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700497 if (resultTo == null) {
498 context.startActivity(intent);
499 } else {
500 resultTo.startActivityForResult(intent, resultRequestCode);
501 }
502 }
503
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100504 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100505 int titleResId, CharSequence title, boolean isShortcut,
506 UserHandle userHandle) {
507 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
508 null /* titleResPackageName */, titleResId, title, isShortcut);
509 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
510 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
511 context.startActivityAsUser(intent, userHandle);
512 }
513
514 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
515 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
516 UserHandle userHandle) {
517 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
518 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100519 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
520 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100521 context.startActivityAsUser(intent, userHandle);
522 }
523
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700524 /**
525 * Build an Intent to launch a new activity showing the selected fragment.
526 * The implementation constructs an Intent that re-launches the current activity with the
527 * appropriate arguments to display the fragment.
528 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700529 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700530 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000531 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700532 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100533 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700534 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700535 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700536 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700537 * @return Returns an Intent that can be launched to display the given
538 * fragment.
539 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000540 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100541 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
542 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700543 Intent intent = new Intent(Intent.ACTION_MAIN);
544 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000545 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700546 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100547 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
548 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700549 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700550 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700551 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700552 return intent;
553 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100554
555 /**
556 * Returns the managed profile of the current user or null if none found.
557 */
558 public static UserHandle getManagedProfile(UserManager userManager) {
559 List<UserHandle> userProfiles = userManager.getUserProfiles();
560 final int count = userProfiles.size();
561 for (int i = 0; i < count; i++) {
562 final UserHandle profile = userProfiles.get(i);
563 if (profile.getIdentifier() == userManager.getUserHandle()) {
564 continue;
565 }
566 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
567 if (userInfo.isManagedProfile()) {
568 return profile;
569 }
570 }
571 return null;
572 }
573
574 /**
575 * Returns true if the current profile is a managed one.
576 */
577 public static boolean isManagedProfile(UserManager userManager) {
578 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
579 return currentUser.isManagedProfile();
580 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100581
582 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100583 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100584 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100585 * The target user can be either the current user, the user that launched this activity or
586 * the user contained as an extra in the arguments or intent extras.
587 *
588 * Note: This is secure in the sense that it only returns a target user different to the current
589 * one if the app launching this activity is the Settings app itself, running in the same user
590 * 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 +0100591 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100592 public static UserHandle getSecureTargetUser(IBinder activityToken,
593 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
594 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
595 IActivityManager am = ActivityManagerNative.getDefault();
596 try {
597 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
598 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
599
600 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
601 am.getLaunchedFromUid(activityToken)));
602 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
603 // Check it's secure
604 if (isProfileOf(um, launchedFromUser)) {
605 return launchedFromUser;
606 }
607 }
608 UserHandle extrasUser = intentExtras != null
609 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
610 if (extrasUser != null && !extrasUser.equals(currentUser)) {
611 // Check it's secure
612 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
613 return extrasUser;
614 }
615 }
616 UserHandle argumentsUser = arguments != null
617 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
618 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
619 // Check it's secure
620 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
621 return argumentsUser;
622 }
623 }
624 } catch (RemoteException e) {
625 // Should not happen
626 Log.v(TAG, "Could not talk to activity manager.", e);
627 }
628 return currentUser;
629 }
630
631 /**
632 * Returns the target user for a Settings activity.
633 *
634 * The target user can be either the current user, the user that launched this activity or
635 * the user contained as an extra in the arguments or intent extras.
636 *
637 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
638 * possible.
639 *
640 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
641 */
642 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
643 @Nullable Bundle intentExtras) {
644 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
645 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100646 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100647 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
648 am.getLaunchedFromUid(activityToken)));
649 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
650 return launchedFromUser;
651 }
652 UserHandle extrasUser = intentExtras != null
653 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
654 if (extrasUser != null && !extrasUser.equals(currentUser)) {
655 return extrasUser;
656 }
657 UserHandle argumentsUser = arguments != null
658 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
659 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
660 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100661 }
662 } catch (RemoteException e) {
663 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100664 Log.v(TAG, "Could not talk to activity manager.", e);
665 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100666 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100667 return currentUser;
668 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100669
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100670 /**
671 * Returns true if the user provided is in the same profiles group as the current user.
672 */
673 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
674 if (um == null || otherUser == null) return false;
675 return (UserHandle.myUserId() == otherUser.getIdentifier())
676 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100677 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530678
Andres Moralesce249fe2014-07-07 16:58:16 -0700679
680 /**
681 * Returns whether or not this device is able to be OEM unlocked.
682 */
683 static boolean isOemUnlockEnabled(Context context) {
684 PersistentDataBlockManager manager =(PersistentDataBlockManager)
685 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
686 return manager.getOemUnlockEnabled();
687 }
688
689 /**
690 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
691 * devices allow users to flash other OSes to them.
692 */
693 static void setOemUnlockEnabled(Context context, boolean enabled) {
694 PersistentDataBlockManager manager =(PersistentDataBlockManager)
695 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
696 manager.setOemUnlockEnabled(enabled);
697 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100698
699 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700700 * Return whether or not the user should have a SIM Cards option in Settings.
701 * TODO: Change back to returning true if count is greater than one after testing.
702 * TODO: See bug 16533525.
703 */
704 public static boolean showSimCardTile(Context context) {
705 final TelephonyManager tm =
706 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
707
PauloftheWestdbd03822014-12-04 11:56:35 -0800708 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700709 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200710
711 /**
Elliott Hughes7253df32014-09-02 17:10:14 -0700712 * Returns elapsed time for the given millis, in the following format:
713 * 2d 5h 40m 29s
714 * @param context the application context
715 * @param millis the elapsed time in milli seconds
716 * @param withSeconds include seconds?
717 * @return the formatted elapsed time
718 */
719 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
720 StringBuilder sb = new StringBuilder();
721 int seconds = (int) Math.floor(millis / 1000);
722 if (!withSeconds) {
723 // Round up.
724 seconds += 30;
725 }
726
727 int days = 0, hours = 0, minutes = 0;
728 if (seconds >= SECONDS_PER_DAY) {
729 days = seconds / SECONDS_PER_DAY;
730 seconds -= days * SECONDS_PER_DAY;
731 }
732 if (seconds >= SECONDS_PER_HOUR) {
733 hours = seconds / SECONDS_PER_HOUR;
734 seconds -= hours * SECONDS_PER_HOUR;
735 }
736 if (seconds >= SECONDS_PER_MINUTE) {
737 minutes = seconds / SECONDS_PER_MINUTE;
738 seconds -= minutes * SECONDS_PER_MINUTE;
739 }
740 if (withSeconds) {
741 if (days > 0) {
742 sb.append(context.getString(R.string.battery_history_days,
743 days, hours, minutes, seconds));
744 } else if (hours > 0) {
745 sb.append(context.getString(R.string.battery_history_hours,
746 hours, minutes, seconds));
747 } else if (minutes > 0) {
748 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
749 } else {
750 sb.append(context.getString(R.string.battery_history_seconds, seconds));
751 }
752 } else {
753 if (days > 0) {
754 sb.append(context.getString(R.string.battery_history_days_no_seconds,
755 days, hours, minutes));
756 } else if (hours > 0) {
757 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
758 hours, minutes));
759 } else {
760 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
761 }
762 }
763 return sb.toString();
764 }
PauloftheWest0a0daca2014-11-06 15:02:58 -0800765
766 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800767 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
768 * @param userManager Instance of UserManager
769 * @param checkUser The user to check the existence of.
770 * @return UserInfo of the user or null for non-existent user.
771 */
772 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
773 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
774 final int checkUserId = checkUser.getIdentifier();
775 for (UserInfo user : users) {
776 if (user.id == checkUserId) {
777 return user;
778 }
779 }
780 return null;
781 }
782
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000783 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
784 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
785 com.android.internal.R.styleable.Preference,
786 com.android.internal.R.attr.preferenceCategoryStyle, 0);
787 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
788 0);
789 a.recycle();
790 return inflater.inflate(resId, parent, false);
791 }
792
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -0800793 /**
794 * Return if we are running low on storage space or not.
795 *
796 * @param context The context
797 * @return true if we are running low on storage space
798 */
799 public static boolean isLowStorage(Context context) {
800 final StorageManager sm = StorageManager.from(context);
801 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
802 }
803
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000804 /**
805 * Returns a default user icon (as a {@link Bitmap}) for the given user.
806 *
807 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
808 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
809 */
810 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
811 Bitmap bitmap = null;
812 // Try finding the corresponding bitmap in the dark bitmap cache
813 bitmap = sDarkDefaultUserBitmapCache.get(userId);
814 if (bitmap == null) {
815 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
816 // Save it to cache
817 sDarkDefaultUserBitmapCache.put(userId, bitmap);
818 }
819 return bitmap;
820 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800821
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800822 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
823 // Get list of preferred activities
824 List<ComponentName> prefActList = new ArrayList<>();
825 // Intent list cannot be null. so pass empty list
826 List<IntentFilter> intentList = new ArrayList<>();
827 pm.getPreferredActivities(intentList, prefActList, packageName);
828 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
829 return prefActList.size() > 0;
830 }
831
Christopher Tatea08a2252015-07-01 16:52:43 -0700832 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
833 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
834 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
835
836 ArraySet<String> result = new ArraySet<>();
837 if (iviList.size() > 0) {
838 for (IntentFilterVerificationInfo ivi : iviList) {
839 for (String host : ivi.getDomains()) {
840 result.add(host);
841 }
842 }
843 }
844 if (filters != null && filters.size() > 0) {
845 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700846 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
847 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
848 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700849 result.addAll(filter.getHostsList());
850 }
851 }
852 }
853 return result;
854 }
855
Jason Monkb5aa73f2015-03-31 12:59:33 -0400856 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
857 boolean animate) {
858 setViewShown(loading, !done, animate);
859 setViewShown(doneLoading, done, animate);
860 }
861
862 private static void setViewShown(final View view, boolean shown, boolean animate) {
863 if (animate) {
864 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
865 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
866 if (shown) {
867 view.setVisibility(View.VISIBLE);
868 } else {
869 animation.setAnimationListener(new AnimationListener() {
870 @Override
871 public void onAnimationStart(Animation animation) {
872 }
873
874 @Override
875 public void onAnimationRepeat(Animation animation) {
876 }
877
878 @Override
879 public void onAnimationEnd(Animation animation) {
880 view.setVisibility(View.INVISIBLE);
881 }
882 });
883 }
884 view.startAnimation(animation);
885 } else {
886 view.clearAnimation();
887 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
888 }
889 }
Sudheer Shankabc956302015-04-09 12:19:53 +0100890
891 /**
892 * Returns the application info of the currently installed MDM package.
893 */
894 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
895 DevicePolicyManager dpm =
896 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
897 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
898 if (mdmPackage == null) {
899 return null;
900 }
901 String mdmPackageName = mdmPackage.getPackageName();
902 try {
903 IPackageManager ipm = AppGlobals.getPackageManager();
904 ApplicationInfo mdmApplicationInfo =
905 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
906 return mdmApplicationInfo;
907 } catch (RemoteException e) {
908 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
909 + ", userId " + profileId, e);
910 return null;
911 }
912 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400913
914 public static boolean isBandwidthControlEnabled() {
915 final INetworkManagementService netManager = INetworkManagementService.Stub
916 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
917 try {
918 return netManager.isBandwidthControlEnabled();
919 } catch (RemoteException e) {
920 return false;
921 }
922 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400923
924 /**
925 * Returns an accessible SpannableString.
926 * @param displayText the text to display
927 * @param accessibileText the text text-to-speech engines should read
928 */
929 public static SpannableString createAccessibleSequence(CharSequence displayText,
930 String accessibileText) {
931 SpannableString str = new SpannableString(displayText);
932 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
933 displayText.length(),
934 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
935 return str;
936 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700937
Clara Bayarrife432e82015-10-12 12:07:02 +0100938 /**
939 * Returns the user id present in the bundle with {@link ChooseLockGeneric#KEY_USER_ID} if it
940 * belongs to the current user.
941 *
942 * @throws SecurityException if the given userId does not belong to the current user group.
943 */
944 public static int getSameOwnerUserId(Context context, Bundle bundle) {
945 if (bundle == null) {
946 return getEffectiveUserId(context);
947 }
Clara Bayarri6934a042015-10-14 11:07:35 +0100948 int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100949 return getSameOwnerUserId(context, userId);
950 }
951
952 /**
953 * Returns the given user id if it belongs to the current user.
954 *
955 * @throws SecurityException if the given userId does not belong to the current user group.
956 */
957 public static int getSameOwnerUserId(Context context, int userId) {
958 UserManager um = UserManager.get(context);
959 if (um != null) {
960 if (um.getUserProfiles().contains(new UserHandle(userId))) {
961 return userId;
962 } else {
963 throw new SecurityException("Given user id " + userId + " does not belong to user "
964 + UserHandle.myUserId());
965 }
966 }
967 return getEffectiveUserId(context);
968 }
969
Andres Morales7bdffd82015-08-04 16:55:00 -0700970 public static int getEffectiveUserId(Context context) {
971 UserManager um = UserManager.get(context);
972 if (um != null) {
973 return um.getCredentialOwnerProfile(UserHandle.myUserId());
974 } else {
975 Log.e(TAG, "Unable to acquire UserManager");
976 return UserHandle.myUserId();
977 }
978 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500979
980 public static int resolveResource(Context context, int attr) {
981 TypedValue value = new TypedValue();
982 context.getTheme().resolveAttribute(attr, value, true);
983 return value.resourceId;
984 }
Jason Monkb37e2882016-01-11 14:27:20 -0500985
986 private static final StringBuilder sBuilder = new StringBuilder(50);
987 private static final java.util.Formatter sFormatter = new java.util.Formatter(
988 sBuilder, Locale.getDefault());
989
990 public static String formatDateRange(Context context, long start, long end) {
991 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
992
993 synchronized (sBuilder) {
994 sBuilder.setLength(0);
995 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
996 .toString();
997 }
998 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700999}
1000