blob: 2a5582971c12fdadd4b1af68fd5c985a6b56a6d6 [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
Daniel Nishi422e7c32017-02-09 16:07:22 -080019import static android.content.Intent.EXTRA_USER;
20import static android.content.Intent.EXTRA_USER_ID;
21import static android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
22import static android.text.format.DateUtils.FORMAT_SHOW_DATE;
23
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010024import android.annotation.Nullable;
Amith Yamasaniae697552011-09-27 11:33:17 -070025import android.app.ActivityManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010026import android.app.AppGlobals;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070027import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010028import android.app.IActivityManager;
Rubin Xu3231afe2016-08-24 10:15:07 +010029import android.app.KeyguardManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010030import android.app.admin.DevicePolicyManager;
Daniel Nishi31027da2017-01-19 14:03:57 -080031import android.content.ActivityNotFoundException;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080032import android.content.ComponentName;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070033import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080034import android.content.Context;
35import android.content.Intent;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080036import android.content.IntentFilter;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080037import android.content.pm.ApplicationInfo;
Sudheer Shankabc956302015-04-09 12:19:53 +010038import android.content.pm.IPackageManager;
Christopher Tatea08a2252015-07-01 16:52:43 -070039import android.content.pm.IntentFilterVerificationInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080040import android.content.pm.PackageManager;
Jason Monk75199542016-05-06 15:09:32 -040041import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070042import android.content.pm.ResolveInfo;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070043import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020044import android.content.res.Resources;
Jason Monkb5aa73f2015-03-31 12:59:33 -040045import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070046import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070047import android.graphics.Bitmap;
Felipe Lemebd884502017-09-15 18:16:21 -070048import android.graphics.Canvas;
49import android.graphics.drawable.BitmapDrawable;
50import android.graphics.drawable.Drawable;
Jeff Sharkeyab508072016-10-11 14:25:22 -060051import android.hardware.fingerprint.FingerprintManager;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080052import android.net.ConnectivityManager;
53import android.net.LinkProperties;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070054import android.net.Network;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070055import android.net.wifi.WifiManager;
Amith Yamasania4379d62011-07-22 10:34:58 -070056import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020057import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010058import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040059import android.os.INetworkManagementService;
Jason Monkbe941212016-05-27 12:58:53 -040060import android.os.Looper;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010061import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040062import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070063import android.os.UserHandle;
64import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080065import android.os.storage.StorageManager;
Daniel Nishi9f60f422017-02-15 15:25:48 -080066import android.os.storage.VolumeInfo;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070067import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070068import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070069import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070070import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070071import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070072import android.provider.ContactsContract.RawContacts;
Udam Saini679f7ad2016-03-25 10:47:00 -070073import android.provider.Settings;
jackqdyuleiddba9662017-03-08 19:35:02 -080074import android.support.annotation.StringRes;
Jason Monk39b46742015-09-10 15:52:51 -040075import android.support.v7.preference.Preference;
76import android.support.v7.preference.PreferenceGroup;
Jason Monk91e2f892016-02-23 15:31:09 -050077import android.support.v7.preference.PreferenceManager;
78import android.support.v7.preference.PreferenceScreen;
Amith Yamasani60133dd2010-09-11 14:17:31 -070079import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040080import android.text.Spannable;
81import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020082import android.text.TextUtils;
Jason Monkb37e2882016-01-11 14:27:20 -050083import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040084import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070085import android.util.ArraySet;
jackqdyuleifde637f2018-01-02 14:51:01 -080086import android.util.IconDrawableFactory;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010087import android.util.Log;
Jason Monkdb4ed192015-12-11 16:48:31 -050088import android.util.TypedValue;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000089import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070090import android.view.View;
91import android.view.ViewGroup;
PMS2263a05602017-06-14 07:10:15 +000092import android.widget.EditText;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070093import android.widget.ListView;
94import android.widget.TabWidget;
Fan Zhangcc335d92016-09-29 14:37:14 -070095
Ricky Wai616342b2016-04-13 10:40:22 +010096import com.android.internal.app.UnlaunchableAppActivity;
Ricky Wai72500162016-06-07 16:54:25 +010097import com.android.internal.util.ArrayUtils;
Rubin Xu3231afe2016-08-24 10:15:07 +010098import com.android.internal.widget.LockPatternUtils;
Jeff Sharkey219ec912017-12-19 14:57:39 -070099import com.android.settings.password.ChooseLockSettingsHelper;
Doris Lingdee1a222017-08-31 16:17:30 -0700100import com.android.settings.wrapper.DevicePolicyManagerWrapper;
Tony Mantlerd9af0b82017-10-20 15:03:28 -0700101import com.android.settings.wrapper.FingerprintManagerWrapper;
Leif Hendrik Wilden28dee1f2018-01-11 10:15:36 -0800102import com.android.settingslib.core.instrumentation.VisibilityLoggerMixin;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700103
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800104import java.net.InetAddress;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100105import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800106import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700107import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900108import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800109
Jason Monk27985e12016-01-08 14:13:05 -0500110public final class Utils extends com.android.settingslib.Utils {
111
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100112 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100113
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800114 /**
115 * Set the preference's title to the matching activity's label.
116 */
117 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
118
119 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700120 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
121 * 1 is most bad (red), the last value is least bad (green).
122 */
123 public static final int[] BADNESS_COLORS = new int[] {
124 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
125 0xfffabf2c, 0xff679e37, 0xff0a7f42
126 };
127
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100128 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
129
Jason Monkbeb171d2015-05-21 15:24:37 -0400130 public static final String OS_PKG = "os";
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 /**
Benjamin Franz194300d2016-01-13 12:16:25 +0000188 * Returns the UserManager for a given context
189 *
190 * @throws IllegalStateException if no UserManager could be retrieved.
191 */
192 public static UserManager getUserManager(Context context) {
193 UserManager um = UserManager.get(context);
194 if (um == null) {
195 throw new IllegalStateException("Unable to load UserManager");
196 }
197 return um;
198 }
199
200 /**
Ying Wanga7188322010-01-04 18:45:10 -0800201 * Returns true if Monkey is running.
202 */
203 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700204 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800205 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700206
207 /**
208 * Returns whether the device is voice-capable (meaning, it is also a phone).
209 */
210 public static boolean isVoiceCapable(Context context) {
211 TelephonyManager telephony =
212 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
213 return telephony != null && telephony.isVoiceCapable();
214 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800215
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800216 /**
217 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
218 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900219 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800220 */
221 public static String getWifiIpAddresses(Context context) {
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700222 WifiManager wifiManager = context.getSystemService(WifiManager.class);
223 Network currentNetwork = wifiManager.getCurrentNetwork();
224 if (currentNetwork != null) {
225 ConnectivityManager cm = (ConnectivityManager)
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800226 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700227 LinkProperties prop = cm.getLinkProperties(currentNetwork);
228 return formatIpAddresses(prop);
229 }
230 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700231 }
232
Amith Yamasani6822b742011-10-17 16:41:00 -0700233 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800234 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900235 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800236 // If there are no entries, return null
237 if (!iter.hasNext()) return null;
238 // Concatenate all available addresses, comma separated
239 String addresses = "";
240 while (iter.hasNext()) {
241 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900242 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800243 }
244 return addresses;
245 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900246
247 public static Locale createLocaleFromString(String localeStr) {
248 // TODO: is there a better way to actually construct a locale that will match?
249 // The main problem is, on top of Java specs, locale.toString() and
250 // new Locale(locale.toString()).toString() do not return equal() strings in
251 // many cases, because the constructor takes the only string as the language
252 // code. So : new Locale("en", "US").toString() => "en_US"
253 // And : new Locale("en_US").toString() => "en_us"
254 if (null == localeStr)
255 return Locale.getDefault();
256 String[] brokenDownLocale = localeStr.split("_", 3);
257 // split may not return a 0-length array.
258 if (1 == brokenDownLocale.length) {
259 return new Locale(brokenDownLocale[0]);
260 } else if (2 == brokenDownLocale.length) {
261 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
262 } else {
263 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
264 }
265 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700266
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900267 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
268 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
269 }
270
Amith Yamasania4379d62011-07-22 10:34:58 -0700271 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700272 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700273 }
274
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700275 /**
276 * Prepare a custom preferences layout, moving padding to {@link ListView}
277 * when outside scrollbars are requested. Usually used to display
278 * {@link ListView} and {@link TabWidget} with correct padding.
279 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700280 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800281 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700282 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700283 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700284 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700285 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700286 final int paddingBottom = res.getDimensionPixelSize(
287 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700288
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700289 if (parent instanceof PreferenceFrameLayout) {
290 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
291
292 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
293 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
294 } else {
295 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
296 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700297 }
298 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700299
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700300 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700301 final Resources res = view.getResources();
302 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700303
304 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
305 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700306 final int paddingBottom = res.getDimensionPixelSize(
307 com.android.internal.R.dimen.preference_fragment_padding_bottom);
308
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700309 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700310 }
311
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700312 public static String getMeProfileName(Context context, boolean full) {
313 if (full) {
314 return getProfileDisplayName(context);
315 } else {
316 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700317 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700318 }
319
320 private static String getShorterNameIfPossible(Context context) {
321 final String given = getLocalProfileGivenName(context);
322 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
323 }
324
325 private static String getLocalProfileGivenName(Context context) {
326 final ContentResolver cr = context.getContentResolver();
327
328 // Find the raw contact ID for the local ME profile raw contact.
329 final long localRowProfileId;
330 final Cursor localRawProfile = cr.query(
331 Profile.CONTENT_RAW_CONTACTS_URI,
332 new String[] {RawContacts._ID},
333 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
334 RawContacts.ACCOUNT_NAME + " IS NULL",
335 null, null);
336 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700337
338 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700339 if (!localRawProfile.moveToFirst()) {
340 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700341 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700342 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700343 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700344 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700345 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700346
347 // Find the structured name for the raw contact.
348 final Cursor structuredName = cr.query(
349 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
350 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
351 CommonDataKinds.StructuredName.FAMILY_NAME},
352 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
353 null, null);
354 if (structuredName == null) return null;
355
356 try {
357 if (!structuredName.moveToFirst()) {
358 return null;
359 }
360 String partialName = structuredName.getString(0);
361 if (TextUtils.isEmpty(partialName)) {
362 partialName = structuredName.getString(1);
363 }
364 return partialName;
365 } finally {
366 structuredName.close();
367 }
368 }
369
370 private static final String getProfileDisplayName(Context context) {
371 final ContentResolver cr = context.getContentResolver();
372 final Cursor profile = cr.query(Profile.CONTENT_URI,
373 new String[] {Profile.DISPLAY_NAME}, null, null, null);
374 if (profile == null) return null;
375
376 try {
377 if (!profile.moveToFirst()) {
378 return null;
379 }
380 return profile.getString(0);
381 } finally {
382 profile.close();
383 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700384 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700385
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700386 public static boolean hasMultipleUsers(Context context) {
387 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
388 .getUsers().size() > 1;
389 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700390
391 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100392 * Returns the managed profile of the current user or {@code null} if none is found or a profile
393 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100394 */
395 public static UserHandle getManagedProfile(UserManager userManager) {
396 List<UserHandle> userProfiles = userManager.getUserProfiles();
397 final int count = userProfiles.size();
398 for (int i = 0; i < count; i++) {
399 final UserHandle profile = userProfiles.get(i);
400 if (profile.getIdentifier() == userManager.getUserHandle()) {
401 continue;
402 }
403 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
404 if (userInfo.isManagedProfile()) {
405 return profile;
406 }
407 }
408 return null;
409 }
410
411 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100412 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
413 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
414 */
415 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
416 // TODO: Call getManagedProfileId from here once Robolectric supports
417 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
418 // yet another implementation that loops over user profiles in this method). In the meantime
419 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
420 // used for Settings Robolectric tests).
421 final int myUserId = UserHandle.myUserId();
422 List<UserInfo> profiles = userManager.getProfiles(myUserId);
423 final int count = profiles.size();
424 for (int i = 0; i < count; i++) {
425 final UserInfo profile = profiles.get(i);
426 if (profile.isManagedProfile()
427 && profile.getUserHandle().getIdentifier() != myUserId) {
428 return profile.getUserHandle();
429 }
430 }
431 return null;
432 }
433
434 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000435 * Retrieves the id for the given user's managed profile.
436 *
437 * @return the managed profile id or UserHandle.USER_NULL if there is none.
438 */
439 public static int getManagedProfileId(UserManager um, int parentUserId) {
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700440 int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
441 for (int profileId : profileIds) {
442 if (profileId != parentUserId) {
443 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000444 }
445 }
446 return UserHandle.USER_NULL;
447 }
448
449 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100450 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000451 * <p>
452 * User would be retrieved in this order:
453 * <ul>
454 * <li> If this activity is launched from other user, return that user id.
455 * <li> If this is launched from the Settings app in same user, return the user contained as an
456 * extra in the arguments or intent extras.
457 * <li> Otherwise, return UserHandle.myUserId().
458 * </ul>
459 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100460 * Note: This is secure in the sense that it only returns a target user different to the current
461 * one if the app launching this activity is the Settings app itself, running in the same user
462 * 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 +0100463 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100464 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000465 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100466 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800467 IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100468 try {
469 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
470 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
471
472 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
473 am.getLaunchedFromUid(activityToken)));
474 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
475 // Check it's secure
476 if (isProfileOf(um, launchedFromUser)) {
477 return launchedFromUser;
478 }
479 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000480 UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100481 if (extrasUser != null && !extrasUser.equals(currentUser)) {
482 // Check it's secure
483 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
484 return extrasUser;
485 }
486 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000487 UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100488 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
489 // Check it's secure
490 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
491 return argumentsUser;
492 }
493 }
494 } catch (RemoteException e) {
495 // Should not happen
496 Log.v(TAG, "Could not talk to activity manager.", e);
497 }
498 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000499 }
500
501 /**
502 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
503 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
504 */
505 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
506 if (bundle == null) {
507 return null;
508 }
509 final UserHandle user = bundle.getParcelable(EXTRA_USER);
510 if (user != null) {
511 return user;
512 }
513 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
514 if (userId != -1) {
515 return UserHandle.of(userId);
516 }
517 return null;
518 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100519
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100520 /**
521 * Returns true if the user provided is in the same profiles group as the current user.
522 */
523 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
524 if (um == null || otherUser == null) return false;
525 return (UserHandle.myUserId() == otherUser.getIdentifier())
526 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100527 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530528
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100529 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700530 * Return whether or not the user should have a SIM Cards option in Settings.
531 * TODO: Change back to returning true if count is greater than one after testing.
532 * TODO: See bug 16533525.
533 */
534 public static boolean showSimCardTile(Context context) {
535 final TelephonyManager tm =
536 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
537
PauloftheWestdbd03822014-12-04 11:56:35 -0800538 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700539 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200540
541 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800542 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
543 * @param userManager Instance of UserManager
544 * @param checkUser The user to check the existence of.
545 * @return UserInfo of the user or null for non-existent user.
546 */
547 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
548 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
549 final int checkUserId = checkUser.getIdentifier();
550 for (UserInfo user : users) {
551 if (user.id == checkUserId) {
552 return user;
553 }
554 }
555 return null;
556 }
557
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000558 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
559 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
560 com.android.internal.R.styleable.Preference,
561 com.android.internal.R.attr.preferenceCategoryStyle, 0);
562 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
563 0);
564 a.recycle();
565 return inflater.inflate(resId, parent, false);
566 }
567
Christopher Tatea08a2252015-07-01 16:52:43 -0700568 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
569 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
570 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
571
572 ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800573 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700574 for (IntentFilterVerificationInfo ivi : iviList) {
575 for (String host : ivi.getDomains()) {
576 result.add(host);
577 }
578 }
579 }
580 if (filters != null && filters.size() > 0) {
581 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700582 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
583 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
584 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700585 result.addAll(filter.getHostsList());
586 }
587 }
588 }
589 return result;
590 }
591
Sudheer Shankabc956302015-04-09 12:19:53 +0100592 /**
593 * Returns the application info of the currently installed MDM package.
594 */
595 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
596 DevicePolicyManager dpm =
597 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
598 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
599 if (mdmPackage == null) {
600 return null;
601 }
602 String mdmPackageName = mdmPackage.getPackageName();
603 try {
604 IPackageManager ipm = AppGlobals.getPackageManager();
605 ApplicationInfo mdmApplicationInfo =
606 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
607 return mdmApplicationInfo;
608 } catch (RemoteException e) {
609 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
610 + ", userId " + profileId, e);
611 return null;
612 }
613 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400614
615 public static boolean isBandwidthControlEnabled() {
616 final INetworkManagementService netManager = INetworkManagementService.Stub
617 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
618 try {
619 return netManager.isBandwidthControlEnabled();
620 } catch (RemoteException e) {
621 return false;
622 }
623 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400624
625 /**
626 * Returns an accessible SpannableString.
627 * @param displayText the text to display
628 * @param accessibileText the text text-to-speech engines should read
629 */
630 public static SpannableString createAccessibleSequence(CharSequence displayText,
631 String accessibileText) {
632 SpannableString str = new SpannableString(displayText);
633 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
634 displayText.length(),
635 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
636 return str;
637 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700638
Clara Bayarrife432e82015-10-12 12:07:02 +0100639 /**
Jeff Sharkey219ec912017-12-19 14:57:39 -0700640 * Returns the user id present in the bundle with
641 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
Clara Bayarrife432e82015-10-12 12:07:02 +0100642 *
Jeff Sharkey219ec912017-12-19 14:57:39 -0700643 * @throws SecurityException if the given userId does not belong to the
644 * current user group.
Clara Bayarrife432e82015-10-12 12:07:02 +0100645 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000646 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700647 return getUserIdFromBundle(context, bundle, false);
648 }
649
650 /**
651 * Returns the user id present in the bundle with
652 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
653 *
654 * @param isInternal indicating if the caller is "internal" to the system,
655 * meaning we're willing to trust extras like
656 * {@link ChooseLockSettingsHelper#EXTRA_ALLOW_ANY_USER}.
657 * @throws SecurityException if the given userId does not belong to the
658 * current user group.
659 */
660 public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
Clara Bayarrife432e82015-10-12 12:07:02 +0100661 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +0000662 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +0100663 }
Jeff Sharkey219ec912017-12-19 14:57:39 -0700664 final boolean allowAnyUser = isInternal
665 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_ALLOW_ANY_USER, false);
Clara Bayarri6934a042015-10-14 11:07:35 +0100666 int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700667 if (userId == LockPatternUtils.USER_FRP) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700668 return allowAnyUser ? userId : enforceSystemUser(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700669 } else {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700670 return allowAnyUser ? userId : enforceSameOwner(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700671 }
672 }
673
674 /**
675 * Returns the given user id if the current user is the system user.
676 *
677 * @throws SecurityException if the current user is not the system user.
678 */
679 public static int enforceSystemUser(Context context, int userId) {
680 if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
681 return userId;
682 }
683 throw new SecurityException("Given user id " + userId + " must only be used from "
684 + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100685 }
686
687 /**
688 * Returns the given user id if it belongs to the current user.
689 *
690 * @throws SecurityException if the given userId does not belong to the current user group.
691 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000692 public static int enforceSameOwner(Context context, int userId) {
Ricky Wai72500162016-06-07 16:54:25 +0100693 final UserManager um = getUserManager(context);
694 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
695 if (ArrayUtils.contains(profileIds, userId)) {
696 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +0100697 }
Ricky Wai72500162016-06-07 16:54:25 +0100698 throw new SecurityException("Given user id " + userId + " does not belong to user "
699 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100700 }
701
Benjamin Franz194300d2016-01-13 12:16:25 +0000702 /**
703 * Returns the effective credential owner of the calling user.
704 */
705 public static int getCredentialOwnerUserId(Context context) {
706 return getCredentialOwnerUserId(context, UserHandle.myUserId());
707 }
708
709 /**
710 * Returns the user id of the credential owner of the given user id.
711 */
712 public static int getCredentialOwnerUserId(Context context, int userId) {
713 UserManager um = getUserManager(context);
714 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700715 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500716
Jason Monkb37e2882016-01-11 14:27:20 -0500717 private static final StringBuilder sBuilder = new StringBuilder(50);
718 private static final java.util.Formatter sFormatter = new java.util.Formatter(
719 sBuilder, Locale.getDefault());
720
721 public static String formatDateRange(Context context, long start, long end) {
722 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
723
724 synchronized (sBuilder) {
725 sBuilder.setLength(0);
726 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
727 .toString();
728 }
729 }
Jason Monk91e2f892016-02-23 15:31:09 -0500730
Udam Saini679f7ad2016-03-25 10:47:00 -0700731 public static boolean isDeviceProvisioned(Context context) {
732 return Settings.Global.getInt(context.getContentResolver(),
733 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
734 }
Ricky Wai616342b2016-04-13 10:40:22 +0100735
Bernard Chau88d523b2016-04-14 15:08:28 +0100736 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100737 int userId) {
738 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
739 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
740 context.startActivity(intent);
741 return true;
742 }
743 return false;
744 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700745
Rubin Xu3231afe2016-08-24 10:15:07 +0100746 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
747 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800748 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100749 ActivityManager.FLAG_AND_LOCKED)) {
750 return false;
751 }
752 } catch (RemoteException e) {
753 return false;
754 }
755 if (!(new LockPatternUtils(context)).isSecure(userId)) {
756 return false;
757 }
Robin Leecccf3242017-02-10 15:32:49 +0000758 return confirmWorkProfileCredentials(context, userId);
759 }
760
Robin Leecccf3242017-02-10 15:32:49 +0000761 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100762 final KeyguardManager km = (KeyguardManager) context.getSystemService(
763 Context.KEYGUARD_SERVICE);
764 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
765 if (unlockIntent != null) {
766 context.startActivity(unlockIntent);
767 return true;
768 } else {
769 return false;
770 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100771 }
772
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700773 public static CharSequence getApplicationLabel(Context context, String packageName) {
774 try {
775 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
776 packageName,
777 PackageManager.MATCH_DISABLED_COMPONENTS
Amith Yamasani21556cd2016-11-01 15:49:21 -0700778 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700779 return appInfo.loadLabel(context.getPackageManager());
780 } catch (PackageManager.NameNotFoundException e) {
781 Log.w(TAG, "Unable to find info for package: " + packageName);
782 }
783 return null;
784 }
Jason Monk75199542016-05-06 15:09:32 -0400785
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600786 public static boolean isPackageDirectBootAware(Context context, String packageName) {
787 try {
788 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
789 packageName, 0);
790 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
791 } catch (NameNotFoundException ignored) {
792 }
793 return false;
794 }
Andre Lago3e398c82016-07-25 14:12:28 +0100795
796 /**
797 * Returns a context created from the given context for the given user, or null if it fails
798 */
799 public static Context createPackageContextAsUser(Context context, int userId) {
800 try {
801 return context.createPackageContextAsUser(
802 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
803 } catch (PackageManager.NameNotFoundException e) {
804 Log.e(TAG, "Failed to create user context", e);
805 }
806 return null;
807 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600808
809 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
810 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800811 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600812 } else {
813 return null;
814 }
815 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800816
Doris Lingdee1a222017-08-31 16:17:30 -0700817 public static FingerprintManagerWrapper getFingerprintManagerWrapperOrNull(Context context) {
Maurice Lame1976ac2017-05-08 21:43:02 -0700818 FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
819 if (fingerprintManager != null) {
820 return new FingerprintManagerWrapper(fingerprintManager);
821 } else {
822 return null;
823 }
824 }
825
Kevin Chyn82792cc2017-07-20 00:15:44 -0700826 public static boolean hasFingerprintHardware(Context context) {
827 FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
828 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
829 }
830
Daniel Nishi31027da2017-01-19 14:03:57 -0800831 /**
832 * Launches an intent which may optionally have a user id defined.
833 * @param fragment Fragment to use to launch the activity.
834 * @param intent Intent to launch.
835 */
836 public static void launchIntent(Fragment fragment, Intent intent) {
837 try {
838 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
839
840 if (userId == -1) {
841 fragment.startActivity(intent);
842 } else {
843 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
844 }
845 } catch (ActivityNotFoundException e) {
846 Log.w(TAG, "No activity found for " + intent);
847 }
848 }
849
Christine Franksc6890ab2017-06-23 14:28:21 -0700850 public static boolean isDemoUser(Context context) {
851 return UserManager.isDeviceInDemoMode(context) && getUserManager(context).isDemoUser();
852 }
853
Justin Klaassen30257272017-08-08 21:58:05 -0700854 public static ComponentName getDeviceOwnerComponent(Context context) {
855 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
856 Context.DEVICE_POLICY_SERVICE);
857 return dpm.getDeviceOwnerComponentOnAnyUser();
Christine Franks14782222017-01-23 16:44:02 -0800858 }
Daniel Nishidfed8a22017-01-19 16:32:41 -0800859
860 /**
861 * Returns if a given user is a profile of another user.
Christine Franksa0dd9872017-07-11 17:32:57 -0700862 * @param user The user whose profiles wibe checked.
Daniel Nishidfed8a22017-01-19 16:32:41 -0800863 * @param profile The (potential) profile.
864 * @return if the profile is actually a profile
865 */
866 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
867 return user.id == profile.id ||
868 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
869 && user.profileGroupId == profile.profileGroupId);
870 }
Daniel Nishi9f60f422017-02-15 15:25:48 -0800871
872 /**
873 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
874 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
875 */
876 @Nullable
877 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
878 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
879 VolumeInfo.ID_PRIVATE_INTERNAL);
880 VolumeInfo volume = sm.findVolumeById(volumeId);
881 return isVolumeValid(volume) ? volume : null;
882 }
883
jackqdyuleiddba9662017-03-08 19:35:02 -0800884 /**
jackqdyulei00015fb2017-08-22 11:25:30 -0700885 * Return {@code true} if the supplied package is device owner or profile owner of at
886 * least one user.
887 * @param userManager used to get profile owner app for each user
888 * @param devicePolicyManager used to check whether it is device owner app
889 * @param packageName package to check about
890 */
891 public static boolean isProfileOrDeviceOwner(UserManager userManager,
892 DevicePolicyManagerWrapper devicePolicyManager, String packageName) {
893 List<UserInfo> userInfos = userManager.getUsers();
894 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
895 return true;
896 }
897 for (int i = 0, size = userInfos.size(); i < size; i++) {
898 ComponentName cn = devicePolicyManager.getProfileOwnerAsUser(userInfos.get(i).id);
899 if (cn != null && cn.getPackageName().equals(packageName)) {
900 return true;
901 }
902 }
903 return false;
904 }
905
906 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800907 * Return the resource id to represent the install status for an app
908 */
909 @StringRes
910 public static int getInstallationStatus(ApplicationInfo info) {
911 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
912 return R.string.not_installed;
913 }
914 return info.enabled ? R.string.installed : R.string.disabled;
915 }
916
Daniel Nishi9f60f422017-02-15 15:25:48 -0800917 private static boolean isVolumeValid(VolumeInfo volume) {
918 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
919 && volume.isMountedReadable();
920 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700921
PMS2263a05602017-06-14 07:10:15 +0000922 public static void setEditTextCursorPosition(EditText editText) {
923 editText.setSelection(editText.getText().length());
924 }
Felipe Lemebd884502017-09-15 18:16:21 -0700925
926 /**
927 * Sets the preference icon with a drawable that is scaled down to to avoid crashing Settings if
928 * it's too big.
929 */
930 public static void setSafeIcon(Preference pref, Drawable icon) {
931 Drawable safeIcon = icon;
932 if (icon != null) {
933 safeIcon = getSafeDrawable(icon, 500, 500);
934 }
935 pref.setIcon(safeIcon);
936 }
937
938 /**
939 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
940 *
941 * @param original original drawable, typically an app icon.
942 * @param maxWidth maximum width, in pixels.
943 * @param maxHeight maximum height, in pixels.
944 */
945 public static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
946 final int actualWidth = original.getMinimumWidth();
947 final int actualHeight = original.getMinimumHeight();
948
949 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
950 return original;
951 }
952
953 float scaleWidth = ((float) maxWidth) / actualWidth;
954 float scaleHeight = ((float) maxHeight) / actualHeight;
955 float scale = Math.min(scaleWidth, scaleHeight);
956 final int width = (int) (actualWidth * scale);
957 final int height = (int) (actualHeight * scale);
958
959 final Bitmap bitmap;
960 if (original instanceof BitmapDrawable) {
961 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
962 height, false);
963 } else {
964 bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
965 final Canvas canvas = new Canvas(bitmap);
966 original.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
967 original.draw(canvas);
968 }
969 return new BitmapDrawable(null, bitmap);
970 }
jackqdyuleifde637f2018-01-02 14:51:01 -0800971
972 /**
973 * Get the {@link Drawable} that represents the app icon
974 */
975 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
976 PackageManager packageManager, String packageName, int userId) {
977 try {
978 final ApplicationInfo appInfo = packageManager.getApplicationInfo(packageName,
979 PackageManager.GET_META_DATA);
980 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
981 } catch (PackageManager.NameNotFoundException e) {
982 return packageManager.getDefaultActivityIcon();
983 }
984 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600985}