blob: 031fb8a9d92d5aa274fc224770c6ce33836e796d [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;
markchien1dd1d792019-01-11 16:18:20 +080080import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070081import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040082import android.text.Spannable;
83import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020084import android.text.TextUtils;
Jason Monkb37e2882016-01-11 14:27:20 -050085import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040086import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070087import android.util.ArraySet;
Zoey Chen3abe48e2020-10-28 22:46:48 +080088import android.util.FeatureFlagUtils;
jackqdyuleifde637f2018-01-02 14:51:01 -080089import android.util.IconDrawableFactory;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010090import android.util.Log;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000091import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070092import android.view.View;
93import android.view.ViewGroup;
PMS2263a05602017-06-14 07:10:15 +000094import android.widget.EditText;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070095import android.widget.ListView;
96import android.widget.TabWidget;
Fan Zhangcc335d92016-09-29 14:37:14 -070097
jasonwshsu9b284a92021-04-20 15:19:15 +080098import androidx.annotation.ColorInt;
Tim Pengdf467882020-06-24 13:10:01 +080099import androidx.annotation.NonNull;
Fan Zhang23f8d592018-08-28 15:11:40 -0700100import androidx.annotation.StringRes;
Jason Chiuc78c54a2019-02-13 16:07:57 +0800101import androidx.core.graphics.drawable.IconCompat;
Tim Pengdf467882020-06-24 13:10:01 +0800102import androidx.core.graphics.drawable.RoundedBitmapDrawable;
103import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
Fan Zhang23f8d592018-08-28 15:11:40 -0700104import androidx.fragment.app.Fragment;
tmfangaed8f362019-03-18 16:56:09 +0800105import androidx.lifecycle.Lifecycle;
Fan Zhang23f8d592018-08-28 15:11:40 -0700106import androidx.preference.Preference;
107import androidx.preference.PreferenceGroup;
108
Ricky Wai616342b2016-04-13 10:40:22 +0100109import com.android.internal.app.UnlaunchableAppActivity;
Ricky Wai72500162016-06-07 16:54:25 +0100110import com.android.internal.util.ArrayUtils;
Rubin Xu3231afe2016-08-24 10:15:07 +0100111import com.android.internal.widget.LockPatternUtils;
Raff Tsaiafd494d2019-10-16 15:25:21 +0800112import com.android.settings.dashboard.profileselector.ProfileFragmentBridge;
Raff Tsai84327f62019-11-15 11:02:25 +0800113import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
Jeff Sharkey219ec912017-12-19 14:57:39 -0700114import com.android.settings.password.ChooseLockSettingsHelper;
tmfangaed8f362019-03-18 16:56:09 +0800115import com.android.settingslib.widget.ActionBarShadowController;
jasonwshsu9b284a92021-04-20 15:19:15 +0800116import com.android.settingslib.widget.AdaptiveIcon;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700117
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800118import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700119import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900120import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800121
Jason Monk27985e12016-01-08 14:13:05 -0500122public final class Utils extends com.android.settingslib.Utils {
123
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100124 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100125
Andras Kloczl106431e2020-05-18 14:53:07 +0100126 public static final String FILE_PROVIDER_AUTHORITY = "com.android.settings.files";
127
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800128 /**
129 * Set the preference's title to the matching activity's label.
130 */
131 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
132
Fan Zhangc3fd2892019-01-29 16:00:19 -0800133 public static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100134
Jason Monkbeb171d2015-05-21 15:24:37 -0400135 public static final String OS_PKG = "os";
136
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200137 /**
Svet Ganov864765f2019-04-05 19:00:05 -0700138 * Whether to disable the new device identifier access restrictions.
139 */
140 public static final String PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED =
141 "device_identifier_access_restrictions_disabled";
142
143 /**
Joel Galenson2118f8a2019-05-31 07:54:20 -0700144 * Whether to show the Permissions Hub.
145 */
146 public static final String PROPERTY_PERMISSIONS_HUB_ENABLED = "permissions_hub_enabled";
147
148 /**
Wei Wangedbe2cc2020-12-08 22:48:53 -0800149 * Whether to show location indicators.
150 */
151 public static final String PROPERTY_LOCATION_INDICATORS_ENABLED = "location_indicators_enabled";
152
153 /**
Wei Wanga6daf852021-01-12 10:30:25 -0800154 * Whether to show location indicator settings in developer options.
155 */
156 public static final String PROPERTY_LOCATION_INDICATOR_SETTINGS_ENABLED =
157 "location_indicator_settings_enabled";
158
Zhen Zhang48bd52e2021-03-03 13:53:34 -0800159 /** Whether or not app hibernation is enabled on the device **/
160 public static final String PROPERTY_APP_HIBERNATION_ENABLED = "app_hibernation_enabled";
161
Wei Wanga6daf852021-01-12 10:30:25 -0800162 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800163 * Finds a matching activity for a preference's intent. If a matching
164 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800165 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800166 * @param context The context.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800167 * @param parentPreferenceGroup The preference group that contains the
Sunny Shao7e866b62019-08-09 11:42:04 +0800168 * preference whose intent is being resolved.
169 * @param preferenceKey The key of the preference whose intent is being
170 * resolved.
171 * @param flags 0 or one or more of
172 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
173 * .
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800174 * @return Whether an activity was found. If false, the preference was
Sunny Shao7e866b62019-08-09 11:42:04 +0800175 * removed.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800176 */
177 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
178 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800179
Bonian Chen5e65da02019-11-08 07:40:35 +0800180 final Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800181 if (preference == null) {
182 return false;
183 }
Ying Wanga7188322010-01-04 18:45:10 -0800184
Bonian Chen5e65da02019-11-08 07:40:35 +0800185 final Intent intent = preference.getIntent();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800186 if (intent != null) {
187 // Find the activity that is in the system image
Bonian Chen5e65da02019-11-08 07:40:35 +0800188 final PackageManager pm = context.getPackageManager();
189 final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
190 final int listSize = list.size();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800191 for (int i = 0; i < listSize; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800192 final ResolveInfo resolveInfo = list.get(i);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800193 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
194 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800195
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800196 // Replace the intent with this specific activity
197 preference.setIntent(new Intent().setClassName(
198 resolveInfo.activityInfo.packageName,
199 resolveInfo.activityInfo.name));
200
201 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
202 // Set the preference title to the activity's label
203 preference.setTitle(resolveInfo.loadLabel(pm));
204 }
Ying Wanga7188322010-01-04 18:45:10 -0800205
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800206 return true;
207 }
208 }
209 }
210
211 // Did not find a matching activity, so remove the preference
212 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800213
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900214 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800215 }
Ying Wanga7188322010-01-04 18:45:10 -0800216
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200217 /**
Ying Wanga7188322010-01-04 18:45:10 -0800218 * Returns true if Monkey is running.
219 */
220 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700221 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800222 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700223
224 /**
225 * Returns whether the device is voice-capable (meaning, it is also a phone).
226 */
227 public static boolean isVoiceCapable(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800228 final TelephonyManager telephony =
Amith Yamasani60133dd2010-09-11 14:17:31 -0700229 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
230 return telephony != null && telephony.isVoiceCapable();
231 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800232
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800233 /**
234 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
235 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900236 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800237 */
238 public static String getWifiIpAddresses(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800239 final WifiManager wifiManager = context.getSystemService(WifiManager.class);
240 final Network currentNetwork = wifiManager.getCurrentNetwork();
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700241 if (currentNetwork != null) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800242 final ConnectivityManager cm = (ConnectivityManager)
Sunny Shao7e866b62019-08-09 11:42:04 +0800243 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800244 final LinkProperties prop = cm.getLinkProperties(currentNetwork);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700245 return formatIpAddresses(prop);
246 }
247 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700248 }
249
Amith Yamasani6822b742011-10-17 16:41:00 -0700250 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800251 if (prop == null) return null;
Chiachang Wang003e27d2021-03-18 15:01:03 +0800252 final Iterator<LinkAddress> iter = prop.getAllLinkAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800253 // If there are no entries, return null
254 if (!iter.hasNext()) return null;
255 // Concatenate all available addresses, comma separated
256 String addresses = "";
257 while (iter.hasNext()) {
Chiachang Wang003e27d2021-03-18 15:01:03 +0800258 addresses += iter.next().getAddress().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900259 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800260 }
261 return addresses;
262 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900263
264 public static Locale createLocaleFromString(String localeStr) {
265 // TODO: is there a better way to actually construct a locale that will match?
266 // The main problem is, on top of Java specs, locale.toString() and
267 // new Locale(locale.toString()).toString() do not return equal() strings in
268 // many cases, because the constructor takes the only string as the language
269 // code. So : new Locale("en", "US").toString() => "en_US"
270 // And : new Locale("en_US").toString() => "en_us"
Sunny Shao7e866b62019-08-09 11:42:04 +0800271 if (null == localeStr)
Jean Chalard71ad1f42011-05-12 15:06:16 +0900272 return Locale.getDefault();
Bonian Chen5e65da02019-11-08 07:40:35 +0800273 final String[] brokenDownLocale = localeStr.split("_", 3);
Jean Chalard71ad1f42011-05-12 15:06:16 +0900274 // split may not return a 0-length array.
275 if (1 == brokenDownLocale.length) {
276 return new Locale(brokenDownLocale[0]);
277 } else if (2 == brokenDownLocale.length) {
278 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
279 } else {
280 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
281 }
282 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700283
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900284 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
285 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
286 }
287
Mill Chenad99e2e2020-10-21 16:32:56 +0800288 /**
289 * Return true if battery is present.
290 */
291 public static boolean isBatteryPresent(Context context) {
292 Intent batteryBroadcast = context.registerReceiver(null /* receiver */,
293 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
294 return isBatteryPresent(batteryBroadcast);
295 }
296
Amith Yamasania4379d62011-07-22 10:34:58 -0700297 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700298 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700299 }
300
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700301 /**
302 * Prepare a custom preferences layout, moving padding to {@link ListView}
303 * when outside scrollbars are requested. Usually used to display
304 * {@link ListView} and {@link TabWidget} with correct padding.
305 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700306 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800307 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700308 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700309 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700310 final Resources res = list.getResources();
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700311 final int paddingBottom = res.getDimensionPixelSize(
312 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700313
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700314 if (parent instanceof PreferenceFrameLayout) {
315 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700316 }
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800317 list.setPaddingRelative(0 /* start */, 0 /* top */, 0 /* end */, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700318 }
319 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700320
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700321 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700322 final Resources res = view.getResources();
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700323
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800324 final int paddingStart = additive ? view.getPaddingStart() : 0;
325 final int paddingEnd = additive ? view.getPaddingEnd() : 0;
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700326 final int paddingBottom = res.getDimensionPixelSize(
327 com.android.internal.R.dimen.preference_fragment_padding_bottom);
328
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700329 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700330 }
331
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700332 public static String getMeProfileName(Context context, boolean full) {
333 if (full) {
334 return getProfileDisplayName(context);
335 } else {
336 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700337 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700338 }
339
340 private static String getShorterNameIfPossible(Context context) {
341 final String given = getLocalProfileGivenName(context);
342 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
343 }
344
345 private static String getLocalProfileGivenName(Context context) {
346 final ContentResolver cr = context.getContentResolver();
347
348 // Find the raw contact ID for the local ME profile raw contact.
349 final long localRowProfileId;
350 final Cursor localRawProfile = cr.query(
351 Profile.CONTENT_RAW_CONTACTS_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800352 new String[] {RawContacts._ID},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700353 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
354 RawContacts.ACCOUNT_NAME + " IS NULL",
355 null, null);
356 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700357
358 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700359 if (!localRawProfile.moveToFirst()) {
360 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700361 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700362 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700363 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700364 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700365 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700366
367 // Find the structured name for the raw contact.
368 final Cursor structuredName = cr.query(
369 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
Sunny Shao7e866b62019-08-09 11:42:04 +0800370 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
371 CommonDataKinds.StructuredName.FAMILY_NAME},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700372 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
373 null, null);
374 if (structuredName == null) return null;
375
376 try {
377 if (!structuredName.moveToFirst()) {
378 return null;
379 }
380 String partialName = structuredName.getString(0);
381 if (TextUtils.isEmpty(partialName)) {
382 partialName = structuredName.getString(1);
383 }
384 return partialName;
385 } finally {
386 structuredName.close();
387 }
388 }
389
390 private static final String getProfileDisplayName(Context context) {
391 final ContentResolver cr = context.getContentResolver();
392 final Cursor profile = cr.query(Profile.CONTENT_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800393 new String[] {Profile.DISPLAY_NAME}, null, null, null);
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700394 if (profile == null) return null;
395
396 try {
397 if (!profile.moveToFirst()) {
398 return null;
399 }
400 return profile.getString(0);
401 } finally {
402 profile.close();
403 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700404 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700405
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700406 public static boolean hasMultipleUsers(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800407 return context.getSystemService(UserManager.class)
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700408 .getUsers().size() > 1;
409 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700410
411 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100412 * Returns the managed profile of the current user or {@code null} if none is found or a profile
413 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100414 */
415 public static UserHandle getManagedProfile(UserManager userManager) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800416 final List<UserHandle> userProfiles = userManager.getUserProfiles();
Aarthi Balachanderd0f83592018-07-10 17:04:53 -0700417 for (UserHandle profile : userProfiles) {
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100418 if (profile.getIdentifier() == userManager.getUserHandle()) {
419 continue;
420 }
421 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
422 if (userInfo.isManagedProfile()) {
423 return profile;
424 }
425 }
426 return null;
427 }
428
429 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100430 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
431 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
432 */
433 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
434 // TODO: Call getManagedProfileId from here once Robolectric supports
435 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
436 // yet another implementation that loops over user profiles in this method). In the meantime
437 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
438 // used for Settings Robolectric tests).
439 final int myUserId = UserHandle.myUserId();
Bonian Chen5e65da02019-11-08 07:40:35 +0800440 final List<UserInfo> profiles = userManager.getProfiles(myUserId);
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100441 final int count = profiles.size();
442 for (int i = 0; i < count; i++) {
443 final UserInfo profile = profiles.get(i);
444 if (profile.isManagedProfile()
445 && profile.getUserHandle().getIdentifier() != myUserId) {
446 return profile.getUserHandle();
447 }
448 }
449 return null;
450 }
451
452 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000453 * Retrieves the id for the given user's managed profile.
454 *
455 * @return the managed profile id or UserHandle.USER_NULL if there is none.
456 */
457 public static int getManagedProfileId(UserManager um, int parentUserId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800458 final int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700459 for (int profileId : profileIds) {
460 if (profileId != parentUserId) {
461 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000462 }
463 }
464 return UserHandle.USER_NULL;
465 }
466
467 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100468 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000469 * <p>
470 * User would be retrieved in this order:
471 * <ul>
472 * <li> If this activity is launched from other user, return that user id.
473 * <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 +0800474 * extra in the arguments or intent extras.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000475 * <li> Otherwise, return UserHandle.myUserId().
476 * </ul>
477 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100478 * Note: This is secure in the sense that it only returns a target user different to the current
479 * one if the app launching this activity is the Settings app itself, running in the same user
480 * 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 +0100481 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100482 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000483 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800484 final UserHandle currentUser = new UserHandle(UserHandle.myUserId());
485 final IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100486 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800487 final String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
488 final boolean launchedFromSettingsApp =
489 SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100490
Bonian Chen5e65da02019-11-08 07:40:35 +0800491 final UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100492 am.getLaunchedFromUid(activityToken)));
493 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
494 // Check it's secure
495 if (isProfileOf(um, launchedFromUser)) {
496 return launchedFromUser;
497 }
498 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800499 final UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100500 if (extrasUser != null && !extrasUser.equals(currentUser)) {
501 // Check it's secure
502 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
503 return extrasUser;
504 }
505 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800506 final UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100507 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
508 // Check it's secure
509 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
510 return argumentsUser;
511 }
512 }
513 } catch (RemoteException e) {
514 // Should not happen
515 Log.v(TAG, "Could not talk to activity manager.", e);
516 }
517 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000518 }
519
520 /**
521 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
522 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
523 */
Sunny Shao7e866b62019-08-09 11:42:04 +0800524 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
Tony Mak8f41b9b2016-11-23 11:36:18 +0000525 if (bundle == null) {
526 return null;
527 }
528 final UserHandle user = bundle.getParcelable(EXTRA_USER);
529 if (user != null) {
530 return user;
531 }
532 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
533 if (userId != -1) {
534 return UserHandle.of(userId);
535 }
536 return null;
537 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100538
Sunny Shao7e866b62019-08-09 11:42:04 +0800539 /**
540 * Returns true if the user provided is in the same profiles group as the current user.
541 */
542 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
543 if (um == null || otherUser == null) return false;
544 return (UserHandle.myUserId() == otherUser.getIdentifier())
545 || um.getUserProfiles().contains(otherUser);
546 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530547
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100548 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800549 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
550 * @param userManager Instance of UserManager
Sunny Shao7e866b62019-08-09 11:42:04 +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) {
Colin Cross38fa1852020-08-27 04:12:26 +0000555 final List<UserInfo> users = userManager.getAliveUsers();
Amith Yamasani45f86232014-11-19 17:12:46 -0800556 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) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800576 final List<IntentFilterVerificationInfo> iviList =
577 pm.getIntentFilterVerifications(packageName);
578 final List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
Christopher Tatea08a2252015-07-01 16:52:43 -0700579
Bonian Chen5e65da02019-11-08 07:40:35 +0800580 final ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800581 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700582 for (IntentFilterVerificationInfo ivi : iviList) {
583 for (String host : ivi.getDomains()) {
584 result.add(host);
585 }
586 }
587 }
588 if (filters != null && filters.size() > 0) {
589 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700590 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
591 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
Sunny Shao7e866b62019-08-09 11:42:04 +0800592 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700593 result.addAll(filter.getHostsList());
594 }
595 }
596 }
597 return result;
598 }
599
Sudheer Shankabc956302015-04-09 12:19:53 +0100600 /**
601 * Returns the application info of the currently installed MDM package.
602 */
603 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800604 final DevicePolicyManager dpm =
Sudheer Shankabc956302015-04-09 12:19:53 +0100605 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800606 final ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
Sudheer Shankabc956302015-04-09 12:19:53 +0100607 if (mdmPackage == null) {
608 return null;
609 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800610 final String mdmPackageName = mdmPackage.getPackageName();
Sudheer Shankabc956302015-04-09 12:19:53 +0100611 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800612 final IPackageManager ipm = AppGlobals.getPackageManager();
613 final ApplicationInfo mdmApplicationInfo =
Sudheer Shankabc956302015-04-09 12:19:53 +0100614 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
615 return mdmApplicationInfo;
616 } catch (RemoteException e) {
617 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
618 + ", userId " + profileId, e);
619 return null;
620 }
621 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400622
623 public static boolean isBandwidthControlEnabled() {
624 final INetworkManagementService netManager = INetworkManagementService.Stub
625 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
626 try {
627 return netManager.isBandwidthControlEnabled();
628 } catch (RemoteException e) {
629 return false;
630 }
631 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400632
633 /**
634 * Returns an accessible SpannableString.
Sunny Shao7e866b62019-08-09 11:42:04 +0800635 * @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) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800640 final SpannableString str = new SpannableString(displayText);
Julia Reynoldsce25af42015-07-08 16:56:31 -0400641 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 Shao7e866b62019-08-09 11:42:04 +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 Shao7e866b62019-08-09 11:42:04 +0800663 * meaning we're willing to trust extras like
Kevin Chynb13bc502020-07-20 23:35:21 -0700664 * {@link ChooseLockSettingsHelper#EXTRA_KEY_ALLOW_ANY_USER}.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700665 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +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
Kevin Chynb13bc502020-07-20 23:35:21 -0700673 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_KEY_ALLOW_ANY_USER, false);
Bonian Chen5e65da02019-11-08 07:40:35 +0800674 final 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) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800701 final UserManager um = context.getSystemService(UserManager.class);
Ricky Wai72500162016-06-07 16:54:25 +0100702 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) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800721 final UserManager um = context.getSystemService(UserManager.class);
Benjamin Franz194300d2016-01-13 12:16:25 +0000722 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700723 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500724
Alex Johnston403c3302020-01-07 15:40:05 +0000725 /**
726 * Returns the credential type of the given user id.
727 */
728 public static @LockPatternUtils.CredentialType int getCredentialType(Context context,
729 int userId) {
730 final LockPatternUtils lpu = new LockPatternUtils(context);
731 return lpu.getCredentialTypeForUser(userId);
732 }
733
Jason Monkb37e2882016-01-11 14:27:20 -0500734 private static final StringBuilder sBuilder = new StringBuilder(50);
735 private static final java.util.Formatter sFormatter = new java.util.Formatter(
736 sBuilder, Locale.getDefault());
737
738 public static String formatDateRange(Context context, long start, long end) {
739 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
740
741 synchronized (sBuilder) {
742 sBuilder.setLength(0);
743 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
744 .toString();
745 }
746 }
Jason Monk91e2f892016-02-23 15:31:09 -0500747
Bernard Chau88d523b2016-04-14 15:08:28 +0100748 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100749 int userId) {
750 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
751 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
752 context.startActivity(intent);
753 return true;
754 }
755 return false;
756 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700757
Rubin Xu3231afe2016-08-24 10:15:07 +0100758 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
759 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800760 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100761 ActivityManager.FLAG_AND_LOCKED)) {
762 return false;
763 }
764 } catch (RemoteException e) {
765 return false;
766 }
767 if (!(new LockPatternUtils(context)).isSecure(userId)) {
768 return false;
769 }
Robin Leecccf3242017-02-10 15:32:49 +0000770 return confirmWorkProfileCredentials(context, userId);
771 }
772
Robin Leecccf3242017-02-10 15:32:49 +0000773 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100774 final KeyguardManager km = (KeyguardManager) context.getSystemService(
775 Context.KEYGUARD_SERVICE);
776 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
777 if (unlockIntent != null) {
778 context.startActivity(unlockIntent);
779 return true;
780 } else {
781 return false;
782 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100783 }
784
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700785 public static CharSequence getApplicationLabel(Context context, String packageName) {
786 try {
787 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
788 packageName,
789 PackageManager.MATCH_DISABLED_COMPONENTS
Sunny Shao7e866b62019-08-09 11:42:04 +0800790 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700791 return appInfo.loadLabel(context.getPackageManager());
792 } catch (PackageManager.NameNotFoundException e) {
Raff Tsai376ce872020-01-06 00:42:35 +0800793 Log.e(TAG, "Unable to find info for package: " + packageName);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700794 }
795 return null;
796 }
Jason Monk75199542016-05-06 15:09:32 -0400797
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600798 public static boolean isPackageDirectBootAware(Context context, String packageName) {
799 try {
800 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
801 packageName, 0);
802 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
803 } catch (NameNotFoundException ignored) {
804 }
805 return false;
806 }
Andre Lago3e398c82016-07-25 14:12:28 +0100807
808 /**
809 * Returns a context created from the given context for the given user, or null if it fails
810 */
811 public static Context createPackageContextAsUser(Context context, int userId) {
812 try {
813 return context.createPackageContextAsUser(
814 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
815 } catch (PackageManager.NameNotFoundException e) {
816 Log.e(TAG, "Failed to create user context", e);
817 }
818 return null;
819 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600820
821 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
822 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800823 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600824 } else {
825 return null;
826 }
827 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800828
Kevin Chyn82792cc2017-07-20 00:15:44 -0700829 public static boolean hasFingerprintHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800830 final FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
Kevin Chyn82792cc2017-07-20 00:15:44 -0700831 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
832 }
833
Kevin Chyn4882e872018-06-25 17:58:31 -0700834 public static FaceManager getFaceManagerOrNull(Context context) {
835 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
836 return (FaceManager) context.getSystemService(Context.FACE_SERVICE);
837 } else {
838 return null;
839 }
840 }
841
842 public static boolean hasFaceHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800843 final FaceManager faceManager = getFaceManagerOrNull(context);
Kevin Chyn4882e872018-06-25 17:58:31 -0700844 return faceManager != null && faceManager.isHardwareDetected();
845 }
846
Daniel Nishi31027da2017-01-19 14:03:57 -0800847 /**
Mill Chen7edebee2021-04-09 23:14:27 +0800848 * Return true if the device supports multiple biometrics authentications.
849 */
850 public static boolean isMultipleBiometricsSupported(Context context) {
851 return hasFingerprintHardware(context) && hasFaceHardware(context);
852 }
853
854 /**
Daniel Nishi31027da2017-01-19 14:03:57 -0800855 * Launches an intent which may optionally have a user id defined.
856 * @param fragment Fragment to use to launch the activity.
Sunny Shao7e866b62019-08-09 11:42:04 +0800857 * @param intent Intent to launch.
Daniel Nishi31027da2017-01-19 14:03:57 -0800858 */
859 public static void launchIntent(Fragment fragment, Intent intent) {
860 try {
861 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
862
863 if (userId == -1) {
864 fragment.startActivity(intent);
865 } else {
866 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
867 }
868 } catch (ActivityNotFoundException e) {
869 Log.w(TAG, "No activity found for " + intent);
870 }
871 }
872
Christine Franksc6890ab2017-06-23 14:28:21 -0700873 public static boolean isDemoUser(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800874 return UserManager.isDeviceInDemoMode(context)
875 && context.getSystemService(UserManager.class).isDemoUser();
Christine Franksc6890ab2017-06-23 14:28:21 -0700876 }
877
Justin Klaassen30257272017-08-08 21:58:05 -0700878 public static ComponentName getDeviceOwnerComponent(Context context) {
879 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
880 Context.DEVICE_POLICY_SERVICE);
881 return dpm.getDeviceOwnerComponentOnAnyUser();
Christine Franks14782222017-01-23 16:44:02 -0800882 }
Daniel Nishidfed8a22017-01-19 16:32:41 -0800883
884 /**
885 * Returns if a given user is a profile of another user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800886 * @param user The user whose profiles wibe checked.
Daniel Nishidfed8a22017-01-19 16:32:41 -0800887 * @param profile The (potential) profile.
888 * @return if the profile is actually a profile
889 */
890 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
891 return user.id == profile.id ||
892 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
893 && user.profileGroupId == profile.profileGroupId);
894 }
Daniel Nishi9f60f422017-02-15 15:25:48 -0800895
896 /**
897 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
898 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
899 */
900 @Nullable
901 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
902 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
903 VolumeInfo.ID_PRIVATE_INTERNAL);
Bonian Chen5e65da02019-11-08 07:40:35 +0800904 final VolumeInfo volume = sm.findVolumeById(volumeId);
Daniel Nishi9f60f422017-02-15 15:25:48 -0800905 return isVolumeValid(volume) ? volume : null;
906 }
907
jackqdyuleiddba9662017-03-08 19:35:02 -0800908 /**
jackqdyulei00015fb2017-08-22 11:25:30 -0700909 * Return {@code true} if the supplied package is device owner or profile owner of at
910 * least one user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800911 * @param userManager used to get profile owner app for each user
jackqdyulei00015fb2017-08-22 11:25:30 -0700912 * @param devicePolicyManager used to check whether it is device owner app
Sunny Shao7e866b62019-08-09 11:42:04 +0800913 * @param packageName package to check about
jackqdyulei00015fb2017-08-22 11:25:30 -0700914 */
915 public static boolean isProfileOrDeviceOwner(UserManager userManager,
Fan Zhangaab36de2018-03-30 16:58:28 -0700916 DevicePolicyManager devicePolicyManager, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800917 final List<UserInfo> userInfos = userManager.getUsers();
jackqdyulei00015fb2017-08-22 11:25:30 -0700918 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
919 return true;
920 }
921 for (int i = 0, size = userInfos.size(); i < size; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800922 final ComponentName cn = devicePolicyManager
923 .getProfileOwnerAsUser(userInfos.get(i).id);
jackqdyulei00015fb2017-08-22 11:25:30 -0700924 if (cn != null && cn.getPackageName().equals(packageName)) {
925 return true;
926 }
927 }
928 return false;
929 }
930
931 /**
Alex Johnston341f9952020-02-26 15:54:11 +0000932 * Return {@code true} if the supplied package is the device owner or profile owner of a
933 * given user.
934 *
935 * @param devicePolicyManager used to check whether it is device owner and profile owner app
936 * @param packageName package to check about
937 * @param userId the if of the relevant user
938 */
939 public static boolean isProfileOrDeviceOwner(DevicePolicyManager devicePolicyManager,
940 String packageName, int userId) {
941 if ((devicePolicyManager.getDeviceOwnerUserId() == userId)
942 && devicePolicyManager.isDeviceOwnerApp(packageName)) {
943 return true;
944 }
945 final ComponentName cn = devicePolicyManager.getProfileOwnerAsUser(userId);
946 if (cn != null && cn.getPackageName().equals(packageName)) {
947 return true;
948 }
949 return false;
950 }
951
952 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800953 * Return the resource id to represent the install status for an app
954 */
955 @StringRes
956 public static int getInstallationStatus(ApplicationInfo info) {
957 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
958 return R.string.not_installed;
959 }
960 return info.enabled ? R.string.installed : R.string.disabled;
961 }
962
Daniel Nishi9f60f422017-02-15 15:25:48 -0800963 private static boolean isVolumeValid(VolumeInfo volume) {
964 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
965 && volume.isMountedReadable();
966 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700967
PMS2263a05602017-06-14 07:10:15 +0000968 public static void setEditTextCursorPosition(EditText editText) {
969 editText.setSelection(editText.getText().length());
970 }
Felipe Lemebd884502017-09-15 18:16:21 -0700971
972 /**
jasonwshsu9b284a92021-04-20 15:19:15 +0800973 * Gets the adaptive icon with a drawable that wrapped with an adaptive background using {@code
974 * backgroundColor} if it is not a {@link AdaptiveIconDrawable}
975 *
976 * If the given {@code icon} is too big, it will be auto scaled down to to avoid crashing
977 * Settings.
Felipe Lemebd884502017-09-15 18:16:21 -0700978 */
jasonwshsu9b284a92021-04-20 15:19:15 +0800979 public static Drawable getAdaptiveIcon(Context context, Drawable icon,
980 @ColorInt int backgroundColor) {
981 Drawable adaptiveIcon = getSafeIcon(icon);
982
983 if (!(adaptiveIcon instanceof AdaptiveIconDrawable)) {
984 adaptiveIcon = new AdaptiveIcon(context, adaptiveIcon);
985 ((AdaptiveIcon) adaptiveIcon).setBackgroundColor(backgroundColor);
986 }
987
988 return adaptiveIcon;
989 }
990
991 /**
992 * Gets the icon with a drawable that is scaled down to to avoid crashing Settings if it's too
993 * big and not a {@link VectorDrawable}.
994 */
995 public static Drawable getSafeIcon(Drawable icon) {
Felipe Lemebd884502017-09-15 18:16:21 -0700996 Drawable safeIcon = icon;
jasonwshsu9b284a92021-04-20 15:19:15 +0800997
Phil Weaver5a3e02d2018-03-08 17:38:46 -0800998 if ((icon != null) && !(icon instanceof VectorDrawable)) {
Felipe Lemebd884502017-09-15 18:16:21 -0700999 safeIcon = getSafeDrawable(icon, 500, 500);
1000 }
jasonwshsu9b284a92021-04-20 15:19:15 +08001001
1002 return safeIcon;
Felipe Lemebd884502017-09-15 18:16:21 -07001003 }
1004
1005 /**
1006 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
1007 *
Sunny Shao7e866b62019-08-09 11:42:04 +08001008 * @param original original drawable, typically an app icon.
1009 * @param maxWidth maximum width, in pixels.
Felipe Lemebd884502017-09-15 18:16:21 -07001010 * @param maxHeight maximum height, in pixels.
1011 */
jasonwshsu9b284a92021-04-20 15:19:15 +08001012 private static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
Felipe Lemebd884502017-09-15 18:16:21 -07001013 final int actualWidth = original.getMinimumWidth();
1014 final int actualHeight = original.getMinimumHeight();
1015
1016 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
1017 return original;
1018 }
1019
Bonian Chen5e65da02019-11-08 07:40:35 +08001020 final float scaleWidth = ((float) maxWidth) / actualWidth;
1021 final float scaleHeight = ((float) maxHeight) / actualHeight;
1022 final float scale = Math.min(scaleWidth, scaleHeight);
Felipe Lemebd884502017-09-15 18:16:21 -07001023 final int width = (int) (actualWidth * scale);
1024 final int height = (int) (actualHeight * scale);
1025
1026 final Bitmap bitmap;
1027 if (original instanceof BitmapDrawable) {
1028 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
1029 height, false);
1030 } else {
Jason Chiuc78c54a2019-02-13 16:07:57 +08001031 bitmap = createBitmap(original, width, height);
Felipe Lemebd884502017-09-15 18:16:21 -07001032 }
1033 return new BitmapDrawable(null, bitmap);
1034 }
jackqdyuleifde637f2018-01-02 14:51:01 -08001035
1036 /**
Jason Chiuc78c54a2019-02-13 16:07:57 +08001037 * Create an Icon pointing to a drawable.
Jason Chiu1217bbe2019-01-24 16:32:31 +08001038 */
Jason Chiuc78c54a2019-02-13 16:07:57 +08001039 public static IconCompat createIconWithDrawable(Drawable drawable) {
1040 Bitmap bitmap;
Jason Chiu1217bbe2019-01-24 16:32:31 +08001041 if (drawable instanceof BitmapDrawable) {
Sunny Shao7e866b62019-08-09 11:42:04 +08001042 bitmap = ((BitmapDrawable)drawable).getBitmap();
Jason Chiuc78c54a2019-02-13 16:07:57 +08001043 } else {
1044 final int width = drawable.getIntrinsicWidth();
1045 final int height = drawable.getIntrinsicHeight();
1046 bitmap = createBitmap(drawable,
1047 width > 0 ? width : 1,
1048 height > 0 ? height : 1);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001049 }
Jason Chiuc78c54a2019-02-13 16:07:57 +08001050 return IconCompat.createWithBitmap(bitmap);
1051 }
Jason Chiu1217bbe2019-01-24 16:32:31 +08001052
clownshen24827d32019-03-29 20:22:02 +08001053 /**
1054 * Creates a drawable with specified width and height.
1055 */
1056 public static Bitmap createBitmap(Drawable drawable, int width, int height) {
Jason Chiuc78c54a2019-02-13 16:07:57 +08001057 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001058 final Canvas canvas = new Canvas(bitmap);
1059 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1060 drawable.draw(canvas);
1061 return bitmap;
1062 }
1063
1064 /**
jackqdyuleifde637f2018-01-02 14:51:01 -08001065 * Get the {@link Drawable} that represents the app icon
1066 */
1067 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
1068 PackageManager packageManager, String packageName, int userId) {
1069 try {
Tony Mak4e292812018-03-19 15:37:21 +00001070 final ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
1071 packageName, PackageManager.GET_META_DATA, userId);
jackqdyuleifde637f2018-01-02 14:51:01 -08001072 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
1073 } catch (PackageManager.NameNotFoundException e) {
1074 return packageManager.getDefaultActivityIcon();
1075 }
1076 }
Raff Tsai2928cd42018-11-05 16:10:19 +08001077
1078 /** Returns true if the current package is installed & enabled. */
1079 public static boolean isPackageEnabled(Context context, String packageName) {
1080 try {
1081 return context.getPackageManager().getApplicationInfo(packageName, 0).enabled;
1082 } catch (Exception e) {
1083 Log.e(TAG, "Error while retrieving application info for package " + packageName, e);
1084 }
1085 return false;
1086 }
markchien1dd1d792019-01-11 16:18:20 +08001087
1088 /** Get {@link Resources} by subscription id if subscription id is valid. */
1089 public static Resources getResourcesForSubId(Context context, int subId) {
1090 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1091 return SubscriptionManager.getResourcesForSubId(context, subId);
1092 } else {
1093 return context.getResources();
1094 }
1095 }
Ng Zhi Anb97bdc32019-02-01 12:39:31 -08001096
1097 /**
1098 * Returns true if SYSTEM_ALERT_WINDOW permission is available.
1099 * Starting from Q, SYSTEM_ALERT_WINDOW is disabled on low ram phones.
1100 */
1101 public static boolean isSystemAlertWindowEnabled(Context context) {
1102 // SYSTEM_ALERT_WINDOW is disabled on on low ram devices starting from Q
1103 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
1104 return !(am.isLowRamDevice() && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q));
1105 }
tmfangaed8f362019-03-18 16:56:09 +08001106
1107 /**
1108 * Adds a shadow appear/disappear animation to action bar scroll.
1109 *
1110 * <p/>
1111 * This method must be called after {@link Fragment#onCreate(Bundle)}.
1112 */
1113 public static void setActionBarShadowAnimation(Activity activity, Lifecycle lifecycle,
1114 View scrollView) {
1115 if (activity == null) {
1116 Log.w(TAG, "No activity, cannot style actionbar.");
1117 return;
1118 }
1119 final ActionBar actionBar = activity.getActionBar();
1120 if (actionBar == null) {
1121 Log.w(TAG, "No actionbar, cannot style actionbar.");
1122 return;
1123 }
1124 actionBar.setElevation(0);
1125
1126 if (lifecycle != null && scrollView != null) {
1127 ActionBarShadowController.attachToView(activity, lifecycle, scrollView);
1128 }
1129 }
Raff Tsaiafd494d2019-10-16 15:25:21 +08001130
1131 /**
1132 * Return correct target fragment based on argument
1133 *
1134 * @param activity the activity target fragment will be launched.
1135 * @param fragmentName initial target fragment name.
1136 * @param args fragment launch arguments.
1137 */
1138 public static Fragment getTargetFragment(Activity activity, String fragmentName, Bundle args) {
1139 Fragment f = null;
Raff Tsai84327f62019-11-15 11:02:25 +08001140 final boolean isPersonal = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001141 == ProfileSelectFragment.ProfileType.PERSONAL : false;
Raff Tsai84327f62019-11-15 11:02:25 +08001142 final boolean isWork = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001143 == ProfileSelectFragment.ProfileType.WORK : false;
Raff Tsai3fbdf342020-01-16 05:27:32 +08001144 if (activity.getSystemService(UserManager.class).getUserProfiles().size() > 1
Raff Tsaiafd494d2019-10-16 15:25:21 +08001145 && ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName) != null
Raff Tsai84327f62019-11-15 11:02:25 +08001146 && !isWork && !isPersonal) {
Raff Tsaiafd494d2019-10-16 15:25:21 +08001147 f = Fragment.instantiate(activity, ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName),
1148 args);
1149 } else {
1150 f = Fragment.instantiate(activity, fragmentName, args);
1151 }
1152 return f;
1153 }
Yanting Yang96127fe2020-03-20 12:04:09 +08001154
1155 /**
1156 * Returns true if current binder uid is Settings Intelligence.
1157 */
1158 public static boolean isSettingsIntelligence(Context context) {
1159 final int callingUid = Binder.getCallingUid();
1160 final String callingPackage = context.getPackageManager().getPackagesForUid(callingUid)[0];
1161 final boolean isSettingsIntelligence = TextUtils.equals(callingPackage,
1162 context.getString(R.string.config_settingsintelligence_package_name));
1163 return isSettingsIntelligence;
1164 }
Jason Chiu8ac1e4d2020-05-11 16:13:47 +08001165
1166 /**
1167 * Returns true if the night mode is enabled.
1168 */
1169 public static boolean isNightMode(Context context) {
1170 final int currentNightMode =
1171 context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1172 return currentNightMode == Configuration.UI_MODE_NIGHT_YES;
1173 }
Tim Pengdf467882020-06-24 13:10:01 +08001174
1175 /**
1176 * Returns a bitmap with rounded corner.
1177 *
1178 * @param context application context.
1179 * @param source bitmap to apply round corner.
1180 * @param cornerRadius corner radius value.
1181 */
1182 public static Bitmap convertCornerRadiusBitmap(@NonNull Context context,
1183 @NonNull Bitmap source, @NonNull float cornerRadius) {
1184 final Bitmap roundedBitmap = Bitmap.createBitmap(source.getWidth(), source.getHeight(),
1185 Bitmap.Config.ARGB_8888);
1186 final RoundedBitmapDrawable drawable =
1187 RoundedBitmapDrawableFactory.create(context.getResources(), source);
1188 drawable.setAntiAlias(true);
1189 drawable.setCornerRadius(cornerRadius);
1190 final Canvas canvas = new Canvas(roundedBitmap);
1191 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1192 drawable.draw(canvas);
1193 return roundedBitmap;
1194 }
Zoey Chen3abe48e2020-10-28 22:46:48 +08001195
1196 public static boolean isProviderModelEnabled(Context context) {
1197 return FeatureFlagUtils.isEnabled(context, FeatureFlagUtils.SETTINGS_PROVIDER_MODEL);
1198 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001199}