blob: 6e92640467412073d5d10405ad76b6d866be0ea8 [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;
Jason Chiu8ac1e4d2020-05-11 16:13:47 +080045import android.content.res.Configuration;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020046import android.content.res.Resources;
Jason Monkb5aa73f2015-03-31 12:59:33 -040047import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070048import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070049import android.graphics.Bitmap;
Felipe Lemebd884502017-09-15 18:16:21 -070050import android.graphics.Canvas;
jasonwshsu9b284a92021-04-20 15:19:15 +080051import android.graphics.drawable.AdaptiveIconDrawable;
Felipe Lemebd884502017-09-15 18:16:21 -070052import android.graphics.drawable.BitmapDrawable;
53import android.graphics.drawable.Drawable;
Phil Weaver5a3e02d2018-03-08 17:38:46 -080054import android.graphics.drawable.VectorDrawable;
Kevin Chyn4882e872018-06-25 17:58:31 -070055import android.hardware.face.FaceManager;
Jeff Sharkeyab508072016-10-11 14:25:22 -060056import android.hardware.fingerprint.FingerprintManager;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080057import android.net.ConnectivityManager;
Chiachang Wang003e27d2021-03-18 15:01:03 +080058import android.net.LinkAddress;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080059import android.net.LinkProperties;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070060import android.net.Network;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070061import android.net.wifi.WifiManager;
Amith Yamasania4379d62011-07-22 10:34:58 -070062import android.os.BatteryManager;
Yanting Yang96127fe2020-03-20 12:04:09 +080063import android.os.Binder;
Ng Zhi Anb97bdc32019-02-01 12:39:31 -080064import android.os.Build;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020065import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010066import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040067import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010068import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040069import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070070import android.os.UserHandle;
71import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080072import android.os.storage.StorageManager;
Daniel Nishi9f60f422017-02-15 15:25:48 -080073import android.os.storage.VolumeInfo;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070074import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070075import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070076import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070077import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070078import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070079import android.provider.ContactsContract.RawContacts;
Yi-Ling Chuang58813f72021-04-23 17:10:53 +080080import android.provider.Settings;
markchien1dd1d792019-01-11 16:18:20 +080081import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070082import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040083import android.text.Spannable;
84import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020085import android.text.TextUtils;
Jason Monkb37e2882016-01-11 14:27:20 -050086import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040087import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070088import android.util.ArraySet;
Zoey Chen3abe48e2020-10-28 22:46:48 +080089import android.util.FeatureFlagUtils;
jackqdyuleifde637f2018-01-02 14:51:01 -080090import android.util.IconDrawableFactory;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010091import android.util.Log;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000092import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070093import android.view.View;
94import android.view.ViewGroup;
PMS2263a05602017-06-14 07:10:15 +000095import android.widget.EditText;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070096import android.widget.ListView;
97import android.widget.TabWidget;
Fan Zhangcc335d92016-09-29 14:37:14 -070098
jasonwshsu9b284a92021-04-20 15:19:15 +080099import androidx.annotation.ColorInt;
Tim Pengdf467882020-06-24 13:10:01 +0800100import androidx.annotation.NonNull;
Fan Zhang23f8d592018-08-28 15:11:40 -0700101import androidx.annotation.StringRes;
Jason Chiuc78c54a2019-02-13 16:07:57 +0800102import androidx.core.graphics.drawable.IconCompat;
Tim Pengdf467882020-06-24 13:10:01 +0800103import androidx.core.graphics.drawable.RoundedBitmapDrawable;
104import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
Fan Zhang23f8d592018-08-28 15:11:40 -0700105import androidx.fragment.app.Fragment;
tmfangaed8f362019-03-18 16:56:09 +0800106import androidx.lifecycle.Lifecycle;
Fan Zhang23f8d592018-08-28 15:11:40 -0700107import androidx.preference.Preference;
108import androidx.preference.PreferenceGroup;
109
Ricky Wai616342b2016-04-13 10:40:22 +0100110import com.android.internal.app.UnlaunchableAppActivity;
Ricky Wai72500162016-06-07 16:54:25 +0100111import com.android.internal.util.ArrayUtils;
Rubin Xu3231afe2016-08-24 10:15:07 +0100112import com.android.internal.widget.LockPatternUtils;
Yi-Ling Chuang58813f72021-04-23 17:10:53 +0800113import com.android.settings.core.FeatureFlags;
Raff Tsaiafd494d2019-10-16 15:25:21 +0800114import com.android.settings.dashboard.profileselector.ProfileFragmentBridge;
Raff Tsai84327f62019-11-15 11:02:25 +0800115import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
Jeff Sharkey219ec912017-12-19 14:57:39 -0700116import com.android.settings.password.ChooseLockSettingsHelper;
tmfangaed8f362019-03-18 16:56:09 +0800117import com.android.settingslib.widget.ActionBarShadowController;
jasonwshsu9b284a92021-04-20 15:19:15 +0800118import com.android.settingslib.widget.AdaptiveIcon;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700119
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800120import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700121import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900122import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800123
Jason Monk27985e12016-01-08 14:13:05 -0500124public final class Utils extends com.android.settingslib.Utils {
125
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100126 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100127
Andras Kloczl106431e2020-05-18 14:53:07 +0100128 public static final String FILE_PROVIDER_AUTHORITY = "com.android.settings.files";
129
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800130 /**
131 * Set the preference's title to the matching activity's label.
132 */
133 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
134
Fan Zhangc3fd2892019-01-29 16:00:19 -0800135 public static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100136
Jason Monkbeb171d2015-05-21 15:24:37 -0400137 public static final String OS_PKG = "os";
138
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200139 /**
Svet Ganov864765f2019-04-05 19:00:05 -0700140 * Whether to disable the new device identifier access restrictions.
141 */
142 public static final String PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED =
143 "device_identifier_access_restrictions_disabled";
144
145 /**
Joel Galenson2118f8a2019-05-31 07:54:20 -0700146 * Whether to show the Permissions Hub.
147 */
148 public static final String PROPERTY_PERMISSIONS_HUB_ENABLED = "permissions_hub_enabled";
149
150 /**
Wei Wangedbe2cc2020-12-08 22:48:53 -0800151 * Whether to show location indicators.
152 */
153 public static final String PROPERTY_LOCATION_INDICATORS_ENABLED = "location_indicators_enabled";
154
155 /**
Wei Wanga6daf852021-01-12 10:30:25 -0800156 * Whether to show location indicator settings in developer options.
157 */
158 public static final String PROPERTY_LOCATION_INDICATOR_SETTINGS_ENABLED =
159 "location_indicator_settings_enabled";
160
Zhen Zhang48bd52e2021-03-03 13:53:34 -0800161 /** Whether or not app hibernation is enabled on the device **/
162 public static final String PROPERTY_APP_HIBERNATION_ENABLED = "app_hibernation_enabled";
163
Kevin Han4b342712021-05-25 17:45:23 -0700164 /** Whether or not app hibernation targets apps that target a pre-S SDK **/
165 public static final String PROPERTY_HIBERNATION_TARGETS_PRE_S_APPS =
166 "app_hibernation_targets_pre_s_apps";
167
Yi-Ling Chuang58813f72021-04-23 17:10:53 +0800168 /** Whether or not Settings Shared Axis transition is enabled */
169 public static final String SETTINGS_SHARED_AXIS_ENABLED = "settings_shared_axis_enabled";
170
Wei Wanga6daf852021-01-12 10:30:25 -0800171 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800172 * Finds a matching activity for a preference's intent. If a matching
173 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800174 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800175 * @param context The context.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800176 * @param parentPreferenceGroup The preference group that contains the
Sunny Shao7e866b62019-08-09 11:42:04 +0800177 * preference whose intent is being resolved.
178 * @param preferenceKey The key of the preference whose intent is being
179 * resolved.
180 * @param flags 0 or one or more of
181 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
182 * .
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800183 * @return Whether an activity was found. If false, the preference was
Sunny Shao7e866b62019-08-09 11:42:04 +0800184 * removed.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800185 */
186 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
187 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800188
Bonian Chen5e65da02019-11-08 07:40:35 +0800189 final Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800190 if (preference == null) {
191 return false;
192 }
Ying Wanga7188322010-01-04 18:45:10 -0800193
Bonian Chen5e65da02019-11-08 07:40:35 +0800194 final Intent intent = preference.getIntent();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800195 if (intent != null) {
196 // Find the activity that is in the system image
Bonian Chen5e65da02019-11-08 07:40:35 +0800197 final PackageManager pm = context.getPackageManager();
198 final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
199 final int listSize = list.size();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800200 for (int i = 0; i < listSize; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800201 final ResolveInfo resolveInfo = list.get(i);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800202 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
203 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800204
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800205 // Replace the intent with this specific activity
206 preference.setIntent(new Intent().setClassName(
207 resolveInfo.activityInfo.packageName,
208 resolveInfo.activityInfo.name));
209
210 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
211 // Set the preference title to the activity's label
212 preference.setTitle(resolveInfo.loadLabel(pm));
213 }
Ying Wanga7188322010-01-04 18:45:10 -0800214
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800215 return true;
216 }
217 }
218 }
219
220 // Did not find a matching activity, so remove the preference
221 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800222
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900223 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800224 }
Ying Wanga7188322010-01-04 18:45:10 -0800225
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200226 /**
Ying Wanga7188322010-01-04 18:45:10 -0800227 * Returns true if Monkey is running.
228 */
229 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700230 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800231 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700232
233 /**
234 * Returns whether the device is voice-capable (meaning, it is also a phone).
235 */
236 public static boolean isVoiceCapable(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800237 final TelephonyManager telephony =
Amith Yamasani60133dd2010-09-11 14:17:31 -0700238 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
239 return telephony != null && telephony.isVoiceCapable();
240 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800241
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800242 /**
243 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
244 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900245 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800246 */
247 public static String getWifiIpAddresses(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800248 final WifiManager wifiManager = context.getSystemService(WifiManager.class);
249 final Network currentNetwork = wifiManager.getCurrentNetwork();
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700250 if (currentNetwork != null) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800251 final ConnectivityManager cm = (ConnectivityManager)
Sunny Shao7e866b62019-08-09 11:42:04 +0800252 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800253 final LinkProperties prop = cm.getLinkProperties(currentNetwork);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700254 return formatIpAddresses(prop);
255 }
256 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700257 }
258
Amith Yamasani6822b742011-10-17 16:41:00 -0700259 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800260 if (prop == null) return null;
Chiachang Wang003e27d2021-03-18 15:01:03 +0800261 final Iterator<LinkAddress> iter = prop.getAllLinkAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800262 // If there are no entries, return null
263 if (!iter.hasNext()) return null;
264 // Concatenate all available addresses, comma separated
265 String addresses = "";
266 while (iter.hasNext()) {
Chiachang Wang003e27d2021-03-18 15:01:03 +0800267 addresses += iter.next().getAddress().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900268 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800269 }
270 return addresses;
271 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900272
273 public static Locale createLocaleFromString(String localeStr) {
274 // TODO: is there a better way to actually construct a locale that will match?
275 // The main problem is, on top of Java specs, locale.toString() and
276 // new Locale(locale.toString()).toString() do not return equal() strings in
277 // many cases, because the constructor takes the only string as the language
278 // code. So : new Locale("en", "US").toString() => "en_US"
279 // And : new Locale("en_US").toString() => "en_us"
Sunny Shao7e866b62019-08-09 11:42:04 +0800280 if (null == localeStr)
Jean Chalard71ad1f42011-05-12 15:06:16 +0900281 return Locale.getDefault();
Bonian Chen5e65da02019-11-08 07:40:35 +0800282 final String[] brokenDownLocale = localeStr.split("_", 3);
Jean Chalard71ad1f42011-05-12 15:06:16 +0900283 // split may not return a 0-length array.
284 if (1 == brokenDownLocale.length) {
285 return new Locale(brokenDownLocale[0]);
286 } else if (2 == brokenDownLocale.length) {
287 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
288 } else {
289 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
290 }
291 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700292
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900293 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
294 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
295 }
296
Mill Chenad99e2e2020-10-21 16:32:56 +0800297 /**
298 * Return true if battery is present.
299 */
300 public static boolean isBatteryPresent(Context context) {
301 Intent batteryBroadcast = context.registerReceiver(null /* receiver */,
302 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
303 return isBatteryPresent(batteryBroadcast);
304 }
305
Amith Yamasania4379d62011-07-22 10:34:58 -0700306 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700307 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700308 }
309
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700310 /**
311 * Prepare a custom preferences layout, moving padding to {@link ListView}
312 * when outside scrollbars are requested. Usually used to display
313 * {@link ListView} and {@link TabWidget} with correct padding.
314 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700315 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800316 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700317 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700318 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700319 final Resources res = list.getResources();
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700320 final int paddingBottom = res.getDimensionPixelSize(
321 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700322
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700323 if (parent instanceof PreferenceFrameLayout) {
324 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700325 }
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800326 list.setPaddingRelative(0 /* start */, 0 /* top */, 0 /* end */, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700327 }
328 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700329
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700330 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700331 final Resources res = view.getResources();
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700332
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800333 final int paddingStart = additive ? view.getPaddingStart() : 0;
334 final int paddingEnd = additive ? view.getPaddingEnd() : 0;
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700335 final int paddingBottom = res.getDimensionPixelSize(
336 com.android.internal.R.dimen.preference_fragment_padding_bottom);
337
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700338 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700339 }
340
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700341 public static String getMeProfileName(Context context, boolean full) {
342 if (full) {
343 return getProfileDisplayName(context);
344 } else {
345 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700346 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700347 }
348
349 private static String getShorterNameIfPossible(Context context) {
350 final String given = getLocalProfileGivenName(context);
351 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
352 }
353
354 private static String getLocalProfileGivenName(Context context) {
355 final ContentResolver cr = context.getContentResolver();
356
357 // Find the raw contact ID for the local ME profile raw contact.
358 final long localRowProfileId;
359 final Cursor localRawProfile = cr.query(
360 Profile.CONTENT_RAW_CONTACTS_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800361 new String[] {RawContacts._ID},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700362 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
363 RawContacts.ACCOUNT_NAME + " IS NULL",
364 null, null);
365 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700366
367 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700368 if (!localRawProfile.moveToFirst()) {
369 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700370 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700371 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700372 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700373 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700374 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700375
376 // Find the structured name for the raw contact.
377 final Cursor structuredName = cr.query(
378 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
Sunny Shao7e866b62019-08-09 11:42:04 +0800379 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
380 CommonDataKinds.StructuredName.FAMILY_NAME},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700381 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
382 null, null);
383 if (structuredName == null) return null;
384
385 try {
386 if (!structuredName.moveToFirst()) {
387 return null;
388 }
389 String partialName = structuredName.getString(0);
390 if (TextUtils.isEmpty(partialName)) {
391 partialName = structuredName.getString(1);
392 }
393 return partialName;
394 } finally {
395 structuredName.close();
396 }
397 }
398
399 private static final String getProfileDisplayName(Context context) {
400 final ContentResolver cr = context.getContentResolver();
401 final Cursor profile = cr.query(Profile.CONTENT_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800402 new String[] {Profile.DISPLAY_NAME}, null, null, null);
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700403 if (profile == null) return null;
404
405 try {
406 if (!profile.moveToFirst()) {
407 return null;
408 }
409 return profile.getString(0);
410 } finally {
411 profile.close();
412 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700413 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700414
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700415 public static boolean hasMultipleUsers(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800416 return context.getSystemService(UserManager.class)
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700417 .getUsers().size() > 1;
418 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700419
420 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100421 * Returns the managed profile of the current user or {@code null} if none is found or a profile
422 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100423 */
424 public static UserHandle getManagedProfile(UserManager userManager) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800425 final List<UserHandle> userProfiles = userManager.getUserProfiles();
Aarthi Balachanderd0f83592018-07-10 17:04:53 -0700426 for (UserHandle profile : userProfiles) {
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100427 if (profile.getIdentifier() == userManager.getUserHandle()) {
428 continue;
429 }
430 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
431 if (userInfo.isManagedProfile()) {
432 return profile;
433 }
434 }
435 return null;
436 }
437
438 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100439 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
440 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
441 */
442 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
443 // TODO: Call getManagedProfileId from here once Robolectric supports
444 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
445 // yet another implementation that loops over user profiles in this method). In the meantime
446 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
447 // used for Settings Robolectric tests).
448 final int myUserId = UserHandle.myUserId();
Bonian Chen5e65da02019-11-08 07:40:35 +0800449 final List<UserInfo> profiles = userManager.getProfiles(myUserId);
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100450 final int count = profiles.size();
451 for (int i = 0; i < count; i++) {
452 final UserInfo profile = profiles.get(i);
453 if (profile.isManagedProfile()
454 && profile.getUserHandle().getIdentifier() != myUserId) {
455 return profile.getUserHandle();
456 }
457 }
458 return null;
459 }
460
461 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000462 * Retrieves the id for the given user's managed profile.
463 *
464 * @return the managed profile id or UserHandle.USER_NULL if there is none.
465 */
466 public static int getManagedProfileId(UserManager um, int parentUserId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800467 final int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700468 for (int profileId : profileIds) {
469 if (profileId != parentUserId) {
470 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000471 }
472 }
473 return UserHandle.USER_NULL;
474 }
475
Arc Wang54306822021-04-29 18:54:10 +0800476 /** Returns user ID of current user, throws IllegalStateException if it's not available. */
477 public static int getCurrentUserId(UserManager userManager, boolean isWorkProfile)
478 throws IllegalStateException {
479 if (isWorkProfile) {
480 final UserHandle managedUserHandle = getManagedProfile(userManager);
481 if (managedUserHandle == null) {
482 throw new IllegalStateException("Work profile user ID is not available.");
483 }
484 return managedUserHandle.getIdentifier();
485 }
486 return UserHandle.myUserId();
487 }
488
Clara Bayarri462cce12016-02-18 12:09:21 +0000489 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100490 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000491 * <p>
492 * User would be retrieved in this order:
493 * <ul>
494 * <li> If this activity is launched from other user, return that user id.
495 * <li> If this is launched from the Settings app in same user, return the user contained as an
Sunny Shao7e866b62019-08-09 11:42:04 +0800496 * extra in the arguments or intent extras.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000497 * <li> Otherwise, return UserHandle.myUserId().
498 * </ul>
499 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100500 * Note: This is secure in the sense that it only returns a target user different to the current
501 * one if the app launching this activity is the Settings app itself, running in the same user
502 * 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 +0100503 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100504 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000505 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800506 final UserHandle currentUser = new UserHandle(UserHandle.myUserId());
507 final IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100508 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800509 final String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
510 final boolean launchedFromSettingsApp =
511 SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100512
Bonian Chen5e65da02019-11-08 07:40:35 +0800513 final UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100514 am.getLaunchedFromUid(activityToken)));
515 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
516 // Check it's secure
517 if (isProfileOf(um, launchedFromUser)) {
518 return launchedFromUser;
519 }
520 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800521 final UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100522 if (extrasUser != null && !extrasUser.equals(currentUser)) {
523 // Check it's secure
524 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
525 return extrasUser;
526 }
527 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800528 final UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100529 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
530 // Check it's secure
531 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
532 return argumentsUser;
533 }
534 }
535 } catch (RemoteException e) {
536 // Should not happen
537 Log.v(TAG, "Could not talk to activity manager.", e);
538 }
539 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000540 }
541
542 /**
543 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
544 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
545 */
Sunny Shao7e866b62019-08-09 11:42:04 +0800546 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
Tony Mak8f41b9b2016-11-23 11:36:18 +0000547 if (bundle == null) {
548 return null;
549 }
550 final UserHandle user = bundle.getParcelable(EXTRA_USER);
551 if (user != null) {
552 return user;
553 }
554 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
555 if (userId != -1) {
556 return UserHandle.of(userId);
557 }
558 return null;
559 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100560
Sunny Shao7e866b62019-08-09 11:42:04 +0800561 /**
562 * Returns true if the user provided is in the same profiles group as the current user.
563 */
564 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
565 if (um == null || otherUser == null) return false;
566 return (UserHandle.myUserId() == otherUser.getIdentifier())
567 || um.getUserProfiles().contains(otherUser);
568 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530569
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100570 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800571 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
572 * @param userManager Instance of UserManager
Sunny Shao7e866b62019-08-09 11:42:04 +0800573 * @param checkUser The user to check the existence of.
Amith Yamasani45f86232014-11-19 17:12:46 -0800574 * @return UserInfo of the user or null for non-existent user.
575 */
576 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
Colin Cross38fa1852020-08-27 04:12:26 +0000577 final List<UserInfo> users = userManager.getAliveUsers();
Amith Yamasani45f86232014-11-19 17:12:46 -0800578 final int checkUserId = checkUser.getIdentifier();
579 for (UserInfo user : users) {
580 if (user.id == checkUserId) {
581 return user;
582 }
583 }
584 return null;
585 }
586
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000587 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
588 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
589 com.android.internal.R.styleable.Preference,
590 com.android.internal.R.attr.preferenceCategoryStyle, 0);
591 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
592 0);
593 a.recycle();
594 return inflater.inflate(resId, parent, false);
595 }
596
Christopher Tatea08a2252015-07-01 16:52:43 -0700597 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800598 final List<IntentFilterVerificationInfo> iviList =
599 pm.getIntentFilterVerifications(packageName);
600 final List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
Christopher Tatea08a2252015-07-01 16:52:43 -0700601
Bonian Chen5e65da02019-11-08 07:40:35 +0800602 final ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800603 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700604 for (IntentFilterVerificationInfo ivi : iviList) {
605 for (String host : ivi.getDomains()) {
606 result.add(host);
607 }
608 }
609 }
610 if (filters != null && filters.size() > 0) {
611 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700612 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
613 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
Sunny Shao7e866b62019-08-09 11:42:04 +0800614 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700615 result.addAll(filter.getHostsList());
616 }
617 }
618 }
619 return result;
620 }
621
Sudheer Shankabc956302015-04-09 12:19:53 +0100622 /**
623 * Returns the application info of the currently installed MDM package.
624 */
625 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800626 final DevicePolicyManager dpm =
Sudheer Shankabc956302015-04-09 12:19:53 +0100627 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800628 final ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
Sudheer Shankabc956302015-04-09 12:19:53 +0100629 if (mdmPackage == null) {
630 return null;
631 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800632 final String mdmPackageName = mdmPackage.getPackageName();
Sudheer Shankabc956302015-04-09 12:19:53 +0100633 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800634 final IPackageManager ipm = AppGlobals.getPackageManager();
635 final ApplicationInfo mdmApplicationInfo =
Sudheer Shankabc956302015-04-09 12:19:53 +0100636 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
637 return mdmApplicationInfo;
638 } catch (RemoteException e) {
639 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
640 + ", userId " + profileId, e);
641 return null;
642 }
643 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400644
645 public static boolean isBandwidthControlEnabled() {
646 final INetworkManagementService netManager = INetworkManagementService.Stub
647 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
648 try {
649 return netManager.isBandwidthControlEnabled();
650 } catch (RemoteException e) {
651 return false;
652 }
653 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400654
655 /**
656 * Returns an accessible SpannableString.
Sunny Shao7e866b62019-08-09 11:42:04 +0800657 * @param displayText the text to display
Julia Reynoldsce25af42015-07-08 16:56:31 -0400658 * @param accessibileText the text text-to-speech engines should read
659 */
660 public static SpannableString createAccessibleSequence(CharSequence displayText,
661 String accessibileText) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800662 final SpannableString str = new SpannableString(displayText);
Julia Reynoldsce25af42015-07-08 16:56:31 -0400663 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
664 displayText.length(),
665 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
666 return str;
667 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700668
Clara Bayarrife432e82015-10-12 12:07:02 +0100669 /**
Jeff Sharkey219ec912017-12-19 14:57:39 -0700670 * Returns the user id present in the bundle with
671 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
Clara Bayarrife432e82015-10-12 12:07:02 +0100672 *
Jeff Sharkey219ec912017-12-19 14:57:39 -0700673 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800674 * current user group.
Clara Bayarrife432e82015-10-12 12:07:02 +0100675 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000676 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700677 return getUserIdFromBundle(context, bundle, false);
678 }
679
680 /**
681 * Returns the user id present in the bundle with
682 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
683 *
684 * @param isInternal indicating if the caller is "internal" to the system,
Sunny Shao7e866b62019-08-09 11:42:04 +0800685 * meaning we're willing to trust extras like
Kevin Chynb13bc502020-07-20 23:35:21 -0700686 * {@link ChooseLockSettingsHelper#EXTRA_KEY_ALLOW_ANY_USER}.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700687 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800688 * current user group.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700689 */
690 public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
Clara Bayarrife432e82015-10-12 12:07:02 +0100691 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +0000692 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +0100693 }
Jeff Sharkey219ec912017-12-19 14:57:39 -0700694 final boolean allowAnyUser = isInternal
Kevin Chynb13bc502020-07-20 23:35:21 -0700695 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_KEY_ALLOW_ANY_USER, false);
Bonian Chen5e65da02019-11-08 07:40:35 +0800696 final int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700697 if (userId == LockPatternUtils.USER_FRP) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700698 return allowAnyUser ? userId : enforceSystemUser(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700699 } else {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700700 return allowAnyUser ? userId : enforceSameOwner(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700701 }
702 }
703
704 /**
705 * Returns the given user id if the current user is the system user.
706 *
707 * @throws SecurityException if the current user is not the system user.
708 */
709 public static int enforceSystemUser(Context context, int userId) {
710 if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
711 return userId;
712 }
713 throw new SecurityException("Given user id " + userId + " must only be used from "
714 + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100715 }
716
717 /**
718 * Returns the given user id if it belongs to the current user.
719 *
720 * @throws SecurityException if the given userId does not belong to the current user group.
721 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000722 public static int enforceSameOwner(Context context, int userId) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800723 final UserManager um = context.getSystemService(UserManager.class);
Ricky Wai72500162016-06-07 16:54:25 +0100724 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
725 if (ArrayUtils.contains(profileIds, userId)) {
726 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +0100727 }
Ricky Wai72500162016-06-07 16:54:25 +0100728 throw new SecurityException("Given user id " + userId + " does not belong to user "
729 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100730 }
731
Benjamin Franz194300d2016-01-13 12:16:25 +0000732 /**
733 * Returns the effective credential owner of the calling user.
734 */
735 public static int getCredentialOwnerUserId(Context context) {
736 return getCredentialOwnerUserId(context, UserHandle.myUserId());
737 }
738
739 /**
740 * Returns the user id of the credential owner of the given user id.
741 */
742 public static int getCredentialOwnerUserId(Context context, int userId) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800743 final UserManager um = context.getSystemService(UserManager.class);
Benjamin Franz194300d2016-01-13 12:16:25 +0000744 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700745 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500746
Alex Johnston403c3302020-01-07 15:40:05 +0000747 /**
748 * Returns the credential type of the given user id.
749 */
750 public static @LockPatternUtils.CredentialType int getCredentialType(Context context,
751 int userId) {
752 final LockPatternUtils lpu = new LockPatternUtils(context);
753 return lpu.getCredentialTypeForUser(userId);
754 }
755
Jason Monkb37e2882016-01-11 14:27:20 -0500756 private static final StringBuilder sBuilder = new StringBuilder(50);
757 private static final java.util.Formatter sFormatter = new java.util.Formatter(
758 sBuilder, Locale.getDefault());
759
760 public static String formatDateRange(Context context, long start, long end) {
761 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
762
763 synchronized (sBuilder) {
764 sBuilder.setLength(0);
765 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
766 .toString();
767 }
768 }
Jason Monk91e2f892016-02-23 15:31:09 -0500769
Bernard Chau88d523b2016-04-14 15:08:28 +0100770 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100771 int userId) {
772 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
773 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
774 context.startActivity(intent);
775 return true;
776 }
777 return false;
778 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700779
Rubin Xu3231afe2016-08-24 10:15:07 +0100780 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
781 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800782 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100783 ActivityManager.FLAG_AND_LOCKED)) {
784 return false;
785 }
786 } catch (RemoteException e) {
787 return false;
788 }
789 if (!(new LockPatternUtils(context)).isSecure(userId)) {
790 return false;
791 }
Robin Leecccf3242017-02-10 15:32:49 +0000792 return confirmWorkProfileCredentials(context, userId);
793 }
794
Robin Leecccf3242017-02-10 15:32:49 +0000795 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100796 final KeyguardManager km = (KeyguardManager) context.getSystemService(
797 Context.KEYGUARD_SERVICE);
798 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
799 if (unlockIntent != null) {
800 context.startActivity(unlockIntent);
801 return true;
802 } else {
803 return false;
804 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100805 }
806
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700807 public static CharSequence getApplicationLabel(Context context, String packageName) {
808 try {
809 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
810 packageName,
811 PackageManager.MATCH_DISABLED_COMPONENTS
Sunny Shao7e866b62019-08-09 11:42:04 +0800812 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700813 return appInfo.loadLabel(context.getPackageManager());
814 } catch (PackageManager.NameNotFoundException e) {
Raff Tsai376ce872020-01-06 00:42:35 +0800815 Log.e(TAG, "Unable to find info for package: " + packageName);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700816 }
817 return null;
818 }
Jason Monk75199542016-05-06 15:09:32 -0400819
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600820 public static boolean isPackageDirectBootAware(Context context, String packageName) {
821 try {
822 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
823 packageName, 0);
824 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
825 } catch (NameNotFoundException ignored) {
826 }
827 return false;
828 }
Andre Lago3e398c82016-07-25 14:12:28 +0100829
830 /**
831 * Returns a context created from the given context for the given user, or null if it fails
832 */
833 public static Context createPackageContextAsUser(Context context, int userId) {
834 try {
835 return context.createPackageContextAsUser(
836 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
837 } catch (PackageManager.NameNotFoundException e) {
838 Log.e(TAG, "Failed to create user context", e);
839 }
840 return null;
841 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600842
843 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
844 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800845 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600846 } else {
847 return null;
848 }
849 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800850
Kevin Chyn82792cc2017-07-20 00:15:44 -0700851 public static boolean hasFingerprintHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800852 final FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
Kevin Chyn82792cc2017-07-20 00:15:44 -0700853 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
854 }
855
Kevin Chyn4882e872018-06-25 17:58:31 -0700856 public static FaceManager getFaceManagerOrNull(Context context) {
857 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
858 return (FaceManager) context.getSystemService(Context.FACE_SERVICE);
859 } else {
860 return null;
861 }
862 }
863
864 public static boolean hasFaceHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800865 final FaceManager faceManager = getFaceManagerOrNull(context);
Kevin Chyn4882e872018-06-25 17:58:31 -0700866 return faceManager != null && faceManager.isHardwareDetected();
867 }
868
Daniel Nishi31027da2017-01-19 14:03:57 -0800869 /**
Mill Chen7edebee2021-04-09 23:14:27 +0800870 * Return true if the device supports multiple biometrics authentications.
871 */
872 public static boolean isMultipleBiometricsSupported(Context context) {
873 return hasFingerprintHardware(context) && hasFaceHardware(context);
874 }
875
876 /**
Daniel Nishi31027da2017-01-19 14:03:57 -0800877 * Launches an intent which may optionally have a user id defined.
878 * @param fragment Fragment to use to launch the activity.
Sunny Shao7e866b62019-08-09 11:42:04 +0800879 * @param intent Intent to launch.
Daniel Nishi31027da2017-01-19 14:03:57 -0800880 */
881 public static void launchIntent(Fragment fragment, Intent intent) {
882 try {
883 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
884
885 if (userId == -1) {
886 fragment.startActivity(intent);
887 } else {
888 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
889 }
890 } catch (ActivityNotFoundException e) {
891 Log.w(TAG, "No activity found for " + intent);
892 }
893 }
894
Christine Franksc6890ab2017-06-23 14:28:21 -0700895 public static boolean isDemoUser(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800896 return UserManager.isDeviceInDemoMode(context)
897 && context.getSystemService(UserManager.class).isDemoUser();
Christine Franksc6890ab2017-06-23 14:28:21 -0700898 }
899
Justin Klaassen30257272017-08-08 21:58:05 -0700900 public static ComponentName getDeviceOwnerComponent(Context context) {
901 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
902 Context.DEVICE_POLICY_SERVICE);
903 return dpm.getDeviceOwnerComponentOnAnyUser();
Christine Franks14782222017-01-23 16:44:02 -0800904 }
Daniel Nishidfed8a22017-01-19 16:32:41 -0800905
906 /**
907 * Returns if a given user is a profile of another user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800908 * @param user The user whose profiles wibe checked.
Daniel Nishidfed8a22017-01-19 16:32:41 -0800909 * @param profile The (potential) profile.
910 * @return if the profile is actually a profile
911 */
912 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
913 return user.id == profile.id ||
914 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
915 && user.profileGroupId == profile.profileGroupId);
916 }
Daniel Nishi9f60f422017-02-15 15:25:48 -0800917
918 /**
919 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
920 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
921 */
922 @Nullable
923 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
924 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
925 VolumeInfo.ID_PRIVATE_INTERNAL);
Bonian Chen5e65da02019-11-08 07:40:35 +0800926 final VolumeInfo volume = sm.findVolumeById(volumeId);
Daniel Nishi9f60f422017-02-15 15:25:48 -0800927 return isVolumeValid(volume) ? volume : null;
928 }
929
jackqdyuleiddba9662017-03-08 19:35:02 -0800930 /**
jackqdyulei00015fb2017-08-22 11:25:30 -0700931 * Return {@code true} if the supplied package is device owner or profile owner of at
932 * least one user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800933 * @param userManager used to get profile owner app for each user
jackqdyulei00015fb2017-08-22 11:25:30 -0700934 * @param devicePolicyManager used to check whether it is device owner app
Sunny Shao7e866b62019-08-09 11:42:04 +0800935 * @param packageName package to check about
jackqdyulei00015fb2017-08-22 11:25:30 -0700936 */
937 public static boolean isProfileOrDeviceOwner(UserManager userManager,
Fan Zhangaab36de2018-03-30 16:58:28 -0700938 DevicePolicyManager devicePolicyManager, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800939 final List<UserInfo> userInfos = userManager.getUsers();
jackqdyulei00015fb2017-08-22 11:25:30 -0700940 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
941 return true;
942 }
943 for (int i = 0, size = userInfos.size(); i < size; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800944 final ComponentName cn = devicePolicyManager
945 .getProfileOwnerAsUser(userInfos.get(i).id);
jackqdyulei00015fb2017-08-22 11:25:30 -0700946 if (cn != null && cn.getPackageName().equals(packageName)) {
947 return true;
948 }
949 }
950 return false;
951 }
952
953 /**
Alex Johnston341f9952020-02-26 15:54:11 +0000954 * Return {@code true} if the supplied package is the device owner or profile owner of a
955 * given user.
956 *
957 * @param devicePolicyManager used to check whether it is device owner and profile owner app
958 * @param packageName package to check about
959 * @param userId the if of the relevant user
960 */
961 public static boolean isProfileOrDeviceOwner(DevicePolicyManager devicePolicyManager,
962 String packageName, int userId) {
963 if ((devicePolicyManager.getDeviceOwnerUserId() == userId)
964 && devicePolicyManager.isDeviceOwnerApp(packageName)) {
965 return true;
966 }
967 final ComponentName cn = devicePolicyManager.getProfileOwnerAsUser(userId);
968 if (cn != null && cn.getPackageName().equals(packageName)) {
969 return true;
970 }
971 return false;
972 }
973
974 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800975 * Return the resource id to represent the install status for an app
976 */
977 @StringRes
978 public static int getInstallationStatus(ApplicationInfo info) {
979 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
980 return R.string.not_installed;
981 }
982 return info.enabled ? R.string.installed : R.string.disabled;
983 }
984
Daniel Nishi9f60f422017-02-15 15:25:48 -0800985 private static boolean isVolumeValid(VolumeInfo volume) {
986 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
987 && volume.isMountedReadable();
988 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700989
PMS2263a05602017-06-14 07:10:15 +0000990 public static void setEditTextCursorPosition(EditText editText) {
991 editText.setSelection(editText.getText().length());
992 }
Felipe Lemebd884502017-09-15 18:16:21 -0700993
994 /**
jasonwshsu9b284a92021-04-20 15:19:15 +0800995 * Gets the adaptive icon with a drawable that wrapped with an adaptive background using {@code
996 * backgroundColor} if it is not a {@link AdaptiveIconDrawable}
997 *
998 * If the given {@code icon} is too big, it will be auto scaled down to to avoid crashing
999 * Settings.
Felipe Lemebd884502017-09-15 18:16:21 -07001000 */
jasonwshsu9b284a92021-04-20 15:19:15 +08001001 public static Drawable getAdaptiveIcon(Context context, Drawable icon,
1002 @ColorInt int backgroundColor) {
1003 Drawable adaptiveIcon = getSafeIcon(icon);
1004
1005 if (!(adaptiveIcon instanceof AdaptiveIconDrawable)) {
1006 adaptiveIcon = new AdaptiveIcon(context, adaptiveIcon);
1007 ((AdaptiveIcon) adaptiveIcon).setBackgroundColor(backgroundColor);
1008 }
1009
1010 return adaptiveIcon;
1011 }
1012
1013 /**
1014 * Gets the icon with a drawable that is scaled down to to avoid crashing Settings if it's too
1015 * big and not a {@link VectorDrawable}.
1016 */
1017 public static Drawable getSafeIcon(Drawable icon) {
Felipe Lemebd884502017-09-15 18:16:21 -07001018 Drawable safeIcon = icon;
jasonwshsu9b284a92021-04-20 15:19:15 +08001019
Phil Weaver5a3e02d2018-03-08 17:38:46 -08001020 if ((icon != null) && !(icon instanceof VectorDrawable)) {
Felipe Lemebd884502017-09-15 18:16:21 -07001021 safeIcon = getSafeDrawable(icon, 500, 500);
1022 }
jasonwshsu9b284a92021-04-20 15:19:15 +08001023
1024 return safeIcon;
Felipe Lemebd884502017-09-15 18:16:21 -07001025 }
1026
1027 /**
1028 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
1029 *
Sunny Shao7e866b62019-08-09 11:42:04 +08001030 * @param original original drawable, typically an app icon.
1031 * @param maxWidth maximum width, in pixels.
Felipe Lemebd884502017-09-15 18:16:21 -07001032 * @param maxHeight maximum height, in pixels.
1033 */
jasonwshsu9b284a92021-04-20 15:19:15 +08001034 private static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
Felipe Lemebd884502017-09-15 18:16:21 -07001035 final int actualWidth = original.getMinimumWidth();
1036 final int actualHeight = original.getMinimumHeight();
1037
1038 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
1039 return original;
1040 }
1041
Bonian Chen5e65da02019-11-08 07:40:35 +08001042 final float scaleWidth = ((float) maxWidth) / actualWidth;
1043 final float scaleHeight = ((float) maxHeight) / actualHeight;
1044 final float scale = Math.min(scaleWidth, scaleHeight);
Felipe Lemebd884502017-09-15 18:16:21 -07001045 final int width = (int) (actualWidth * scale);
1046 final int height = (int) (actualHeight * scale);
1047
1048 final Bitmap bitmap;
1049 if (original instanceof BitmapDrawable) {
1050 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
1051 height, false);
1052 } else {
Jason Chiuc78c54a2019-02-13 16:07:57 +08001053 bitmap = createBitmap(original, width, height);
Felipe Lemebd884502017-09-15 18:16:21 -07001054 }
1055 return new BitmapDrawable(null, bitmap);
1056 }
jackqdyuleifde637f2018-01-02 14:51:01 -08001057
1058 /**
Jason Chiuc78c54a2019-02-13 16:07:57 +08001059 * Create an Icon pointing to a drawable.
Jason Chiu1217bbe2019-01-24 16:32:31 +08001060 */
Jason Chiuc78c54a2019-02-13 16:07:57 +08001061 public static IconCompat createIconWithDrawable(Drawable drawable) {
1062 Bitmap bitmap;
Jason Chiu1217bbe2019-01-24 16:32:31 +08001063 if (drawable instanceof BitmapDrawable) {
Sunny Shao7e866b62019-08-09 11:42:04 +08001064 bitmap = ((BitmapDrawable)drawable).getBitmap();
Jason Chiuc78c54a2019-02-13 16:07:57 +08001065 } else {
1066 final int width = drawable.getIntrinsicWidth();
1067 final int height = drawable.getIntrinsicHeight();
1068 bitmap = createBitmap(drawable,
1069 width > 0 ? width : 1,
1070 height > 0 ? height : 1);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001071 }
Jason Chiuc78c54a2019-02-13 16:07:57 +08001072 return IconCompat.createWithBitmap(bitmap);
1073 }
Jason Chiu1217bbe2019-01-24 16:32:31 +08001074
clownshen24827d32019-03-29 20:22:02 +08001075 /**
1076 * Creates a drawable with specified width and height.
1077 */
1078 public static Bitmap createBitmap(Drawable drawable, int width, int height) {
Jason Chiuc78c54a2019-02-13 16:07:57 +08001079 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001080 final Canvas canvas = new Canvas(bitmap);
1081 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1082 drawable.draw(canvas);
1083 return bitmap;
1084 }
1085
1086 /**
jackqdyuleifde637f2018-01-02 14:51:01 -08001087 * Get the {@link Drawable} that represents the app icon
1088 */
1089 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
1090 PackageManager packageManager, String packageName, int userId) {
1091 try {
Tony Mak4e292812018-03-19 15:37:21 +00001092 final ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
1093 packageName, PackageManager.GET_META_DATA, userId);
jackqdyuleifde637f2018-01-02 14:51:01 -08001094 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
1095 } catch (PackageManager.NameNotFoundException e) {
1096 return packageManager.getDefaultActivityIcon();
1097 }
1098 }
Raff Tsai2928cd42018-11-05 16:10:19 +08001099
1100 /** Returns true if the current package is installed & enabled. */
1101 public static boolean isPackageEnabled(Context context, String packageName) {
1102 try {
1103 return context.getPackageManager().getApplicationInfo(packageName, 0).enabled;
1104 } catch (Exception e) {
1105 Log.e(TAG, "Error while retrieving application info for package " + packageName, e);
1106 }
1107 return false;
1108 }
markchien1dd1d792019-01-11 16:18:20 +08001109
1110 /** Get {@link Resources} by subscription id if subscription id is valid. */
1111 public static Resources getResourcesForSubId(Context context, int subId) {
1112 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1113 return SubscriptionManager.getResourcesForSubId(context, subId);
1114 } else {
1115 return context.getResources();
1116 }
1117 }
Ng Zhi Anb97bdc32019-02-01 12:39:31 -08001118
1119 /**
1120 * Returns true if SYSTEM_ALERT_WINDOW permission is available.
1121 * Starting from Q, SYSTEM_ALERT_WINDOW is disabled on low ram phones.
1122 */
1123 public static boolean isSystemAlertWindowEnabled(Context context) {
1124 // SYSTEM_ALERT_WINDOW is disabled on on low ram devices starting from Q
1125 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
1126 return !(am.isLowRamDevice() && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q));
1127 }
tmfangaed8f362019-03-18 16:56:09 +08001128
1129 /**
1130 * Adds a shadow appear/disappear animation to action bar scroll.
1131 *
1132 * <p/>
1133 * This method must be called after {@link Fragment#onCreate(Bundle)}.
1134 */
1135 public static void setActionBarShadowAnimation(Activity activity, Lifecycle lifecycle,
1136 View scrollView) {
1137 if (activity == null) {
1138 Log.w(TAG, "No activity, cannot style actionbar.");
1139 return;
1140 }
1141 final ActionBar actionBar = activity.getActionBar();
1142 if (actionBar == null) {
1143 Log.w(TAG, "No actionbar, cannot style actionbar.");
1144 return;
1145 }
1146 actionBar.setElevation(0);
1147
1148 if (lifecycle != null && scrollView != null) {
1149 ActionBarShadowController.attachToView(activity, lifecycle, scrollView);
1150 }
1151 }
Raff Tsaiafd494d2019-10-16 15:25:21 +08001152
1153 /**
1154 * Return correct target fragment based on argument
1155 *
1156 * @param activity the activity target fragment will be launched.
1157 * @param fragmentName initial target fragment name.
1158 * @param args fragment launch arguments.
1159 */
1160 public static Fragment getTargetFragment(Activity activity, String fragmentName, Bundle args) {
1161 Fragment f = null;
Raff Tsai84327f62019-11-15 11:02:25 +08001162 final boolean isPersonal = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001163 == ProfileSelectFragment.ProfileType.PERSONAL : false;
Raff Tsai84327f62019-11-15 11:02:25 +08001164 final boolean isWork = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001165 == ProfileSelectFragment.ProfileType.WORK : false;
Raff Tsai3fbdf342020-01-16 05:27:32 +08001166 if (activity.getSystemService(UserManager.class).getUserProfiles().size() > 1
Raff Tsaiafd494d2019-10-16 15:25:21 +08001167 && ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName) != null
Raff Tsai84327f62019-11-15 11:02:25 +08001168 && !isWork && !isPersonal) {
Raff Tsaiafd494d2019-10-16 15:25:21 +08001169 f = Fragment.instantiate(activity, ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName),
1170 args);
1171 } else {
1172 f = Fragment.instantiate(activity, fragmentName, args);
1173 }
1174 return f;
1175 }
Yanting Yang96127fe2020-03-20 12:04:09 +08001176
1177 /**
1178 * Returns true if current binder uid is Settings Intelligence.
1179 */
1180 public static boolean isSettingsIntelligence(Context context) {
1181 final int callingUid = Binder.getCallingUid();
1182 final String callingPackage = context.getPackageManager().getPackagesForUid(callingUid)[0];
1183 final boolean isSettingsIntelligence = TextUtils.equals(callingPackage,
1184 context.getString(R.string.config_settingsintelligence_package_name));
1185 return isSettingsIntelligence;
1186 }
Jason Chiu8ac1e4d2020-05-11 16:13:47 +08001187
1188 /**
1189 * Returns true if the night mode is enabled.
1190 */
1191 public static boolean isNightMode(Context context) {
1192 final int currentNightMode =
1193 context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1194 return currentNightMode == Configuration.UI_MODE_NIGHT_YES;
1195 }
Tim Pengdf467882020-06-24 13:10:01 +08001196
1197 /**
1198 * Returns a bitmap with rounded corner.
1199 *
1200 * @param context application context.
1201 * @param source bitmap to apply round corner.
1202 * @param cornerRadius corner radius value.
1203 */
1204 public static Bitmap convertCornerRadiusBitmap(@NonNull Context context,
1205 @NonNull Bitmap source, @NonNull float cornerRadius) {
1206 final Bitmap roundedBitmap = Bitmap.createBitmap(source.getWidth(), source.getHeight(),
1207 Bitmap.Config.ARGB_8888);
1208 final RoundedBitmapDrawable drawable =
1209 RoundedBitmapDrawableFactory.create(context.getResources(), source);
1210 drawable.setAntiAlias(true);
1211 drawable.setCornerRadius(cornerRadius);
1212 final Canvas canvas = new Canvas(roundedBitmap);
1213 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1214 drawable.draw(canvas);
1215 return roundedBitmap;
1216 }
Zoey Chen3abe48e2020-10-28 22:46:48 +08001217
1218 public static boolean isProviderModelEnabled(Context context) {
1219 return FeatureFlagUtils.isEnabled(context, FeatureFlagUtils.SETTINGS_PROVIDER_MODEL);
1220 }
Yi-Ling Chuang58813f72021-04-23 17:10:53 +08001221
1222 public static boolean isPageTransitionEnabled(Context context) {
1223 final boolean isSilkyHome = FeatureFlagUtils.isEnabled(context, FeatureFlags.SILKY_HOME);
1224 final boolean isTransitionEnabled = Settings.Global.getInt(context.getContentResolver(),
Curtis Belmonte1e1b2592021-05-07 22:42:35 +00001225 SETTINGS_SHARED_AXIS_ENABLED, 0) == 1;
Yi-Ling Chuang58813f72021-04-23 17:10:53 +08001226
1227 return isSilkyHome && isTransitionEnabled;
1228 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001229}