blob: f996444b4820e5475990123d19738ae9106a7603 [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;
jackqdyuleifde637f2018-01-02 14:51:01 -080088import android.util.IconDrawableFactory;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010089import android.util.Log;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000090import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070091import android.view.View;
92import android.view.ViewGroup;
PMS2263a05602017-06-14 07:10:15 +000093import android.widget.EditText;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070094import android.widget.ListView;
95import android.widget.TabWidget;
Fan Zhangcc335d92016-09-29 14:37:14 -070096
jasonwshsu9b284a92021-04-20 15:19:15 +080097import androidx.annotation.ColorInt;
Tim Pengdf467882020-06-24 13:10:01 +080098import androidx.annotation.NonNull;
Fan Zhang23f8d592018-08-28 15:11:40 -070099import androidx.annotation.StringRes;
Jason Chiuc78c54a2019-02-13 16:07:57 +0800100import androidx.core.graphics.drawable.IconCompat;
Tim Pengdf467882020-06-24 13:10:01 +0800101import androidx.core.graphics.drawable.RoundedBitmapDrawable;
102import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
Fan Zhang23f8d592018-08-28 15:11:40 -0700103import androidx.fragment.app.Fragment;
tmfangaed8f362019-03-18 16:56:09 +0800104import androidx.lifecycle.Lifecycle;
Fan Zhang23f8d592018-08-28 15:11:40 -0700105import androidx.preference.Preference;
106import androidx.preference.PreferenceGroup;
107
Ricky Wai616342b2016-04-13 10:40:22 +0100108import com.android.internal.app.UnlaunchableAppActivity;
Ricky Wai72500162016-06-07 16:54:25 +0100109import com.android.internal.util.ArrayUtils;
Rubin Xu3231afe2016-08-24 10:15:07 +0100110import com.android.internal.widget.LockPatternUtils;
Raff Tsaiafd494d2019-10-16 15:25:21 +0800111import com.android.settings.dashboard.profileselector.ProfileFragmentBridge;
Raff Tsai84327f62019-11-15 11:02:25 +0800112import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
Jeff Sharkey219ec912017-12-19 14:57:39 -0700113import com.android.settings.password.ChooseLockSettingsHelper;
tmfangaed8f362019-03-18 16:56:09 +0800114import com.android.settingslib.widget.ActionBarShadowController;
jasonwshsu9b284a92021-04-20 15:19:15 +0800115import com.android.settingslib.widget.AdaptiveIcon;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700116
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800117import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700118import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900119import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800120
Jason Monk27985e12016-01-08 14:13:05 -0500121public final class Utils extends com.android.settingslib.Utils {
122
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100123 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100124
Andras Kloczl106431e2020-05-18 14:53:07 +0100125 public static final String FILE_PROVIDER_AUTHORITY = "com.android.settings.files";
126
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800127 /**
128 * Set the preference's title to the matching activity's label.
129 */
130 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
131
Fan Zhangc3fd2892019-01-29 16:00:19 -0800132 public static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100133
Jason Monkbeb171d2015-05-21 15:24:37 -0400134 public static final String OS_PKG = "os";
135
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200136 /**
Svet Ganov864765f2019-04-05 19:00:05 -0700137 * Whether to disable the new device identifier access restrictions.
138 */
139 public static final String PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED =
140 "device_identifier_access_restrictions_disabled";
141
142 /**
Joel Galenson2118f8a2019-05-31 07:54:20 -0700143 * Whether to show the Permissions Hub.
144 */
145 public static final String PROPERTY_PERMISSIONS_HUB_ENABLED = "permissions_hub_enabled";
146
147 /**
Wei Wangedbe2cc2020-12-08 22:48:53 -0800148 * Whether to show location indicators.
149 */
150 public static final String PROPERTY_LOCATION_INDICATORS_ENABLED = "location_indicators_enabled";
151
152 /**
Wei Wanga6daf852021-01-12 10:30:25 -0800153 * Whether to show location indicator settings in developer options.
154 */
155 public static final String PROPERTY_LOCATION_INDICATOR_SETTINGS_ENABLED =
156 "location_indicator_settings_enabled";
157
Zhen Zhang48bd52e2021-03-03 13:53:34 -0800158 /** Whether or not app hibernation is enabled on the device **/
159 public static final String PROPERTY_APP_HIBERNATION_ENABLED = "app_hibernation_enabled";
160
Kevin Han4b342712021-05-25 17:45:23 -0700161 /** Whether or not app hibernation targets apps that target a pre-S SDK **/
162 public static final String PROPERTY_HIBERNATION_TARGETS_PRE_S_APPS =
163 "app_hibernation_targets_pre_s_apps";
164
Wei Wanga6daf852021-01-12 10:30:25 -0800165 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800166 * Finds a matching activity for a preference's intent. If a matching
167 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800168 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800169 * @param context The context.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800170 * @param parentPreferenceGroup The preference group that contains the
Sunny Shao7e866b62019-08-09 11:42:04 +0800171 * preference whose intent is being resolved.
172 * @param preferenceKey The key of the preference whose intent is being
173 * resolved.
174 * @param flags 0 or one or more of
175 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
176 * .
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800177 * @return Whether an activity was found. If false, the preference was
Sunny Shao7e866b62019-08-09 11:42:04 +0800178 * removed.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800179 */
180 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
181 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800182
Bonian Chen5e65da02019-11-08 07:40:35 +0800183 final Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800184 if (preference == null) {
185 return false;
186 }
Ying Wanga7188322010-01-04 18:45:10 -0800187
Bonian Chen5e65da02019-11-08 07:40:35 +0800188 final Intent intent = preference.getIntent();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800189 if (intent != null) {
190 // Find the activity that is in the system image
Bonian Chen5e65da02019-11-08 07:40:35 +0800191 final PackageManager pm = context.getPackageManager();
192 final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
193 final int listSize = list.size();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800194 for (int i = 0; i < listSize; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800195 final ResolveInfo resolveInfo = list.get(i);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800196 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
197 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800198
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800199 // Replace the intent with this specific activity
200 preference.setIntent(new Intent().setClassName(
201 resolveInfo.activityInfo.packageName,
202 resolveInfo.activityInfo.name));
203
204 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
205 // Set the preference title to the activity's label
206 preference.setTitle(resolveInfo.loadLabel(pm));
207 }
Ying Wanga7188322010-01-04 18:45:10 -0800208
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800209 return true;
210 }
211 }
212 }
213
214 // Did not find a matching activity, so remove the preference
215 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800216
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900217 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800218 }
Ying Wanga7188322010-01-04 18:45:10 -0800219
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200220 /**
Ying Wanga7188322010-01-04 18:45:10 -0800221 * Returns true if Monkey is running.
222 */
223 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700224 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800225 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700226
227 /**
228 * Returns whether the device is voice-capable (meaning, it is also a phone).
229 */
230 public static boolean isVoiceCapable(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800231 final TelephonyManager telephony =
Amith Yamasani60133dd2010-09-11 14:17:31 -0700232 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
233 return telephony != null && telephony.isVoiceCapable();
234 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800235
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800236 /**
237 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
238 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900239 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800240 */
241 public static String getWifiIpAddresses(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800242 final WifiManager wifiManager = context.getSystemService(WifiManager.class);
243 final Network currentNetwork = wifiManager.getCurrentNetwork();
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700244 if (currentNetwork != null) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800245 final ConnectivityManager cm = (ConnectivityManager)
Sunny Shao7e866b62019-08-09 11:42:04 +0800246 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800247 final LinkProperties prop = cm.getLinkProperties(currentNetwork);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700248 return formatIpAddresses(prop);
249 }
250 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700251 }
252
Amith Yamasani6822b742011-10-17 16:41:00 -0700253 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800254 if (prop == null) return null;
Chiachang Wang003e27d2021-03-18 15:01:03 +0800255 final Iterator<LinkAddress> iter = prop.getAllLinkAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800256 // If there are no entries, return null
257 if (!iter.hasNext()) return null;
258 // Concatenate all available addresses, comma separated
259 String addresses = "";
260 while (iter.hasNext()) {
Chiachang Wang003e27d2021-03-18 15:01:03 +0800261 addresses += iter.next().getAddress().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900262 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800263 }
264 return addresses;
265 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900266
267 public static Locale createLocaleFromString(String localeStr) {
268 // TODO: is there a better way to actually construct a locale that will match?
269 // The main problem is, on top of Java specs, locale.toString() and
270 // new Locale(locale.toString()).toString() do not return equal() strings in
271 // many cases, because the constructor takes the only string as the language
272 // code. So : new Locale("en", "US").toString() => "en_US"
273 // And : new Locale("en_US").toString() => "en_us"
Sunny Shao7e866b62019-08-09 11:42:04 +0800274 if (null == localeStr)
Jean Chalard71ad1f42011-05-12 15:06:16 +0900275 return Locale.getDefault();
Bonian Chen5e65da02019-11-08 07:40:35 +0800276 final String[] brokenDownLocale = localeStr.split("_", 3);
Jean Chalard71ad1f42011-05-12 15:06:16 +0900277 // split may not return a 0-length array.
278 if (1 == brokenDownLocale.length) {
279 return new Locale(brokenDownLocale[0]);
280 } else if (2 == brokenDownLocale.length) {
281 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
282 } else {
283 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
284 }
285 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700286
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900287 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
288 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
289 }
290
Mill Chenad99e2e2020-10-21 16:32:56 +0800291 /**
292 * Return true if battery is present.
293 */
294 public static boolean isBatteryPresent(Context context) {
295 Intent batteryBroadcast = context.registerReceiver(null /* receiver */,
296 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
297 return isBatteryPresent(batteryBroadcast);
298 }
299
Amith Yamasania4379d62011-07-22 10:34:58 -0700300 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700301 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700302 }
303
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700304 /**
305 * Prepare a custom preferences layout, moving padding to {@link ListView}
306 * when outside scrollbars are requested. Usually used to display
307 * {@link ListView} and {@link TabWidget} with correct padding.
308 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700309 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800310 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700311 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700312 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700313 final Resources res = list.getResources();
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700314 final int paddingBottom = res.getDimensionPixelSize(
315 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700316
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700317 if (parent instanceof PreferenceFrameLayout) {
318 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700319 }
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800320 list.setPaddingRelative(0 /* start */, 0 /* top */, 0 /* end */, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700321 }
322 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700323
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700324 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700325 final Resources res = view.getResources();
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700326
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800327 final int paddingStart = additive ? view.getPaddingStart() : 0;
328 final int paddingEnd = additive ? view.getPaddingEnd() : 0;
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700329 final int paddingBottom = res.getDimensionPixelSize(
330 com.android.internal.R.dimen.preference_fragment_padding_bottom);
331
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700332 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700333 }
334
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700335 public static String getMeProfileName(Context context, boolean full) {
336 if (full) {
337 return getProfileDisplayName(context);
338 } else {
339 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700340 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700341 }
342
343 private static String getShorterNameIfPossible(Context context) {
344 final String given = getLocalProfileGivenName(context);
345 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
346 }
347
348 private static String getLocalProfileGivenName(Context context) {
349 final ContentResolver cr = context.getContentResolver();
350
351 // Find the raw contact ID for the local ME profile raw contact.
352 final long localRowProfileId;
353 final Cursor localRawProfile = cr.query(
354 Profile.CONTENT_RAW_CONTACTS_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800355 new String[] {RawContacts._ID},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700356 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
357 RawContacts.ACCOUNT_NAME + " IS NULL",
358 null, null);
359 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700360
361 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700362 if (!localRawProfile.moveToFirst()) {
363 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700364 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700365 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700366 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700367 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700368 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700369
370 // Find the structured name for the raw contact.
371 final Cursor structuredName = cr.query(
372 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
Sunny Shao7e866b62019-08-09 11:42:04 +0800373 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
374 CommonDataKinds.StructuredName.FAMILY_NAME},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700375 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
376 null, null);
377 if (structuredName == null) return null;
378
379 try {
380 if (!structuredName.moveToFirst()) {
381 return null;
382 }
383 String partialName = structuredName.getString(0);
384 if (TextUtils.isEmpty(partialName)) {
385 partialName = structuredName.getString(1);
386 }
387 return partialName;
388 } finally {
389 structuredName.close();
390 }
391 }
392
393 private static final String getProfileDisplayName(Context context) {
394 final ContentResolver cr = context.getContentResolver();
395 final Cursor profile = cr.query(Profile.CONTENT_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800396 new String[] {Profile.DISPLAY_NAME}, null, null, null);
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700397 if (profile == null) return null;
398
399 try {
400 if (!profile.moveToFirst()) {
401 return null;
402 }
403 return profile.getString(0);
404 } finally {
405 profile.close();
406 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700407 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700408
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700409 public static boolean hasMultipleUsers(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800410 return context.getSystemService(UserManager.class)
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700411 .getUsers().size() > 1;
412 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700413
414 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100415 * Returns the managed profile of the current user or {@code null} if none is found or a profile
416 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100417 */
418 public static UserHandle getManagedProfile(UserManager userManager) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800419 final List<UserHandle> userProfiles = userManager.getUserProfiles();
Aarthi Balachanderd0f83592018-07-10 17:04:53 -0700420 for (UserHandle profile : userProfiles) {
Adam Bookatz30dafd42021-10-01 00:15:32 -0700421 if (profile.getIdentifier() == userManager.getProcessUserId()) {
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100422 continue;
423 }
424 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
425 if (userInfo.isManagedProfile()) {
426 return profile;
427 }
428 }
429 return null;
430 }
431
432 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100433 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
434 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
435 */
436 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
437 // TODO: Call getManagedProfileId from here once Robolectric supports
438 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
439 // yet another implementation that loops over user profiles in this method). In the meantime
440 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
441 // used for Settings Robolectric tests).
442 final int myUserId = UserHandle.myUserId();
Bonian Chen5e65da02019-11-08 07:40:35 +0800443 final List<UserInfo> profiles = userManager.getProfiles(myUserId);
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100444 final int count = profiles.size();
445 for (int i = 0; i < count; i++) {
446 final UserInfo profile = profiles.get(i);
447 if (profile.isManagedProfile()
448 && profile.getUserHandle().getIdentifier() != myUserId) {
449 return profile.getUserHandle();
450 }
451 }
452 return null;
453 }
454
455 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000456 * Retrieves the id for the given user's managed profile.
457 *
458 * @return the managed profile id or UserHandle.USER_NULL if there is none.
459 */
460 public static int getManagedProfileId(UserManager um, int parentUserId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800461 final int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700462 for (int profileId : profileIds) {
463 if (profileId != parentUserId) {
464 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000465 }
466 }
467 return UserHandle.USER_NULL;
468 }
469
Arc Wang54306822021-04-29 18:54:10 +0800470 /** Returns user ID of current user, throws IllegalStateException if it's not available. */
471 public static int getCurrentUserId(UserManager userManager, boolean isWorkProfile)
472 throws IllegalStateException {
473 if (isWorkProfile) {
474 final UserHandle managedUserHandle = getManagedProfile(userManager);
475 if (managedUserHandle == null) {
476 throw new IllegalStateException("Work profile user ID is not available.");
477 }
478 return managedUserHandle.getIdentifier();
479 }
480 return UserHandle.myUserId();
481 }
482
Clara Bayarri462cce12016-02-18 12:09:21 +0000483 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100484 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000485 * <p>
486 * User would be retrieved in this order:
487 * <ul>
488 * <li> If this activity is launched from other user, return that user id.
489 * <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 +0800490 * extra in the arguments or intent extras.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000491 * <li> Otherwise, return UserHandle.myUserId().
492 * </ul>
493 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100494 * Note: This is secure in the sense that it only returns a target user different to the current
495 * one if the app launching this activity is the Settings app itself, running in the same user
496 * 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 +0100497 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100498 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000499 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800500 final UserHandle currentUser = new UserHandle(UserHandle.myUserId());
501 final IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100502 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800503 final String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
504 final boolean launchedFromSettingsApp =
505 SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100506
Bonian Chen5e65da02019-11-08 07:40:35 +0800507 final UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100508 am.getLaunchedFromUid(activityToken)));
509 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
510 // Check it's secure
511 if (isProfileOf(um, launchedFromUser)) {
512 return launchedFromUser;
513 }
514 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800515 final UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100516 if (extrasUser != null && !extrasUser.equals(currentUser)) {
517 // Check it's secure
518 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
519 return extrasUser;
520 }
521 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800522 final UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100523 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
524 // Check it's secure
525 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
526 return argumentsUser;
527 }
528 }
529 } catch (RemoteException e) {
530 // Should not happen
531 Log.v(TAG, "Could not talk to activity manager.", e);
532 }
533 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000534 }
535
536 /**
537 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
538 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
539 */
Sunny Shao7e866b62019-08-09 11:42:04 +0800540 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
Tony Mak8f41b9b2016-11-23 11:36:18 +0000541 if (bundle == null) {
542 return null;
543 }
544 final UserHandle user = bundle.getParcelable(EXTRA_USER);
545 if (user != null) {
546 return user;
547 }
548 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
549 if (userId != -1) {
550 return UserHandle.of(userId);
551 }
552 return null;
553 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100554
Sunny Shao7e866b62019-08-09 11:42:04 +0800555 /**
556 * Returns true if the user provided is in the same profiles group as the current user.
557 */
558 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
559 if (um == null || otherUser == null) return false;
560 return (UserHandle.myUserId() == otherUser.getIdentifier())
561 || um.getUserProfiles().contains(otherUser);
562 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530563
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100564 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800565 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
566 * @param userManager Instance of UserManager
Sunny Shao7e866b62019-08-09 11:42:04 +0800567 * @param checkUser The user to check the existence of.
Amith Yamasani45f86232014-11-19 17:12:46 -0800568 * @return UserInfo of the user or null for non-existent user.
569 */
570 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
Colin Cross38fa1852020-08-27 04:12:26 +0000571 final List<UserInfo> users = userManager.getAliveUsers();
Amith Yamasani45f86232014-11-19 17:12:46 -0800572 final int checkUserId = checkUser.getIdentifier();
573 for (UserInfo user : users) {
574 if (user.id == checkUserId) {
575 return user;
576 }
577 }
578 return null;
579 }
580
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000581 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
582 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
583 com.android.internal.R.styleable.Preference,
584 com.android.internal.R.attr.preferenceCategoryStyle, 0);
585 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
586 0);
587 a.recycle();
588 return inflater.inflate(resId, parent, false);
589 }
590
Christopher Tatea08a2252015-07-01 16:52:43 -0700591 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800592 final List<IntentFilterVerificationInfo> iviList =
593 pm.getIntentFilterVerifications(packageName);
594 final List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
Christopher Tatea08a2252015-07-01 16:52:43 -0700595
Bonian Chen5e65da02019-11-08 07:40:35 +0800596 final ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800597 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700598 for (IntentFilterVerificationInfo ivi : iviList) {
599 for (String host : ivi.getDomains()) {
600 result.add(host);
601 }
602 }
603 }
604 if (filters != null && filters.size() > 0) {
605 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700606 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
607 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
Sunny Shao7e866b62019-08-09 11:42:04 +0800608 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700609 result.addAll(filter.getHostsList());
610 }
611 }
612 }
613 return result;
614 }
615
Sudheer Shankabc956302015-04-09 12:19:53 +0100616 /**
617 * Returns the application info of the currently installed MDM package.
618 */
619 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800620 final DevicePolicyManager dpm =
Sudheer Shankabc956302015-04-09 12:19:53 +0100621 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800622 final ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
Sudheer Shankabc956302015-04-09 12:19:53 +0100623 if (mdmPackage == null) {
624 return null;
625 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800626 final String mdmPackageName = mdmPackage.getPackageName();
Sudheer Shankabc956302015-04-09 12:19:53 +0100627 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800628 final IPackageManager ipm = AppGlobals.getPackageManager();
629 final ApplicationInfo mdmApplicationInfo =
Sudheer Shankabc956302015-04-09 12:19:53 +0100630 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
631 return mdmApplicationInfo;
632 } catch (RemoteException e) {
633 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
634 + ", userId " + profileId, e);
635 return null;
636 }
637 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400638
639 public static boolean isBandwidthControlEnabled() {
640 final INetworkManagementService netManager = INetworkManagementService.Stub
641 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
642 try {
643 return netManager.isBandwidthControlEnabled();
644 } catch (RemoteException e) {
645 return false;
646 }
647 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400648
649 /**
650 * Returns an accessible SpannableString.
Sunny Shao7e866b62019-08-09 11:42:04 +0800651 * @param displayText the text to display
Julia Reynoldsce25af42015-07-08 16:56:31 -0400652 * @param accessibileText the text text-to-speech engines should read
653 */
654 public static SpannableString createAccessibleSequence(CharSequence displayText,
655 String accessibileText) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800656 final SpannableString str = new SpannableString(displayText);
Julia Reynoldsce25af42015-07-08 16:56:31 -0400657 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
658 displayText.length(),
659 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
660 return str;
661 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700662
Clara Bayarrife432e82015-10-12 12:07:02 +0100663 /**
Jeff Sharkey219ec912017-12-19 14:57:39 -0700664 * Returns the user id present in the bundle with
665 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
Clara Bayarrife432e82015-10-12 12:07:02 +0100666 *
Jeff Sharkey219ec912017-12-19 14:57:39 -0700667 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800668 * current user group.
Clara Bayarrife432e82015-10-12 12:07:02 +0100669 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000670 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700671 return getUserIdFromBundle(context, bundle, false);
672 }
673
674 /**
675 * Returns the user id present in the bundle with
676 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
677 *
678 * @param isInternal indicating if the caller is "internal" to the system,
Sunny Shao7e866b62019-08-09 11:42:04 +0800679 * meaning we're willing to trust extras like
Kevin Chynb13bc502020-07-20 23:35:21 -0700680 * {@link ChooseLockSettingsHelper#EXTRA_KEY_ALLOW_ANY_USER}.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700681 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800682 * current user group.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700683 */
684 public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
Clara Bayarrife432e82015-10-12 12:07:02 +0100685 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +0000686 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +0100687 }
Jeff Sharkey219ec912017-12-19 14:57:39 -0700688 final boolean allowAnyUser = isInternal
Kevin Chynb13bc502020-07-20 23:35:21 -0700689 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_KEY_ALLOW_ANY_USER, false);
Bonian Chen5e65da02019-11-08 07:40:35 +0800690 final int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700691 if (userId == LockPatternUtils.USER_FRP) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700692 return allowAnyUser ? userId : enforceSystemUser(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700693 } else {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700694 return allowAnyUser ? userId : enforceSameOwner(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700695 }
696 }
697
698 /**
699 * Returns the given user id if the current user is the system user.
700 *
701 * @throws SecurityException if the current user is not the system user.
702 */
703 public static int enforceSystemUser(Context context, int userId) {
704 if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
705 return userId;
706 }
707 throw new SecurityException("Given user id " + userId + " must only be used from "
708 + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100709 }
710
711 /**
712 * Returns the given user id if it belongs to the current user.
713 *
714 * @throws SecurityException if the given userId does not belong to the current user group.
715 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000716 public static int enforceSameOwner(Context context, int userId) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800717 final UserManager um = context.getSystemService(UserManager.class);
Ricky Wai72500162016-06-07 16:54:25 +0100718 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
719 if (ArrayUtils.contains(profileIds, userId)) {
720 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +0100721 }
Ricky Wai72500162016-06-07 16:54:25 +0100722 throw new SecurityException("Given user id " + userId + " does not belong to user "
723 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100724 }
725
Benjamin Franz194300d2016-01-13 12:16:25 +0000726 /**
727 * Returns the effective credential owner of the calling user.
728 */
729 public static int getCredentialOwnerUserId(Context context) {
730 return getCredentialOwnerUserId(context, UserHandle.myUserId());
731 }
732
733 /**
734 * Returns the user id of the credential owner of the given user id.
735 */
736 public static int getCredentialOwnerUserId(Context context, int userId) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800737 final UserManager um = context.getSystemService(UserManager.class);
Benjamin Franz194300d2016-01-13 12:16:25 +0000738 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700739 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500740
Alex Johnston403c3302020-01-07 15:40:05 +0000741 /**
742 * Returns the credential type of the given user id.
743 */
744 public static @LockPatternUtils.CredentialType int getCredentialType(Context context,
745 int userId) {
746 final LockPatternUtils lpu = new LockPatternUtils(context);
747 return lpu.getCredentialTypeForUser(userId);
748 }
749
Jason Monkb37e2882016-01-11 14:27:20 -0500750 private static final StringBuilder sBuilder = new StringBuilder(50);
751 private static final java.util.Formatter sFormatter = new java.util.Formatter(
752 sBuilder, Locale.getDefault());
753
754 public static String formatDateRange(Context context, long start, long end) {
755 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
756
757 synchronized (sBuilder) {
758 sBuilder.setLength(0);
759 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
760 .toString();
761 }
762 }
Jason Monk91e2f892016-02-23 15:31:09 -0500763
Bernard Chau88d523b2016-04-14 15:08:28 +0100764 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100765 int userId) {
766 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
767 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
768 context.startActivity(intent);
769 return true;
770 }
771 return false;
772 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700773
Rubin Xu3231afe2016-08-24 10:15:07 +0100774 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
775 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800776 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100777 ActivityManager.FLAG_AND_LOCKED)) {
778 return false;
779 }
780 } catch (RemoteException e) {
781 return false;
782 }
783 if (!(new LockPatternUtils(context)).isSecure(userId)) {
784 return false;
785 }
Robin Leecccf3242017-02-10 15:32:49 +0000786 return confirmWorkProfileCredentials(context, userId);
787 }
788
Robin Leecccf3242017-02-10 15:32:49 +0000789 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100790 final KeyguardManager km = (KeyguardManager) context.getSystemService(
791 Context.KEYGUARD_SERVICE);
792 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
793 if (unlockIntent != null) {
794 context.startActivity(unlockIntent);
795 return true;
796 } else {
797 return false;
798 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100799 }
800
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700801 public static CharSequence getApplicationLabel(Context context, String packageName) {
802 try {
803 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
804 packageName,
805 PackageManager.MATCH_DISABLED_COMPONENTS
Sunny Shao7e866b62019-08-09 11:42:04 +0800806 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700807 return appInfo.loadLabel(context.getPackageManager());
808 } catch (PackageManager.NameNotFoundException e) {
Raff Tsai376ce872020-01-06 00:42:35 +0800809 Log.e(TAG, "Unable to find info for package: " + packageName);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700810 }
811 return null;
812 }
Jason Monk75199542016-05-06 15:09:32 -0400813
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600814 public static boolean isPackageDirectBootAware(Context context, String packageName) {
815 try {
816 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
817 packageName, 0);
818 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
819 } catch (NameNotFoundException ignored) {
820 }
821 return false;
822 }
Andre Lago3e398c82016-07-25 14:12:28 +0100823
824 /**
825 * Returns a context created from the given context for the given user, or null if it fails
826 */
827 public static Context createPackageContextAsUser(Context context, int userId) {
828 try {
829 return context.createPackageContextAsUser(
830 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
831 } catch (PackageManager.NameNotFoundException e) {
832 Log.e(TAG, "Failed to create user context", e);
833 }
834 return null;
835 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600836
837 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
838 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800839 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600840 } else {
841 return null;
842 }
843 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800844
Kevin Chyn82792cc2017-07-20 00:15:44 -0700845 public static boolean hasFingerprintHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800846 final FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
Kevin Chyn82792cc2017-07-20 00:15:44 -0700847 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
848 }
849
Kevin Chyn4882e872018-06-25 17:58:31 -0700850 public static FaceManager getFaceManagerOrNull(Context context) {
851 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
852 return (FaceManager) context.getSystemService(Context.FACE_SERVICE);
853 } else {
854 return null;
855 }
856 }
857
858 public static boolean hasFaceHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800859 final FaceManager faceManager = getFaceManagerOrNull(context);
Kevin Chyn4882e872018-06-25 17:58:31 -0700860 return faceManager != null && faceManager.isHardwareDetected();
861 }
862
Daniel Nishi31027da2017-01-19 14:03:57 -0800863 /**
Mill Chen7edebee2021-04-09 23:14:27 +0800864 * Return true if the device supports multiple biometrics authentications.
865 */
866 public static boolean isMultipleBiometricsSupported(Context context) {
867 return hasFingerprintHardware(context) && hasFaceHardware(context);
868 }
869
870 /**
Daniel Nishi31027da2017-01-19 14:03:57 -0800871 * Launches an intent which may optionally have a user id defined.
872 * @param fragment Fragment to use to launch the activity.
Sunny Shao7e866b62019-08-09 11:42:04 +0800873 * @param intent Intent to launch.
Daniel Nishi31027da2017-01-19 14:03:57 -0800874 */
875 public static void launchIntent(Fragment fragment, Intent intent) {
876 try {
877 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
878
879 if (userId == -1) {
880 fragment.startActivity(intent);
881 } else {
882 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
883 }
884 } catch (ActivityNotFoundException e) {
885 Log.w(TAG, "No activity found for " + intent);
886 }
887 }
888
Christine Franksc6890ab2017-06-23 14:28:21 -0700889 public static boolean isDemoUser(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800890 return UserManager.isDeviceInDemoMode(context)
891 && context.getSystemService(UserManager.class).isDemoUser();
Christine Franksc6890ab2017-06-23 14:28:21 -0700892 }
893
Justin Klaassen30257272017-08-08 21:58:05 -0700894 public static ComponentName getDeviceOwnerComponent(Context context) {
895 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
896 Context.DEVICE_POLICY_SERVICE);
897 return dpm.getDeviceOwnerComponentOnAnyUser();
Christine Franks14782222017-01-23 16:44:02 -0800898 }
Daniel Nishidfed8a22017-01-19 16:32:41 -0800899
900 /**
901 * Returns if a given user is a profile of another user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800902 * @param user The user whose profiles wibe checked.
Daniel Nishidfed8a22017-01-19 16:32:41 -0800903 * @param profile The (potential) profile.
904 * @return if the profile is actually a profile
905 */
906 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
907 return user.id == profile.id ||
908 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
909 && user.profileGroupId == profile.profileGroupId);
910 }
Daniel Nishi9f60f422017-02-15 15:25:48 -0800911
912 /**
913 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
914 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
915 */
916 @Nullable
917 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
918 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
919 VolumeInfo.ID_PRIVATE_INTERNAL);
Bonian Chen5e65da02019-11-08 07:40:35 +0800920 final VolumeInfo volume = sm.findVolumeById(volumeId);
Daniel Nishi9f60f422017-02-15 15:25:48 -0800921 return isVolumeValid(volume) ? volume : null;
922 }
923
jackqdyuleiddba9662017-03-08 19:35:02 -0800924 /**
jackqdyulei00015fb2017-08-22 11:25:30 -0700925 * Return {@code true} if the supplied package is device owner or profile owner of at
926 * least one user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800927 * @param userManager used to get profile owner app for each user
jackqdyulei00015fb2017-08-22 11:25:30 -0700928 * @param devicePolicyManager used to check whether it is device owner app
Sunny Shao7e866b62019-08-09 11:42:04 +0800929 * @param packageName package to check about
jackqdyulei00015fb2017-08-22 11:25:30 -0700930 */
931 public static boolean isProfileOrDeviceOwner(UserManager userManager,
Fan Zhangaab36de2018-03-30 16:58:28 -0700932 DevicePolicyManager devicePolicyManager, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800933 final List<UserInfo> userInfos = userManager.getUsers();
jackqdyulei00015fb2017-08-22 11:25:30 -0700934 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
935 return true;
936 }
937 for (int i = 0, size = userInfos.size(); i < size; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800938 final ComponentName cn = devicePolicyManager
939 .getProfileOwnerAsUser(userInfos.get(i).id);
jackqdyulei00015fb2017-08-22 11:25:30 -0700940 if (cn != null && cn.getPackageName().equals(packageName)) {
941 return true;
942 }
943 }
944 return false;
945 }
946
947 /**
Alex Johnston341f9952020-02-26 15:54:11 +0000948 * Return {@code true} if the supplied package is the device owner or profile owner of a
949 * given user.
950 *
951 * @param devicePolicyManager used to check whether it is device owner and profile owner app
952 * @param packageName package to check about
953 * @param userId the if of the relevant user
954 */
955 public static boolean isProfileOrDeviceOwner(DevicePolicyManager devicePolicyManager,
956 String packageName, int userId) {
957 if ((devicePolicyManager.getDeviceOwnerUserId() == userId)
958 && devicePolicyManager.isDeviceOwnerApp(packageName)) {
959 return true;
960 }
961 final ComponentName cn = devicePolicyManager.getProfileOwnerAsUser(userId);
962 if (cn != null && cn.getPackageName().equals(packageName)) {
963 return true;
964 }
965 return false;
966 }
967
968 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800969 * Return the resource id to represent the install status for an app
970 */
971 @StringRes
972 public static int getInstallationStatus(ApplicationInfo info) {
973 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
974 return R.string.not_installed;
975 }
976 return info.enabled ? R.string.installed : R.string.disabled;
977 }
978
Daniel Nishi9f60f422017-02-15 15:25:48 -0800979 private static boolean isVolumeValid(VolumeInfo volume) {
980 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
981 && volume.isMountedReadable();
982 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700983
PMS2263a05602017-06-14 07:10:15 +0000984 public static void setEditTextCursorPosition(EditText editText) {
985 editText.setSelection(editText.getText().length());
986 }
Felipe Lemebd884502017-09-15 18:16:21 -0700987
988 /**
jasonwshsu9b284a92021-04-20 15:19:15 +0800989 * Gets the adaptive icon with a drawable that wrapped with an adaptive background using {@code
990 * backgroundColor} if it is not a {@link AdaptiveIconDrawable}
991 *
992 * If the given {@code icon} is too big, it will be auto scaled down to to avoid crashing
993 * Settings.
Felipe Lemebd884502017-09-15 18:16:21 -0700994 */
jasonwshsu9b284a92021-04-20 15:19:15 +0800995 public static Drawable getAdaptiveIcon(Context context, Drawable icon,
996 @ColorInt int backgroundColor) {
997 Drawable adaptiveIcon = getSafeIcon(icon);
998
999 if (!(adaptiveIcon instanceof AdaptiveIconDrawable)) {
1000 adaptiveIcon = new AdaptiveIcon(context, adaptiveIcon);
1001 ((AdaptiveIcon) adaptiveIcon).setBackgroundColor(backgroundColor);
1002 }
1003
1004 return adaptiveIcon;
1005 }
1006
1007 /**
1008 * Gets the icon with a drawable that is scaled down to to avoid crashing Settings if it's too
1009 * big and not a {@link VectorDrawable}.
1010 */
1011 public static Drawable getSafeIcon(Drawable icon) {
Felipe Lemebd884502017-09-15 18:16:21 -07001012 Drawable safeIcon = icon;
jasonwshsu9b284a92021-04-20 15:19:15 +08001013
Phil Weaver5a3e02d2018-03-08 17:38:46 -08001014 if ((icon != null) && !(icon instanceof VectorDrawable)) {
menghanlia1674782021-08-24 08:45:46 +08001015 safeIcon = getSafeDrawable(icon,
1016 /* MAX_DRAWABLE_SIZE */ 600, /* MAX_DRAWABLE_SIZE */ 600);
Felipe Lemebd884502017-09-15 18:16:21 -07001017 }
jasonwshsu9b284a92021-04-20 15:19:15 +08001018
1019 return safeIcon;
Felipe Lemebd884502017-09-15 18:16:21 -07001020 }
1021
1022 /**
1023 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
1024 *
Sunny Shao7e866b62019-08-09 11:42:04 +08001025 * @param original original drawable, typically an app icon.
1026 * @param maxWidth maximum width, in pixels.
Felipe Lemebd884502017-09-15 18:16:21 -07001027 * @param maxHeight maximum height, in pixels.
1028 */
jasonwshsu9b284a92021-04-20 15:19:15 +08001029 private static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
Felipe Lemebd884502017-09-15 18:16:21 -07001030 final int actualWidth = original.getMinimumWidth();
1031 final int actualHeight = original.getMinimumHeight();
1032
1033 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
1034 return original;
1035 }
1036
Bonian Chen5e65da02019-11-08 07:40:35 +08001037 final float scaleWidth = ((float) maxWidth) / actualWidth;
1038 final float scaleHeight = ((float) maxHeight) / actualHeight;
1039 final float scale = Math.min(scaleWidth, scaleHeight);
Felipe Lemebd884502017-09-15 18:16:21 -07001040 final int width = (int) (actualWidth * scale);
1041 final int height = (int) (actualHeight * scale);
1042
1043 final Bitmap bitmap;
1044 if (original instanceof BitmapDrawable) {
1045 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
1046 height, false);
1047 } else {
Jason Chiuc78c54a2019-02-13 16:07:57 +08001048 bitmap = createBitmap(original, width, height);
Felipe Lemebd884502017-09-15 18:16:21 -07001049 }
1050 return new BitmapDrawable(null, bitmap);
1051 }
jackqdyuleifde637f2018-01-02 14:51:01 -08001052
1053 /**
Jason Chiuc78c54a2019-02-13 16:07:57 +08001054 * Create an Icon pointing to a drawable.
Jason Chiu1217bbe2019-01-24 16:32:31 +08001055 */
Jason Chiuc78c54a2019-02-13 16:07:57 +08001056 public static IconCompat createIconWithDrawable(Drawable drawable) {
1057 Bitmap bitmap;
Jason Chiu1217bbe2019-01-24 16:32:31 +08001058 if (drawable instanceof BitmapDrawable) {
Sunny Shao7e866b62019-08-09 11:42:04 +08001059 bitmap = ((BitmapDrawable)drawable).getBitmap();
Jason Chiuc78c54a2019-02-13 16:07:57 +08001060 } else {
1061 final int width = drawable.getIntrinsicWidth();
1062 final int height = drawable.getIntrinsicHeight();
1063 bitmap = createBitmap(drawable,
1064 width > 0 ? width : 1,
1065 height > 0 ? height : 1);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001066 }
Jason Chiuc78c54a2019-02-13 16:07:57 +08001067 return IconCompat.createWithBitmap(bitmap);
1068 }
Jason Chiu1217bbe2019-01-24 16:32:31 +08001069
clownshen24827d32019-03-29 20:22:02 +08001070 /**
1071 * Creates a drawable with specified width and height.
1072 */
1073 public static Bitmap createBitmap(Drawable drawable, int width, int height) {
Jason Chiuc78c54a2019-02-13 16:07:57 +08001074 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001075 final Canvas canvas = new Canvas(bitmap);
1076 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1077 drawable.draw(canvas);
1078 return bitmap;
1079 }
1080
1081 /**
jackqdyuleifde637f2018-01-02 14:51:01 -08001082 * Get the {@link Drawable} that represents the app icon
1083 */
1084 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
1085 PackageManager packageManager, String packageName, int userId) {
1086 try {
Tony Mak4e292812018-03-19 15:37:21 +00001087 final ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
1088 packageName, PackageManager.GET_META_DATA, userId);
jackqdyuleifde637f2018-01-02 14:51:01 -08001089 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
1090 } catch (PackageManager.NameNotFoundException e) {
1091 return packageManager.getDefaultActivityIcon();
1092 }
1093 }
Raff Tsai2928cd42018-11-05 16:10:19 +08001094
1095 /** Returns true if the current package is installed & enabled. */
1096 public static boolean isPackageEnabled(Context context, String packageName) {
1097 try {
1098 return context.getPackageManager().getApplicationInfo(packageName, 0).enabled;
1099 } catch (Exception e) {
1100 Log.e(TAG, "Error while retrieving application info for package " + packageName, e);
1101 }
1102 return false;
1103 }
markchien1dd1d792019-01-11 16:18:20 +08001104
1105 /** Get {@link Resources} by subscription id if subscription id is valid. */
1106 public static Resources getResourcesForSubId(Context context, int subId) {
1107 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1108 return SubscriptionManager.getResourcesForSubId(context, subId);
1109 } else {
1110 return context.getResources();
1111 }
1112 }
Ng Zhi Anb97bdc32019-02-01 12:39:31 -08001113
1114 /**
1115 * Returns true if SYSTEM_ALERT_WINDOW permission is available.
1116 * Starting from Q, SYSTEM_ALERT_WINDOW is disabled on low ram phones.
1117 */
1118 public static boolean isSystemAlertWindowEnabled(Context context) {
1119 // SYSTEM_ALERT_WINDOW is disabled on on low ram devices starting from Q
1120 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
1121 return !(am.isLowRamDevice() && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q));
1122 }
tmfangaed8f362019-03-18 16:56:09 +08001123
1124 /**
1125 * Adds a shadow appear/disappear animation to action bar scroll.
1126 *
1127 * <p/>
1128 * This method must be called after {@link Fragment#onCreate(Bundle)}.
1129 */
1130 public static void setActionBarShadowAnimation(Activity activity, Lifecycle lifecycle,
1131 View scrollView) {
1132 if (activity == null) {
1133 Log.w(TAG, "No activity, cannot style actionbar.");
1134 return;
1135 }
1136 final ActionBar actionBar = activity.getActionBar();
1137 if (actionBar == null) {
1138 Log.w(TAG, "No actionbar, cannot style actionbar.");
1139 return;
1140 }
1141 actionBar.setElevation(0);
1142
1143 if (lifecycle != null && scrollView != null) {
1144 ActionBarShadowController.attachToView(activity, lifecycle, scrollView);
1145 }
1146 }
Raff Tsaiafd494d2019-10-16 15:25:21 +08001147
1148 /**
1149 * Return correct target fragment based on argument
1150 *
1151 * @param activity the activity target fragment will be launched.
1152 * @param fragmentName initial target fragment name.
1153 * @param args fragment launch arguments.
1154 */
1155 public static Fragment getTargetFragment(Activity activity, String fragmentName, Bundle args) {
1156 Fragment f = null;
Raff Tsai84327f62019-11-15 11:02:25 +08001157 final boolean isPersonal = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001158 == ProfileSelectFragment.ProfileType.PERSONAL : false;
Raff Tsai84327f62019-11-15 11:02:25 +08001159 final boolean isWork = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001160 == ProfileSelectFragment.ProfileType.WORK : false;
Jason Chiuc38978f2021-06-29 21:10:32 +08001161 try {
1162 if (activity.getSystemService(UserManager.class).getUserProfiles().size() > 1
1163 && ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName) != null
1164 && !isWork && !isPersonal) {
1165 f = Fragment.instantiate(activity,
1166 ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName), args);
1167 } else {
1168 f = Fragment.instantiate(activity, fragmentName, args);
1169 }
1170 } catch (Exception e) {
1171 Log.e(TAG, "Unable to get target fragment", e);
Raff Tsaiafd494d2019-10-16 15:25:21 +08001172 }
1173 return f;
1174 }
Yanting Yang96127fe2020-03-20 12:04:09 +08001175
1176 /**
1177 * Returns true if current binder uid is Settings Intelligence.
1178 */
1179 public static boolean isSettingsIntelligence(Context context) {
1180 final int callingUid = Binder.getCallingUid();
1181 final String callingPackage = context.getPackageManager().getPackagesForUid(callingUid)[0];
1182 final boolean isSettingsIntelligence = TextUtils.equals(callingPackage,
1183 context.getString(R.string.config_settingsintelligence_package_name));
1184 return isSettingsIntelligence;
1185 }
Jason Chiu8ac1e4d2020-05-11 16:13:47 +08001186
1187 /**
1188 * Returns true if the night mode is enabled.
1189 */
1190 public static boolean isNightMode(Context context) {
1191 final int currentNightMode =
1192 context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1193 return currentNightMode == Configuration.UI_MODE_NIGHT_YES;
1194 }
Tim Pengdf467882020-06-24 13:10:01 +08001195
1196 /**
1197 * Returns a bitmap with rounded corner.
1198 *
1199 * @param context application context.
1200 * @param source bitmap to apply round corner.
1201 * @param cornerRadius corner radius value.
1202 */
1203 public static Bitmap convertCornerRadiusBitmap(@NonNull Context context,
1204 @NonNull Bitmap source, @NonNull float cornerRadius) {
1205 final Bitmap roundedBitmap = Bitmap.createBitmap(source.getWidth(), source.getHeight(),
1206 Bitmap.Config.ARGB_8888);
1207 final RoundedBitmapDrawable drawable =
1208 RoundedBitmapDrawableFactory.create(context.getResources(), source);
1209 drawable.setAntiAlias(true);
1210 drawable.setCornerRadius(cornerRadius);
1211 final Canvas canvas = new Canvas(roundedBitmap);
1212 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1213 drawable.draw(canvas);
1214 return roundedBitmap;
1215 }
Zoey Chen3abe48e2020-10-28 22:46:48 +08001216
Jason Chiu7d9dcea2021-04-15 16:57:22 +08001217 /**
1218 * Returns the color of homepage preference icons.
1219 */
1220 @ColorInt
1221 public static int getHomepageIconColor(Context context) {
Jason Chiu880471a2022-04-25 15:32:06 +08001222 return getColorAttrDefaultColor(context, android.R.attr.textColorPrimary);
Jason Chiu7d9dcea2021-04-15 16:57:22 +08001223 }
1224
Jason Chiu29a09e52021-10-12 17:24:34 +08001225 /**
1226 * Returns the highlight color of homepage preference icons.
1227 */
1228 @ColorInt
1229 public static int getHomepageIconColorHighlight(Context context) {
Jason Chiu880471a2022-04-25 15:32:06 +08001230 return context.getColor(R.color.accent_select_primary_text);
Jason Chiu29a09e52021-10-12 17:24:34 +08001231 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001232}