blob: 00542cad0179d6301af5ef85db381467e839b1b7 [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;
tmfangaed8f362019-03-18 16:56:09 +080025import android.app.ActionBar;
26import android.app.Activity;
Amith Yamasaniae697552011-09-27 11:33:17 -070027import android.app.ActivityManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010028import android.app.AppGlobals;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010029import android.app.IActivityManager;
Rubin Xu3231afe2016-08-24 10:15:07 +010030import android.app.KeyguardManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010031import android.app.admin.DevicePolicyManager;
Daniel Nishi31027da2017-01-19 14:03:57 -080032import android.content.ActivityNotFoundException;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080033import android.content.ComponentName;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070034import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080035import android.content.Context;
36import android.content.Intent;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080037import android.content.IntentFilter;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080038import android.content.pm.ApplicationInfo;
Sudheer Shankabc956302015-04-09 12:19:53 +010039import android.content.pm.IPackageManager;
Christopher Tatea08a2252015-07-01 16:52:43 -070040import android.content.pm.IntentFilterVerificationInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080041import android.content.pm.PackageManager;
Jason Monk75199542016-05-06 15:09:32 -040042import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070043import android.content.pm.ResolveInfo;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070044import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020045import android.content.res.Resources;
Jason Monkb5aa73f2015-03-31 12:59:33 -040046import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070047import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070048import android.graphics.Bitmap;
Felipe Lemebd884502017-09-15 18:16:21 -070049import android.graphics.Canvas;
50import android.graphics.drawable.BitmapDrawable;
51import android.graphics.drawable.Drawable;
Phil Weaver5a3e02d2018-03-08 17:38:46 -080052import android.graphics.drawable.VectorDrawable;
Kevin Chyn4882e872018-06-25 17:58:31 -070053import android.hardware.face.FaceManager;
Jeff Sharkeyab508072016-10-11 14:25:22 -060054import android.hardware.fingerprint.FingerprintManager;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080055import android.net.ConnectivityManager;
56import android.net.LinkProperties;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070057import android.net.Network;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070058import android.net.wifi.WifiManager;
Amith Yamasania4379d62011-07-22 10:34:58 -070059import android.os.BatteryManager;
Ng Zhi Anb97bdc32019-02-01 12:39:31 -080060import android.os.Build;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020061import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010062import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040063import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010064import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040065import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070066import android.os.UserHandle;
67import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080068import android.os.storage.StorageManager;
Daniel Nishi9f60f422017-02-15 15:25:48 -080069import android.os.storage.VolumeInfo;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070070import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070071import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070072import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070073import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070074import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070075import android.provider.ContactsContract.RawContacts;
Udam Saini679f7ad2016-03-25 10:47:00 -070076import android.provider.Settings;
markchien1dd1d792019-01-11 16:18:20 +080077import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070078import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040079import android.text.Spannable;
80import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020081import android.text.TextUtils;
Jason Monkb37e2882016-01-11 14:27:20 -050082import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040083import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070084import android.util.ArraySet;
jackqdyuleifde637f2018-01-02 14:51:01 -080085import android.util.IconDrawableFactory;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010086import android.util.Log;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000087import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070088import android.view.View;
89import android.view.ViewGroup;
PMS2263a05602017-06-14 07:10:15 +000090import android.widget.EditText;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070091import android.widget.ListView;
92import android.widget.TabWidget;
Fan Zhangcc335d92016-09-29 14:37:14 -070093
Fan Zhang23f8d592018-08-28 15:11:40 -070094import androidx.annotation.StringRes;
Sunny Shao660b36e2019-08-08 15:43:38 +080095import androidx.annotation.NonNull;
Jason Chiuc78c54a2019-02-13 16:07:57 +080096import androidx.core.graphics.drawable.IconCompat;
Fan Zhang23f8d592018-08-28 15:11:40 -070097import androidx.fragment.app.Fragment;
tmfangaed8f362019-03-18 16:56:09 +080098import androidx.lifecycle.Lifecycle;
Fan Zhang23f8d592018-08-28 15:11:40 -070099import androidx.preference.Preference;
100import androidx.preference.PreferenceGroup;
101
Ricky Wai616342b2016-04-13 10:40:22 +0100102import com.android.internal.app.UnlaunchableAppActivity;
Ricky Wai72500162016-06-07 16:54:25 +0100103import com.android.internal.util.ArrayUtils;
Rubin Xu3231afe2016-08-24 10:15:07 +0100104import com.android.internal.widget.LockPatternUtils;
Antony Sargent627f14b2019-03-04 16:00:59 -0800105import com.android.settings.core.FeatureFlags;
106import com.android.settings.development.featureflags.FeatureFlagPersistent;
Jeff Sharkey219ec912017-12-19 14:57:39 -0700107import com.android.settings.password.ChooseLockSettingsHelper;
tmfangaed8f362019-03-18 16:56:09 +0800108import com.android.settingslib.widget.ActionBarShadowController;
Sunny Shao660b36e2019-08-08 15:43:38 +0800109import com.android.settingslib.widget.FooterPreference;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700110
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800111import java.net.InetAddress;
112import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700113import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900114import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800115
Jason Monk27985e12016-01-08 14:13:05 -0500116public final class Utils extends com.android.settingslib.Utils {
117
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100118 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100119
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800120 /**
121 * Set the preference's title to the matching activity's label.
122 */
123 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
124
Fan Zhangc3fd2892019-01-29 16:00:19 -0800125 public static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100126
Jason Monkbeb171d2015-05-21 15:24:37 -0400127 public static final String OS_PKG = "os";
128
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200129 /**
Svet Ganov864765f2019-04-05 19:00:05 -0700130 * Whether to disable the new device identifier access restrictions.
131 */
132 public static final String PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED =
133 "device_identifier_access_restrictions_disabled";
134
135 /**
Joel Galenson2118f8a2019-05-31 07:54:20 -0700136 * Whether to show the Permissions Hub.
137 */
138 public static final String PROPERTY_PERMISSIONS_HUB_ENABLED = "permissions_hub_enabled";
139
140 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800141 * Finds a matching activity for a preference's intent. If a matching
142 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800143 *
Sunny Shao660b36e2019-08-08 15:43:38 +0800144 * @param context The context.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800145 * @param parentPreferenceGroup The preference group that contains the
Sunny Shao660b36e2019-08-08 15:43:38 +0800146 * preference whose intent is being resolved.
147 * @param preferenceKey The key of the preference whose intent is being
148 * resolved.
149 * @param flags 0 or one or more of
150 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
151 * .
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800152 * @return Whether an activity was found. If false, the preference was
Sunny Shao660b36e2019-08-08 15:43:38 +0800153 * removed.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800154 */
155 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
156 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800157
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800158 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
159 if (preference == null) {
160 return false;
161 }
Ying Wanga7188322010-01-04 18:45:10 -0800162
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800163 Intent intent = preference.getIntent();
164 if (intent != null) {
165 // Find the activity that is in the system image
166 PackageManager pm = context.getPackageManager();
167 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
168 int listSize = list.size();
169 for (int i = 0; i < listSize; i++) {
170 ResolveInfo resolveInfo = list.get(i);
171 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
172 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800173
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800174 // Replace the intent with this specific activity
175 preference.setIntent(new Intent().setClassName(
176 resolveInfo.activityInfo.packageName,
177 resolveInfo.activityInfo.name));
178
179 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
180 // Set the preference title to the activity's label
181 preference.setTitle(resolveInfo.loadLabel(pm));
182 }
Ying Wanga7188322010-01-04 18:45:10 -0800183
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800184 return true;
185 }
186 }
187 }
188
189 // Did not find a matching activity, so remove the preference
190 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800191
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900192 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800193 }
Ying Wanga7188322010-01-04 18:45:10 -0800194
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200195 /**
Benjamin Franz194300d2016-01-13 12:16:25 +0000196 * Returns the UserManager for a given context
197 *
198 * @throws IllegalStateException if no UserManager could be retrieved.
199 */
200 public static UserManager getUserManager(Context context) {
201 UserManager um = UserManager.get(context);
202 if (um == null) {
203 throw new IllegalStateException("Unable to load UserManager");
204 }
205 return um;
206 }
207
208 /**
Ying Wanga7188322010-01-04 18:45:10 -0800209 * Returns true if Monkey is running.
210 */
211 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700212 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800213 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700214
215 /**
216 * Returns whether the device is voice-capable (meaning, it is also a phone).
217 */
218 public static boolean isVoiceCapable(Context context) {
219 TelephonyManager telephony =
220 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
221 return telephony != null && telephony.isVoiceCapable();
222 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800223
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800224 /**
225 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
Sunny Shao660b36e2019-08-08 15:43:38 +0800226 *
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800227 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900228 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800229 */
230 public static String getWifiIpAddresses(Context context) {
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700231 WifiManager wifiManager = context.getSystemService(WifiManager.class);
232 Network currentNetwork = wifiManager.getCurrentNetwork();
233 if (currentNetwork != null) {
234 ConnectivityManager cm = (ConnectivityManager)
Sunny Shao660b36e2019-08-08 15:43:38 +0800235 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700236 LinkProperties prop = cm.getLinkProperties(currentNetwork);
237 return formatIpAddresses(prop);
238 }
239 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700240 }
241
Amith Yamasani6822b742011-10-17 16:41:00 -0700242 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800243 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900244 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800245 // If there are no entries, return null
246 if (!iter.hasNext()) return null;
247 // Concatenate all available addresses, comma separated
248 String addresses = "";
249 while (iter.hasNext()) {
250 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900251 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800252 }
253 return addresses;
254 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900255
256 public static Locale createLocaleFromString(String localeStr) {
257 // TODO: is there a better way to actually construct a locale that will match?
258 // The main problem is, on top of Java specs, locale.toString() and
259 // new Locale(locale.toString()).toString() do not return equal() strings in
260 // many cases, because the constructor takes the only string as the language
261 // code. So : new Locale("en", "US").toString() => "en_US"
262 // And : new Locale("en_US").toString() => "en_us"
Sunny Shao660b36e2019-08-08 15:43:38 +0800263 if (null == localeStr) {
Jean Chalard71ad1f42011-05-12 15:06:16 +0900264 return Locale.getDefault();
Sunny Shao660b36e2019-08-08 15:43:38 +0800265 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900266 String[] brokenDownLocale = localeStr.split("_", 3);
267 // split may not return a 0-length array.
268 if (1 == brokenDownLocale.length) {
269 return new Locale(brokenDownLocale[0]);
270 } else if (2 == brokenDownLocale.length) {
271 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
272 } else {
273 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
274 }
275 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700276
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900277 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
278 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
279 }
280
Amith Yamasania4379d62011-07-22 10:34:58 -0700281 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700282 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700283 }
284
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700285 /**
286 * Prepare a custom preferences layout, moving padding to {@link ListView}
287 * when outside scrollbars are requested. Usually used to display
288 * {@link ListView} and {@link TabWidget} with correct padding.
289 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700290 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800291 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700292 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700293 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700294 final Resources res = list.getResources();
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700295 final int paddingBottom = res.getDimensionPixelSize(
296 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700297
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700298 if (parent instanceof PreferenceFrameLayout) {
299 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700300 }
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800301 list.setPaddingRelative(0 /* start */, 0 /* top */, 0 /* end */, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700302 }
303 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700304
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700305 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700306 final Resources res = view.getResources();
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700307
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800308 final int paddingStart = additive ? view.getPaddingStart() : 0;
309 final int paddingEnd = additive ? view.getPaddingEnd() : 0;
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700310 final int paddingBottom = res.getDimensionPixelSize(
311 com.android.internal.R.dimen.preference_fragment_padding_bottom);
312
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700313 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700314 }
315
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700316 public static String getMeProfileName(Context context, boolean full) {
317 if (full) {
318 return getProfileDisplayName(context);
319 } else {
320 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700321 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700322 }
323
324 private static String getShorterNameIfPossible(Context context) {
325 final String given = getLocalProfileGivenName(context);
326 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
327 }
328
329 private static String getLocalProfileGivenName(Context context) {
330 final ContentResolver cr = context.getContentResolver();
331
332 // Find the raw contact ID for the local ME profile raw contact.
333 final long localRowProfileId;
334 final Cursor localRawProfile = cr.query(
335 Profile.CONTENT_RAW_CONTACTS_URI,
Sunny Shao660b36e2019-08-08 15:43:38 +0800336 new String[]{RawContacts._ID},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700337 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
338 RawContacts.ACCOUNT_NAME + " IS NULL",
339 null, null);
340 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700341
342 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700343 if (!localRawProfile.moveToFirst()) {
344 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700345 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700346 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700347 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700348 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700349 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700350
351 // Find the structured name for the raw contact.
352 final Cursor structuredName = cr.query(
353 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
Sunny Shao660b36e2019-08-08 15:43:38 +0800354 new String[]{CommonDataKinds.StructuredName.GIVEN_NAME,
355 CommonDataKinds.StructuredName.FAMILY_NAME},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700356 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
357 null, null);
358 if (structuredName == null) return null;
359
360 try {
361 if (!structuredName.moveToFirst()) {
362 return null;
363 }
364 String partialName = structuredName.getString(0);
365 if (TextUtils.isEmpty(partialName)) {
366 partialName = structuredName.getString(1);
367 }
368 return partialName;
369 } finally {
370 structuredName.close();
371 }
372 }
373
374 private static final String getProfileDisplayName(Context context) {
375 final ContentResolver cr = context.getContentResolver();
376 final Cursor profile = cr.query(Profile.CONTENT_URI,
Sunny Shao660b36e2019-08-08 15:43:38 +0800377 new String[]{Profile.DISPLAY_NAME}, null, null, null);
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700378 if (profile == null) return null;
379
380 try {
381 if (!profile.moveToFirst()) {
382 return null;
383 }
384 return profile.getString(0);
385 } finally {
386 profile.close();
387 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700388 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700389
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700390 public static boolean hasMultipleUsers(Context context) {
391 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
392 .getUsers().size() > 1;
393 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700394
395 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100396 * Returns the managed profile of the current user or {@code null} if none is found or a profile
397 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100398 */
399 public static UserHandle getManagedProfile(UserManager userManager) {
400 List<UserHandle> userProfiles = userManager.getUserProfiles();
Aarthi Balachanderd0f83592018-07-10 17:04:53 -0700401 for (UserHandle profile : userProfiles) {
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100402 if (profile.getIdentifier() == userManager.getUserHandle()) {
403 continue;
404 }
405 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
406 if (userInfo.isManagedProfile()) {
407 return profile;
408 }
409 }
410 return null;
411 }
412
413 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100414 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
415 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
416 */
417 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
418 // TODO: Call getManagedProfileId from here once Robolectric supports
419 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
420 // yet another implementation that loops over user profiles in this method). In the meantime
421 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
422 // used for Settings Robolectric tests).
423 final int myUserId = UserHandle.myUserId();
424 List<UserInfo> profiles = userManager.getProfiles(myUserId);
425 final int count = profiles.size();
426 for (int i = 0; i < count; i++) {
427 final UserInfo profile = profiles.get(i);
428 if (profile.isManagedProfile()
429 && profile.getUserHandle().getIdentifier() != myUserId) {
430 return profile.getUserHandle();
431 }
432 }
433 return null;
434 }
435
436 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000437 * Retrieves the id for the given user's managed profile.
438 *
439 * @return the managed profile id or UserHandle.USER_NULL if there is none.
440 */
441 public static int getManagedProfileId(UserManager um, int parentUserId) {
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700442 int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
443 for (int profileId : profileIds) {
444 if (profileId != parentUserId) {
445 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000446 }
447 }
448 return UserHandle.USER_NULL;
449 }
450
451 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100452 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000453 * <p>
454 * User would be retrieved in this order:
455 * <ul>
456 * <li> If this activity is launched from other user, return that user id.
457 * <li> If this is launched from the Settings app in same user, return the user contained as an
Sunny Shao660b36e2019-08-08 15:43:38 +0800458 * extra in the arguments or intent extras.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000459 * <li> Otherwise, return UserHandle.myUserId().
460 * </ul>
461 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100462 * Note: This is secure in the sense that it only returns a target user different to the current
463 * one if the app launching this activity is the Settings app itself, running in the same user
464 * 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 +0100465 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100466 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000467 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100468 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800469 IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100470 try {
471 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
472 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
473
474 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
475 am.getLaunchedFromUid(activityToken)));
476 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
477 // Check it's secure
478 if (isProfileOf(um, launchedFromUser)) {
479 return launchedFromUser;
480 }
481 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000482 UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100483 if (extrasUser != null && !extrasUser.equals(currentUser)) {
484 // Check it's secure
485 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
486 return extrasUser;
487 }
488 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000489 UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100490 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
491 // Check it's secure
492 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
493 return argumentsUser;
494 }
495 }
496 } catch (RemoteException e) {
497 // Should not happen
498 Log.v(TAG, "Could not talk to activity manager.", e);
499 }
500 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000501 }
502
503 /**
504 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
505 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
506 */
Sunny Shao660b36e2019-08-08 15:43:38 +0800507 private static @Nullable
508 UserHandle getUserHandleFromBundle(Bundle bundle) {
Tony Mak8f41b9b2016-11-23 11:36:18 +0000509 if (bundle == null) {
510 return null;
511 }
512 final UserHandle user = bundle.getParcelable(EXTRA_USER);
513 if (user != null) {
514 return user;
515 }
516 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
517 if (userId != -1) {
518 return UserHandle.of(userId);
519 }
520 return null;
521 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100522
Sunny Shao660b36e2019-08-08 15:43:38 +0800523 /**
524 * Returns true if the user provided is in the same profiles group as the current user.
525 */
526 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
527 if (um == null || otherUser == null) return false;
528 return (UserHandle.myUserId() == otherUser.getIdentifier())
529 || um.getUserProfiles().contains(otherUser);
530 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530531
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100532 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700533 * Return whether or not the user should have a SIM Cards option in Settings.
534 * TODO: Change back to returning true if count is greater than one after testing.
535 * TODO: See bug 16533525.
536 */
537 public static boolean showSimCardTile(Context context) {
Antony Sargent627f14b2019-03-04 16:00:59 -0800538 if (FeatureFlagPersistent.isEnabled(context, FeatureFlags.NETWORK_INTERNET_V2)) {
539 return false;
540 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700541 final TelephonyManager tm =
542 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
543
PauloftheWestdbd03822014-12-04 11:56:35 -0800544 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700545 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200546
547 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800548 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
Sunny Shao660b36e2019-08-08 15:43:38 +0800549 *
Amith Yamasani45f86232014-11-19 17:12:46 -0800550 * @param userManager Instance of UserManager
Sunny Shao660b36e2019-08-08 15:43:38 +0800551 * @param checkUser The user to check the existence of.
Amith Yamasani45f86232014-11-19 17:12:46 -0800552 * @return UserInfo of the user or null for non-existent user.
553 */
554 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
555 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
556 final int checkUserId = checkUser.getIdentifier();
557 for (UserInfo user : users) {
558 if (user.id == checkUserId) {
559 return user;
560 }
561 }
562 return null;
563 }
564
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000565 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
566 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
567 com.android.internal.R.styleable.Preference,
568 com.android.internal.R.attr.preferenceCategoryStyle, 0);
569 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
570 0);
571 a.recycle();
572 return inflater.inflate(resId, parent, false);
573 }
574
Christopher Tatea08a2252015-07-01 16:52:43 -0700575 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
576 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
577 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
578
579 ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800580 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700581 for (IntentFilterVerificationInfo ivi : iviList) {
582 for (String host : ivi.getDomains()) {
583 result.add(host);
584 }
585 }
586 }
587 if (filters != null && filters.size() > 0) {
588 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700589 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
590 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
Sunny Shao660b36e2019-08-08 15:43:38 +0800591 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700592 result.addAll(filter.getHostsList());
593 }
594 }
595 }
596 return result;
597 }
598
Sudheer Shankabc956302015-04-09 12:19:53 +0100599 /**
600 * Returns the application info of the currently installed MDM package.
601 */
602 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
603 DevicePolicyManager dpm =
604 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
605 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
606 if (mdmPackage == null) {
607 return null;
608 }
609 String mdmPackageName = mdmPackage.getPackageName();
610 try {
611 IPackageManager ipm = AppGlobals.getPackageManager();
612 ApplicationInfo mdmApplicationInfo =
613 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
614 return mdmApplicationInfo;
615 } catch (RemoteException e) {
616 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
617 + ", userId " + profileId, e);
618 return null;
619 }
620 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400621
622 public static boolean isBandwidthControlEnabled() {
623 final INetworkManagementService netManager = INetworkManagementService.Stub
624 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
625 try {
626 return netManager.isBandwidthControlEnabled();
627 } catch (RemoteException e) {
628 return false;
629 }
630 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400631
632 /**
633 * Returns an accessible SpannableString.
Sunny Shao660b36e2019-08-08 15:43:38 +0800634 *
635 * @param displayText the text to display
Julia Reynoldsce25af42015-07-08 16:56:31 -0400636 * @param accessibileText the text text-to-speech engines should read
637 */
638 public static SpannableString createAccessibleSequence(CharSequence displayText,
639 String accessibileText) {
640 SpannableString str = new SpannableString(displayText);
641 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
642 displayText.length(),
643 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
644 return str;
645 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700646
Clara Bayarrife432e82015-10-12 12:07:02 +0100647 /**
Jeff Sharkey219ec912017-12-19 14:57:39 -0700648 * Returns the user id present in the bundle with
649 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
Clara Bayarrife432e82015-10-12 12:07:02 +0100650 *
Jeff Sharkey219ec912017-12-19 14:57:39 -0700651 * @throws SecurityException if the given userId does not belong to the
Sunny Shao660b36e2019-08-08 15:43:38 +0800652 * current user group.
Clara Bayarrife432e82015-10-12 12:07:02 +0100653 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000654 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700655 return getUserIdFromBundle(context, bundle, false);
656 }
657
658 /**
659 * Returns the user id present in the bundle with
660 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
661 *
662 * @param isInternal indicating if the caller is "internal" to the system,
Sunny Shao660b36e2019-08-08 15:43:38 +0800663 * meaning we're willing to trust extras like
664 * {@link ChooseLockSettingsHelper#EXTRA_ALLOW_ANY_USER}.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700665 * @throws SecurityException if the given userId does not belong to the
Sunny Shao660b36e2019-08-08 15:43:38 +0800666 * current user group.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700667 */
668 public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
Clara Bayarrife432e82015-10-12 12:07:02 +0100669 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +0000670 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +0100671 }
Jeff Sharkey219ec912017-12-19 14:57:39 -0700672 final boolean allowAnyUser = isInternal
673 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_ALLOW_ANY_USER, false);
Clara Bayarri6934a042015-10-14 11:07:35 +0100674 int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700675 if (userId == LockPatternUtils.USER_FRP) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700676 return allowAnyUser ? userId : enforceSystemUser(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700677 } else {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700678 return allowAnyUser ? userId : enforceSameOwner(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700679 }
680 }
681
682 /**
683 * Returns the given user id if the current user is the system user.
684 *
685 * @throws SecurityException if the current user is not the system user.
686 */
687 public static int enforceSystemUser(Context context, int userId) {
688 if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
689 return userId;
690 }
691 throw new SecurityException("Given user id " + userId + " must only be used from "
692 + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100693 }
694
695 /**
696 * Returns the given user id if it belongs to the current user.
697 *
698 * @throws SecurityException if the given userId does not belong to the current user group.
699 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000700 public static int enforceSameOwner(Context context, int userId) {
Ricky Wai72500162016-06-07 16:54:25 +0100701 final UserManager um = getUserManager(context);
702 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
703 if (ArrayUtils.contains(profileIds, userId)) {
704 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +0100705 }
Ricky Wai72500162016-06-07 16:54:25 +0100706 throw new SecurityException("Given user id " + userId + " does not belong to user "
707 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100708 }
709
Benjamin Franz194300d2016-01-13 12:16:25 +0000710 /**
711 * Returns the effective credential owner of the calling user.
712 */
713 public static int getCredentialOwnerUserId(Context context) {
714 return getCredentialOwnerUserId(context, UserHandle.myUserId());
715 }
716
717 /**
718 * Returns the user id of the credential owner of the given user id.
719 */
720 public static int getCredentialOwnerUserId(Context context, int userId) {
721 UserManager um = getUserManager(context);
722 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700723 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500724
Jason Monkb37e2882016-01-11 14:27:20 -0500725 private static final StringBuilder sBuilder = new StringBuilder(50);
726 private static final java.util.Formatter sFormatter = new java.util.Formatter(
727 sBuilder, Locale.getDefault());
728
729 public static String formatDateRange(Context context, long start, long end) {
730 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
731
732 synchronized (sBuilder) {
733 sBuilder.setLength(0);
734 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
735 .toString();
736 }
737 }
Jason Monk91e2f892016-02-23 15:31:09 -0500738
Udam Saini679f7ad2016-03-25 10:47:00 -0700739 public static boolean isDeviceProvisioned(Context context) {
740 return Settings.Global.getInt(context.getContentResolver(),
741 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
742 }
Ricky Wai616342b2016-04-13 10:40:22 +0100743
Bernard Chau88d523b2016-04-14 15:08:28 +0100744 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100745 int userId) {
746 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
747 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
748 context.startActivity(intent);
749 return true;
750 }
751 return false;
752 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700753
Rubin Xu3231afe2016-08-24 10:15:07 +0100754 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
755 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800756 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100757 ActivityManager.FLAG_AND_LOCKED)) {
758 return false;
759 }
760 } catch (RemoteException e) {
761 return false;
762 }
763 if (!(new LockPatternUtils(context)).isSecure(userId)) {
764 return false;
765 }
Robin Leecccf3242017-02-10 15:32:49 +0000766 return confirmWorkProfileCredentials(context, userId);
767 }
768
Robin Leecccf3242017-02-10 15:32:49 +0000769 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100770 final KeyguardManager km = (KeyguardManager) context.getSystemService(
771 Context.KEYGUARD_SERVICE);
772 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
773 if (unlockIntent != null) {
774 context.startActivity(unlockIntent);
775 return true;
776 } else {
777 return false;
778 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100779 }
780
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700781 public static CharSequence getApplicationLabel(Context context, String packageName) {
782 try {
783 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
784 packageName,
785 PackageManager.MATCH_DISABLED_COMPONENTS
Sunny Shao660b36e2019-08-08 15:43:38 +0800786 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700787 return appInfo.loadLabel(context.getPackageManager());
788 } catch (PackageManager.NameNotFoundException e) {
789 Log.w(TAG, "Unable to find info for package: " + packageName);
790 }
791 return null;
792 }
Jason Monk75199542016-05-06 15:09:32 -0400793
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600794 public static boolean isPackageDirectBootAware(Context context, String packageName) {
795 try {
796 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
797 packageName, 0);
798 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
799 } catch (NameNotFoundException ignored) {
800 }
801 return false;
802 }
Andre Lago3e398c82016-07-25 14:12:28 +0100803
804 /**
805 * Returns a context created from the given context for the given user, or null if it fails
806 */
807 public static Context createPackageContextAsUser(Context context, int userId) {
808 try {
809 return context.createPackageContextAsUser(
810 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
811 } catch (PackageManager.NameNotFoundException e) {
812 Log.e(TAG, "Failed to create user context", e);
813 }
814 return null;
815 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600816
817 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
818 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800819 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600820 } else {
821 return null;
822 }
823 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800824
Kevin Chyn82792cc2017-07-20 00:15:44 -0700825 public static boolean hasFingerprintHardware(Context context) {
826 FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
827 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
828 }
829
Kevin Chyn4882e872018-06-25 17:58:31 -0700830 public static FaceManager getFaceManagerOrNull(Context context) {
831 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
832 return (FaceManager) context.getSystemService(Context.FACE_SERVICE);
833 } else {
834 return null;
835 }
836 }
837
838 public static boolean hasFaceHardware(Context context) {
839 FaceManager faceManager = getFaceManagerOrNull(context);
840 return faceManager != null && faceManager.isHardwareDetected();
841 }
842
Daniel Nishi31027da2017-01-19 14:03:57 -0800843 /**
844 * Launches an intent which may optionally have a user id defined.
Sunny Shao660b36e2019-08-08 15:43:38 +0800845 *
Daniel Nishi31027da2017-01-19 14:03:57 -0800846 * @param fragment Fragment to use to launch the activity.
Sunny Shao660b36e2019-08-08 15:43:38 +0800847 * @param intent Intent to launch.
Daniel Nishi31027da2017-01-19 14:03:57 -0800848 */
849 public static void launchIntent(Fragment fragment, Intent intent) {
850 try {
851 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
852
853 if (userId == -1) {
854 fragment.startActivity(intent);
855 } else {
856 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
857 }
858 } catch (ActivityNotFoundException e) {
859 Log.w(TAG, "No activity found for " + intent);
860 }
861 }
862
Christine Franksc6890ab2017-06-23 14:28:21 -0700863 public static boolean isDemoUser(Context context) {
864 return UserManager.isDeviceInDemoMode(context) && getUserManager(context).isDemoUser();
865 }
866
Justin Klaassen30257272017-08-08 21:58:05 -0700867 public static ComponentName getDeviceOwnerComponent(Context context) {
868 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
869 Context.DEVICE_POLICY_SERVICE);
870 return dpm.getDeviceOwnerComponentOnAnyUser();
Christine Franks14782222017-01-23 16:44:02 -0800871 }
Daniel Nishidfed8a22017-01-19 16:32:41 -0800872
873 /**
874 * Returns if a given user is a profile of another user.
Sunny Shao660b36e2019-08-08 15:43:38 +0800875 *
876 * @param user The user whose profiles wibe checked.
Daniel Nishidfed8a22017-01-19 16:32:41 -0800877 * @param profile The (potential) profile.
878 * @return if the profile is actually a profile
879 */
880 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
881 return user.id == profile.id ||
882 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
883 && user.profileGroupId == profile.profileGroupId);
884 }
Daniel Nishi9f60f422017-02-15 15:25:48 -0800885
886 /**
887 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
888 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
889 */
890 @Nullable
891 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
892 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
893 VolumeInfo.ID_PRIVATE_INTERNAL);
894 VolumeInfo volume = sm.findVolumeById(volumeId);
895 return isVolumeValid(volume) ? volume : null;
896 }
897
jackqdyuleiddba9662017-03-08 19:35:02 -0800898 /**
jackqdyulei00015fb2017-08-22 11:25:30 -0700899 * Return {@code true} if the supplied package is device owner or profile owner of at
900 * least one user.
Sunny Shao660b36e2019-08-08 15:43:38 +0800901 *
902 * @param userManager used to get profile owner app for each user
jackqdyulei00015fb2017-08-22 11:25:30 -0700903 * @param devicePolicyManager used to check whether it is device owner app
Sunny Shao660b36e2019-08-08 15:43:38 +0800904 * @param packageName package to check about
jackqdyulei00015fb2017-08-22 11:25:30 -0700905 */
906 public static boolean isProfileOrDeviceOwner(UserManager userManager,
Fan Zhangaab36de2018-03-30 16:58:28 -0700907 DevicePolicyManager devicePolicyManager, String packageName) {
jackqdyulei00015fb2017-08-22 11:25:30 -0700908 List<UserInfo> userInfos = userManager.getUsers();
909 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
910 return true;
911 }
912 for (int i = 0, size = userInfos.size(); i < size; i++) {
913 ComponentName cn = devicePolicyManager.getProfileOwnerAsUser(userInfos.get(i).id);
914 if (cn != null && cn.getPackageName().equals(packageName)) {
915 return true;
916 }
917 }
918 return false;
919 }
920
921 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800922 * Return the resource id to represent the install status for an app
923 */
924 @StringRes
925 public static int getInstallationStatus(ApplicationInfo info) {
926 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
927 return R.string.not_installed;
928 }
929 return info.enabled ? R.string.installed : R.string.disabled;
930 }
931
Daniel Nishi9f60f422017-02-15 15:25:48 -0800932 private static boolean isVolumeValid(VolumeInfo volume) {
933 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
934 && volume.isMountedReadable();
935 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700936
PMS2263a05602017-06-14 07:10:15 +0000937 public static void setEditTextCursorPosition(EditText editText) {
938 editText.setSelection(editText.getText().length());
939 }
Felipe Lemebd884502017-09-15 18:16:21 -0700940
941 /**
942 * Sets the preference icon with a drawable that is scaled down to to avoid crashing Settings if
943 * it's too big.
944 */
945 public static void setSafeIcon(Preference pref, Drawable icon) {
946 Drawable safeIcon = icon;
Phil Weaver5a3e02d2018-03-08 17:38:46 -0800947 if ((icon != null) && !(icon instanceof VectorDrawable)) {
Felipe Lemebd884502017-09-15 18:16:21 -0700948 safeIcon = getSafeDrawable(icon, 500, 500);
949 }
950 pref.setIcon(safeIcon);
951 }
952
953 /**
954 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
955 *
Sunny Shao660b36e2019-08-08 15:43:38 +0800956 * @param original original drawable, typically an app icon.
957 * @param maxWidth maximum width, in pixels.
Felipe Lemebd884502017-09-15 18:16:21 -0700958 * @param maxHeight maximum height, in pixels.
959 */
960 public static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
961 final int actualWidth = original.getMinimumWidth();
962 final int actualHeight = original.getMinimumHeight();
963
964 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
965 return original;
966 }
967
968 float scaleWidth = ((float) maxWidth) / actualWidth;
969 float scaleHeight = ((float) maxHeight) / actualHeight;
970 float scale = Math.min(scaleWidth, scaleHeight);
971 final int width = (int) (actualWidth * scale);
972 final int height = (int) (actualHeight * scale);
973
974 final Bitmap bitmap;
975 if (original instanceof BitmapDrawable) {
976 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
977 height, false);
978 } else {
Jason Chiuc78c54a2019-02-13 16:07:57 +0800979 bitmap = createBitmap(original, width, height);
Felipe Lemebd884502017-09-15 18:16:21 -0700980 }
981 return new BitmapDrawable(null, bitmap);
982 }
jackqdyuleifde637f2018-01-02 14:51:01 -0800983
984 /**
Jason Chiuc78c54a2019-02-13 16:07:57 +0800985 * Create an Icon pointing to a drawable.
Jason Chiu1217bbe2019-01-24 16:32:31 +0800986 */
Jason Chiuc78c54a2019-02-13 16:07:57 +0800987 public static IconCompat createIconWithDrawable(Drawable drawable) {
988 Bitmap bitmap;
Jason Chiu1217bbe2019-01-24 16:32:31 +0800989 if (drawable instanceof BitmapDrawable) {
Sunny Shao660b36e2019-08-08 15:43:38 +0800990 bitmap = ((BitmapDrawable) drawable).getBitmap();
Jason Chiuc78c54a2019-02-13 16:07:57 +0800991 } else {
992 final int width = drawable.getIntrinsicWidth();
993 final int height = drawable.getIntrinsicHeight();
994 bitmap = createBitmap(drawable,
995 width > 0 ? width : 1,
996 height > 0 ? height : 1);
Jason Chiu1217bbe2019-01-24 16:32:31 +0800997 }
Jason Chiuc78c54a2019-02-13 16:07:57 +0800998 return IconCompat.createWithBitmap(bitmap);
999 }
Jason Chiu1217bbe2019-01-24 16:32:31 +08001000
clownshen24827d32019-03-29 20:22:02 +08001001 /**
1002 * Creates a drawable with specified width and height.
1003 */
1004 public static Bitmap createBitmap(Drawable drawable, int width, int height) {
Jason Chiuc78c54a2019-02-13 16:07:57 +08001005 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001006 final Canvas canvas = new Canvas(bitmap);
1007 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1008 drawable.draw(canvas);
1009 return bitmap;
1010 }
1011
1012 /**
jackqdyuleifde637f2018-01-02 14:51:01 -08001013 * Get the {@link Drawable} that represents the app icon
1014 */
1015 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
1016 PackageManager packageManager, String packageName, int userId) {
1017 try {
Tony Mak4e292812018-03-19 15:37:21 +00001018 final ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
1019 packageName, PackageManager.GET_META_DATA, userId);
jackqdyuleifde637f2018-01-02 14:51:01 -08001020 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
1021 } catch (PackageManager.NameNotFoundException e) {
1022 return packageManager.getDefaultActivityIcon();
1023 }
1024 }
Raff Tsai2928cd42018-11-05 16:10:19 +08001025
1026 /** Returns true if the current package is installed & enabled. */
1027 public static boolean isPackageEnabled(Context context, String packageName) {
1028 try {
1029 return context.getPackageManager().getApplicationInfo(packageName, 0).enabled;
1030 } catch (Exception e) {
1031 Log.e(TAG, "Error while retrieving application info for package " + packageName, e);
1032 }
1033 return false;
1034 }
markchien1dd1d792019-01-11 16:18:20 +08001035
1036 /** Get {@link Resources} by subscription id if subscription id is valid. */
1037 public static Resources getResourcesForSubId(Context context, int subId) {
1038 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1039 return SubscriptionManager.getResourcesForSubId(context, subId);
1040 } else {
1041 return context.getResources();
1042 }
1043 }
Ng Zhi Anb97bdc32019-02-01 12:39:31 -08001044
1045 /**
1046 * Returns true if SYSTEM_ALERT_WINDOW permission is available.
1047 * Starting from Q, SYSTEM_ALERT_WINDOW is disabled on low ram phones.
1048 */
1049 public static boolean isSystemAlertWindowEnabled(Context context) {
1050 // SYSTEM_ALERT_WINDOW is disabled on on low ram devices starting from Q
1051 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
1052 return !(am.isLowRamDevice() && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q));
1053 }
tmfangaed8f362019-03-18 16:56:09 +08001054
1055 /**
1056 * Adds a shadow appear/disappear animation to action bar scroll.
1057 *
1058 * <p/>
1059 * This method must be called after {@link Fragment#onCreate(Bundle)}.
1060 */
1061 public static void setActionBarShadowAnimation(Activity activity, Lifecycle lifecycle,
1062 View scrollView) {
1063 if (activity == null) {
1064 Log.w(TAG, "No activity, cannot style actionbar.");
1065 return;
1066 }
1067 final ActionBar actionBar = activity.getActionBar();
1068 if (actionBar == null) {
1069 Log.w(TAG, "No actionbar, cannot style actionbar.");
1070 return;
1071 }
1072 actionBar.setElevation(0);
1073
1074 if (lifecycle != null && scrollView != null) {
1075 ActionBarShadowController.attachToView(activity, lifecycle, scrollView);
1076 }
1077 }
Sunny Shao660b36e2019-08-08 15:43:38 +08001078
1079 /**
1080 * Add a footer preference into preference group.
1081 *
1082 * @param group The parent {@link PreferenceGroup} of the footer preference.
1083 * @param key The key value of the footer preference.
1084 * @param title The title of the footer preference.
1085 */
1086 public static void addFooterPreference(@NonNull Context context, @NonNull PreferenceGroup group,
1087 String key, CharSequence title) {
1088 final FooterPreference footerPreference = new FooterPreference(context);
1089 footerPreference.setSelectable(false);
1090 if (!TextUtils.isEmpty(key)) {
1091 footerPreference.setKey(key);
1092 }
1093 if (!TextUtils.isEmpty(title)) {
1094 footerPreference.setTitle(title);
1095 }
1096 group.addPreference(footerPreference);
1097 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001098}