blob: 84183154236125381511245111b37ce7a8c5fad9 [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;
51import android.graphics.drawable.BitmapDrawable;
52import android.graphics.drawable.Drawable;
Phil Weaver5a3e02d2018-03-08 17:38:46 -080053import android.graphics.drawable.VectorDrawable;
Kevin Chyn4882e872018-06-25 17:58:31 -070054import android.hardware.face.FaceManager;
Jeff Sharkeyab508072016-10-11 14:25:22 -060055import android.hardware.fingerprint.FingerprintManager;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080056import android.net.ConnectivityManager;
Chiachang Wang003e27d2021-03-18 15:01:03 +080057import android.net.LinkAddress;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080058import android.net.LinkProperties;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070059import android.net.Network;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070060import android.net.wifi.WifiManager;
Amith Yamasania4379d62011-07-22 10:34:58 -070061import android.os.BatteryManager;
Yanting Yang96127fe2020-03-20 12:04:09 +080062import android.os.Binder;
Ng Zhi Anb97bdc32019-02-01 12:39:31 -080063import android.os.Build;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020064import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010065import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040066import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010067import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040068import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070069import android.os.UserHandle;
70import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080071import android.os.storage.StorageManager;
Daniel Nishi9f60f422017-02-15 15:25:48 -080072import android.os.storage.VolumeInfo;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070073import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070074import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070075import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070076import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070077import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070078import android.provider.ContactsContract.RawContacts;
markchien1dd1d792019-01-11 16:18:20 +080079import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070080import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040081import android.text.Spannable;
82import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020083import android.text.TextUtils;
Jason Monkb37e2882016-01-11 14:27:20 -050084import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040085import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070086import android.util.ArraySet;
Zoey Chen3abe48e2020-10-28 22:46:48 +080087import android.util.FeatureFlagUtils;
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
Tim Pengdf467882020-06-24 13:10:01 +080097import androidx.annotation.NonNull;
Fan Zhang23f8d592018-08-28 15:11:40 -070098import androidx.annotation.StringRes;
Jason Chiuc78c54a2019-02-13 16:07:57 +080099import androidx.core.graphics.drawable.IconCompat;
Tim Pengdf467882020-06-24 13:10:01 +0800100import androidx.core.graphics.drawable.RoundedBitmapDrawable;
101import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
Fan Zhang23f8d592018-08-28 15:11:40 -0700102import androidx.fragment.app.Fragment;
tmfangaed8f362019-03-18 16:56:09 +0800103import androidx.lifecycle.Lifecycle;
Fan Zhang23f8d592018-08-28 15:11:40 -0700104import androidx.preference.Preference;
105import androidx.preference.PreferenceGroup;
106
Ricky Wai616342b2016-04-13 10:40:22 +0100107import com.android.internal.app.UnlaunchableAppActivity;
Ricky Wai72500162016-06-07 16:54:25 +0100108import com.android.internal.util.ArrayUtils;
Rubin Xu3231afe2016-08-24 10:15:07 +0100109import com.android.internal.widget.LockPatternUtils;
Raff Tsaiafd494d2019-10-16 15:25:21 +0800110import com.android.settings.dashboard.profileselector.ProfileFragmentBridge;
Raff Tsai84327f62019-11-15 11:02:25 +0800111import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
Jeff Sharkey219ec912017-12-19 14:57:39 -0700112import com.android.settings.password.ChooseLockSettingsHelper;
tmfangaed8f362019-03-18 16:56:09 +0800113import com.android.settingslib.widget.ActionBarShadowController;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700114
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800115import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700116import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900117import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800118
Jason Monk27985e12016-01-08 14:13:05 -0500119public final class Utils extends com.android.settingslib.Utils {
120
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100121 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100122
Andras Kloczl106431e2020-05-18 14:53:07 +0100123 public static final String FILE_PROVIDER_AUTHORITY = "com.android.settings.files";
124
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800125 /**
126 * Set the preference's title to the matching activity's label.
127 */
128 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
129
Fan Zhangc3fd2892019-01-29 16:00:19 -0800130 public static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100131
Jason Monkbeb171d2015-05-21 15:24:37 -0400132 public static final String OS_PKG = "os";
133
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200134 /**
Svet Ganov864765f2019-04-05 19:00:05 -0700135 * Whether to disable the new device identifier access restrictions.
136 */
137 public static final String PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED =
138 "device_identifier_access_restrictions_disabled";
139
140 /**
Joel Galenson2118f8a2019-05-31 07:54:20 -0700141 * Whether to show the Permissions Hub.
142 */
143 public static final String PROPERTY_PERMISSIONS_HUB_ENABLED = "permissions_hub_enabled";
144
145 /**
Wei Wangedbe2cc2020-12-08 22:48:53 -0800146 * Whether to show location indicators.
147 */
148 public static final String PROPERTY_LOCATION_INDICATORS_ENABLED = "location_indicators_enabled";
149
150 /**
Wei Wanga6daf852021-01-12 10:30:25 -0800151 * Whether to show location indicator settings in developer options.
152 */
153 public static final String PROPERTY_LOCATION_INDICATOR_SETTINGS_ENABLED =
154 "location_indicator_settings_enabled";
155
Zhen Zhang48bd52e2021-03-03 13:53:34 -0800156 /** Whether or not app hibernation is enabled on the device **/
157 public static final String PROPERTY_APP_HIBERNATION_ENABLED = "app_hibernation_enabled";
158
Wei Wanga6daf852021-01-12 10:30:25 -0800159 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800160 * Finds a matching activity for a preference's intent. If a matching
161 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800162 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800163 * @param context The context.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800164 * @param parentPreferenceGroup The preference group that contains the
Sunny Shao7e866b62019-08-09 11:42:04 +0800165 * preference whose intent is being resolved.
166 * @param preferenceKey The key of the preference whose intent is being
167 * resolved.
168 * @param flags 0 or one or more of
169 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
170 * .
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800171 * @return Whether an activity was found. If false, the preference was
Sunny Shao7e866b62019-08-09 11:42:04 +0800172 * removed.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800173 */
174 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
175 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800176
Bonian Chen5e65da02019-11-08 07:40:35 +0800177 final Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800178 if (preference == null) {
179 return false;
180 }
Ying Wanga7188322010-01-04 18:45:10 -0800181
Bonian Chen5e65da02019-11-08 07:40:35 +0800182 final Intent intent = preference.getIntent();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800183 if (intent != null) {
184 // Find the activity that is in the system image
Bonian Chen5e65da02019-11-08 07:40:35 +0800185 final PackageManager pm = context.getPackageManager();
186 final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
187 final int listSize = list.size();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800188 for (int i = 0; i < listSize; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800189 final ResolveInfo resolveInfo = list.get(i);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800190 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
191 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800192
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800193 // Replace the intent with this specific activity
194 preference.setIntent(new Intent().setClassName(
195 resolveInfo.activityInfo.packageName,
196 resolveInfo.activityInfo.name));
197
198 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
199 // Set the preference title to the activity's label
200 preference.setTitle(resolveInfo.loadLabel(pm));
201 }
Ying Wanga7188322010-01-04 18:45:10 -0800202
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800203 return true;
204 }
205 }
206 }
207
208 // Did not find a matching activity, so remove the preference
209 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800210
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900211 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800212 }
Ying Wanga7188322010-01-04 18:45:10 -0800213
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200214 /**
Ying Wanga7188322010-01-04 18:45:10 -0800215 * Returns true if Monkey is running.
216 */
217 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700218 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800219 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700220
221 /**
222 * Returns whether the device is voice-capable (meaning, it is also a phone).
223 */
224 public static boolean isVoiceCapable(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800225 final TelephonyManager telephony =
Amith Yamasani60133dd2010-09-11 14:17:31 -0700226 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
227 return telephony != null && telephony.isVoiceCapable();
228 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800229
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800230 /**
231 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
232 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900233 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800234 */
235 public static String getWifiIpAddresses(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800236 final WifiManager wifiManager = context.getSystemService(WifiManager.class);
237 final Network currentNetwork = wifiManager.getCurrentNetwork();
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700238 if (currentNetwork != null) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800239 final ConnectivityManager cm = (ConnectivityManager)
Sunny Shao7e866b62019-08-09 11:42:04 +0800240 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800241 final LinkProperties prop = cm.getLinkProperties(currentNetwork);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700242 return formatIpAddresses(prop);
243 }
244 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700245 }
246
Amith Yamasani6822b742011-10-17 16:41:00 -0700247 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800248 if (prop == null) return null;
Chiachang Wang003e27d2021-03-18 15:01:03 +0800249 final Iterator<LinkAddress> iter = prop.getAllLinkAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800250 // If there are no entries, return null
251 if (!iter.hasNext()) return null;
252 // Concatenate all available addresses, comma separated
253 String addresses = "";
254 while (iter.hasNext()) {
Chiachang Wang003e27d2021-03-18 15:01:03 +0800255 addresses += iter.next().getAddress().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900256 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800257 }
258 return addresses;
259 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900260
261 public static Locale createLocaleFromString(String localeStr) {
262 // TODO: is there a better way to actually construct a locale that will match?
263 // The main problem is, on top of Java specs, locale.toString() and
264 // new Locale(locale.toString()).toString() do not return equal() strings in
265 // many cases, because the constructor takes the only string as the language
266 // code. So : new Locale("en", "US").toString() => "en_US"
267 // And : new Locale("en_US").toString() => "en_us"
Sunny Shao7e866b62019-08-09 11:42:04 +0800268 if (null == localeStr)
Jean Chalard71ad1f42011-05-12 15:06:16 +0900269 return Locale.getDefault();
Bonian Chen5e65da02019-11-08 07:40:35 +0800270 final String[] brokenDownLocale = localeStr.split("_", 3);
Jean Chalard71ad1f42011-05-12 15:06:16 +0900271 // split may not return a 0-length array.
272 if (1 == brokenDownLocale.length) {
273 return new Locale(brokenDownLocale[0]);
274 } else if (2 == brokenDownLocale.length) {
275 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
276 } else {
277 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
278 }
279 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700280
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900281 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
282 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
283 }
284
Mill Chenad99e2e2020-10-21 16:32:56 +0800285 /**
286 * Return true if battery is present.
287 */
288 public static boolean isBatteryPresent(Context context) {
289 Intent batteryBroadcast = context.registerReceiver(null /* receiver */,
290 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
291 return isBatteryPresent(batteryBroadcast);
292 }
293
Amith Yamasania4379d62011-07-22 10:34:58 -0700294 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700295 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700296 }
297
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700298 /**
299 * Prepare a custom preferences layout, moving padding to {@link ListView}
300 * when outside scrollbars are requested. Usually used to display
301 * {@link ListView} and {@link TabWidget} with correct padding.
302 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700303 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800304 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700305 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700306 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700307 final Resources res = list.getResources();
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700308 final int paddingBottom = res.getDimensionPixelSize(
309 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700310
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700311 if (parent instanceof PreferenceFrameLayout) {
312 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700313 }
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800314 list.setPaddingRelative(0 /* start */, 0 /* top */, 0 /* end */, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700315 }
316 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700317
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700318 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700319 final Resources res = view.getResources();
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700320
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800321 final int paddingStart = additive ? view.getPaddingStart() : 0;
322 final int paddingEnd = additive ? view.getPaddingEnd() : 0;
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700323 final int paddingBottom = res.getDimensionPixelSize(
324 com.android.internal.R.dimen.preference_fragment_padding_bottom);
325
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700326 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700327 }
328
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700329 public static String getMeProfileName(Context context, boolean full) {
330 if (full) {
331 return getProfileDisplayName(context);
332 } else {
333 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700334 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700335 }
336
337 private static String getShorterNameIfPossible(Context context) {
338 final String given = getLocalProfileGivenName(context);
339 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
340 }
341
342 private static String getLocalProfileGivenName(Context context) {
343 final ContentResolver cr = context.getContentResolver();
344
345 // Find the raw contact ID for the local ME profile raw contact.
346 final long localRowProfileId;
347 final Cursor localRawProfile = cr.query(
348 Profile.CONTENT_RAW_CONTACTS_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800349 new String[] {RawContacts._ID},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700350 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
351 RawContacts.ACCOUNT_NAME + " IS NULL",
352 null, null);
353 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700354
355 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700356 if (!localRawProfile.moveToFirst()) {
357 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700358 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700359 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700360 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700361 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700362 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700363
364 // Find the structured name for the raw contact.
365 final Cursor structuredName = cr.query(
366 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
Sunny Shao7e866b62019-08-09 11:42:04 +0800367 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
368 CommonDataKinds.StructuredName.FAMILY_NAME},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700369 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
370 null, null);
371 if (structuredName == null) return null;
372
373 try {
374 if (!structuredName.moveToFirst()) {
375 return null;
376 }
377 String partialName = structuredName.getString(0);
378 if (TextUtils.isEmpty(partialName)) {
379 partialName = structuredName.getString(1);
380 }
381 return partialName;
382 } finally {
383 structuredName.close();
384 }
385 }
386
387 private static final String getProfileDisplayName(Context context) {
388 final ContentResolver cr = context.getContentResolver();
389 final Cursor profile = cr.query(Profile.CONTENT_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800390 new String[] {Profile.DISPLAY_NAME}, null, null, null);
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700391 if (profile == null) return null;
392
393 try {
394 if (!profile.moveToFirst()) {
395 return null;
396 }
397 return profile.getString(0);
398 } finally {
399 profile.close();
400 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700401 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700402
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700403 public static boolean hasMultipleUsers(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800404 return context.getSystemService(UserManager.class)
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700405 .getUsers().size() > 1;
406 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700407
408 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100409 * Returns the managed profile of the current user or {@code null} if none is found or a profile
410 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100411 */
412 public static UserHandle getManagedProfile(UserManager userManager) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800413 final List<UserHandle> userProfiles = userManager.getUserProfiles();
Aarthi Balachanderd0f83592018-07-10 17:04:53 -0700414 for (UserHandle profile : userProfiles) {
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100415 if (profile.getIdentifier() == userManager.getUserHandle()) {
416 continue;
417 }
418 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
419 if (userInfo.isManagedProfile()) {
420 return profile;
421 }
422 }
423 return null;
424 }
425
426 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100427 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
428 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
429 */
430 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
431 // TODO: Call getManagedProfileId from here once Robolectric supports
432 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
433 // yet another implementation that loops over user profiles in this method). In the meantime
434 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
435 // used for Settings Robolectric tests).
436 final int myUserId = UserHandle.myUserId();
Bonian Chen5e65da02019-11-08 07:40:35 +0800437 final List<UserInfo> profiles = userManager.getProfiles(myUserId);
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100438 final int count = profiles.size();
439 for (int i = 0; i < count; i++) {
440 final UserInfo profile = profiles.get(i);
441 if (profile.isManagedProfile()
442 && profile.getUserHandle().getIdentifier() != myUserId) {
443 return profile.getUserHandle();
444 }
445 }
446 return null;
447 }
448
449 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000450 * Retrieves the id for the given user's managed profile.
451 *
452 * @return the managed profile id or UserHandle.USER_NULL if there is none.
453 */
454 public static int getManagedProfileId(UserManager um, int parentUserId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800455 final int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700456 for (int profileId : profileIds) {
457 if (profileId != parentUserId) {
458 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000459 }
460 }
461 return UserHandle.USER_NULL;
462 }
463
464 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100465 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000466 * <p>
467 * User would be retrieved in this order:
468 * <ul>
469 * <li> If this activity is launched from other user, return that user id.
470 * <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 +0800471 * extra in the arguments or intent extras.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000472 * <li> Otherwise, return UserHandle.myUserId().
473 * </ul>
474 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100475 * Note: This is secure in the sense that it only returns a target user different to the current
476 * one if the app launching this activity is the Settings app itself, running in the same user
477 * 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 +0100478 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100479 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000480 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800481 final UserHandle currentUser = new UserHandle(UserHandle.myUserId());
482 final IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100483 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800484 final String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
485 final boolean launchedFromSettingsApp =
486 SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100487
Bonian Chen5e65da02019-11-08 07:40:35 +0800488 final UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100489 am.getLaunchedFromUid(activityToken)));
490 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
491 // Check it's secure
492 if (isProfileOf(um, launchedFromUser)) {
493 return launchedFromUser;
494 }
495 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800496 final UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100497 if (extrasUser != null && !extrasUser.equals(currentUser)) {
498 // Check it's secure
499 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
500 return extrasUser;
501 }
502 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800503 final UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100504 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
505 // Check it's secure
506 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
507 return argumentsUser;
508 }
509 }
510 } catch (RemoteException e) {
511 // Should not happen
512 Log.v(TAG, "Could not talk to activity manager.", e);
513 }
514 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000515 }
516
517 /**
518 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
519 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
520 */
Sunny Shao7e866b62019-08-09 11:42:04 +0800521 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
Tony Mak8f41b9b2016-11-23 11:36:18 +0000522 if (bundle == null) {
523 return null;
524 }
525 final UserHandle user = bundle.getParcelable(EXTRA_USER);
526 if (user != null) {
527 return user;
528 }
529 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
530 if (userId != -1) {
531 return UserHandle.of(userId);
532 }
533 return null;
534 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100535
Sunny Shao7e866b62019-08-09 11:42:04 +0800536 /**
537 * Returns true if the user provided is in the same profiles group as the current user.
538 */
539 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
540 if (um == null || otherUser == null) return false;
541 return (UserHandle.myUserId() == otherUser.getIdentifier())
542 || um.getUserProfiles().contains(otherUser);
543 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530544
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100545 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800546 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
547 * @param userManager Instance of UserManager
Sunny Shao7e866b62019-08-09 11:42:04 +0800548 * @param checkUser The user to check the existence of.
Amith Yamasani45f86232014-11-19 17:12:46 -0800549 * @return UserInfo of the user or null for non-existent user.
550 */
551 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
Colin Cross38fa1852020-08-27 04:12:26 +0000552 final List<UserInfo> users = userManager.getAliveUsers();
Amith Yamasani45f86232014-11-19 17:12:46 -0800553 final int checkUserId = checkUser.getIdentifier();
554 for (UserInfo user : users) {
555 if (user.id == checkUserId) {
556 return user;
557 }
558 }
559 return null;
560 }
561
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000562 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
563 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
564 com.android.internal.R.styleable.Preference,
565 com.android.internal.R.attr.preferenceCategoryStyle, 0);
566 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
567 0);
568 a.recycle();
569 return inflater.inflate(resId, parent, false);
570 }
571
Christopher Tatea08a2252015-07-01 16:52:43 -0700572 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800573 final List<IntentFilterVerificationInfo> iviList =
574 pm.getIntentFilterVerifications(packageName);
575 final List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
Christopher Tatea08a2252015-07-01 16:52:43 -0700576
Bonian Chen5e65da02019-11-08 07:40:35 +0800577 final ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800578 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700579 for (IntentFilterVerificationInfo ivi : iviList) {
580 for (String host : ivi.getDomains()) {
581 result.add(host);
582 }
583 }
584 }
585 if (filters != null && filters.size() > 0) {
586 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700587 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
588 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
Sunny Shao7e866b62019-08-09 11:42:04 +0800589 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700590 result.addAll(filter.getHostsList());
591 }
592 }
593 }
594 return result;
595 }
596
Sudheer Shankabc956302015-04-09 12:19:53 +0100597 /**
598 * Returns the application info of the currently installed MDM package.
599 */
600 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800601 final DevicePolicyManager dpm =
Sudheer Shankabc956302015-04-09 12:19:53 +0100602 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800603 final ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
Sudheer Shankabc956302015-04-09 12:19:53 +0100604 if (mdmPackage == null) {
605 return null;
606 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800607 final String mdmPackageName = mdmPackage.getPackageName();
Sudheer Shankabc956302015-04-09 12:19:53 +0100608 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800609 final IPackageManager ipm = AppGlobals.getPackageManager();
610 final ApplicationInfo mdmApplicationInfo =
Sudheer Shankabc956302015-04-09 12:19:53 +0100611 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
612 return mdmApplicationInfo;
613 } catch (RemoteException e) {
614 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
615 + ", userId " + profileId, e);
616 return null;
617 }
618 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400619
620 public static boolean isBandwidthControlEnabled() {
621 final INetworkManagementService netManager = INetworkManagementService.Stub
622 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
623 try {
624 return netManager.isBandwidthControlEnabled();
625 } catch (RemoteException e) {
626 return false;
627 }
628 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400629
630 /**
631 * Returns an accessible SpannableString.
Sunny Shao7e866b62019-08-09 11:42:04 +0800632 * @param displayText the text to display
Julia Reynoldsce25af42015-07-08 16:56:31 -0400633 * @param accessibileText the text text-to-speech engines should read
634 */
635 public static SpannableString createAccessibleSequence(CharSequence displayText,
636 String accessibileText) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800637 final SpannableString str = new SpannableString(displayText);
Julia Reynoldsce25af42015-07-08 16:56:31 -0400638 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
639 displayText.length(),
640 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
641 return str;
642 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700643
Clara Bayarrife432e82015-10-12 12:07:02 +0100644 /**
Jeff Sharkey219ec912017-12-19 14:57:39 -0700645 * Returns the user id present in the bundle with
646 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
Clara Bayarrife432e82015-10-12 12:07:02 +0100647 *
Jeff Sharkey219ec912017-12-19 14:57:39 -0700648 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800649 * current user group.
Clara Bayarrife432e82015-10-12 12:07:02 +0100650 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000651 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700652 return getUserIdFromBundle(context, bundle, false);
653 }
654
655 /**
656 * Returns the user id present in the bundle with
657 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
658 *
659 * @param isInternal indicating if the caller is "internal" to the system,
Sunny Shao7e866b62019-08-09 11:42:04 +0800660 * meaning we're willing to trust extras like
Kevin Chynb13bc502020-07-20 23:35:21 -0700661 * {@link ChooseLockSettingsHelper#EXTRA_KEY_ALLOW_ANY_USER}.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700662 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800663 * current user group.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700664 */
665 public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
Clara Bayarrife432e82015-10-12 12:07:02 +0100666 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +0000667 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +0100668 }
Jeff Sharkey219ec912017-12-19 14:57:39 -0700669 final boolean allowAnyUser = isInternal
Kevin Chynb13bc502020-07-20 23:35:21 -0700670 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_KEY_ALLOW_ANY_USER, false);
Bonian Chen5e65da02019-11-08 07:40:35 +0800671 final int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700672 if (userId == LockPatternUtils.USER_FRP) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700673 return allowAnyUser ? userId : enforceSystemUser(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700674 } else {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700675 return allowAnyUser ? userId : enforceSameOwner(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700676 }
677 }
678
679 /**
680 * Returns the given user id if the current user is the system user.
681 *
682 * @throws SecurityException if the current user is not the system user.
683 */
684 public static int enforceSystemUser(Context context, int userId) {
685 if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
686 return userId;
687 }
688 throw new SecurityException("Given user id " + userId + " must only be used from "
689 + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100690 }
691
692 /**
693 * Returns the given user id if it belongs to the current user.
694 *
695 * @throws SecurityException if the given userId does not belong to the current user group.
696 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000697 public static int enforceSameOwner(Context context, int userId) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800698 final UserManager um = context.getSystemService(UserManager.class);
Ricky Wai72500162016-06-07 16:54:25 +0100699 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
700 if (ArrayUtils.contains(profileIds, userId)) {
701 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +0100702 }
Ricky Wai72500162016-06-07 16:54:25 +0100703 throw new SecurityException("Given user id " + userId + " does not belong to user "
704 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100705 }
706
Benjamin Franz194300d2016-01-13 12:16:25 +0000707 /**
708 * Returns the effective credential owner of the calling user.
709 */
710 public static int getCredentialOwnerUserId(Context context) {
711 return getCredentialOwnerUserId(context, UserHandle.myUserId());
712 }
713
714 /**
715 * Returns the user id of the credential owner of the given user id.
716 */
717 public static int getCredentialOwnerUserId(Context context, int userId) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800718 final UserManager um = context.getSystemService(UserManager.class);
Benjamin Franz194300d2016-01-13 12:16:25 +0000719 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700720 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500721
Alex Johnston403c3302020-01-07 15:40:05 +0000722 /**
723 * Returns the credential type of the given user id.
724 */
725 public static @LockPatternUtils.CredentialType int getCredentialType(Context context,
726 int userId) {
727 final LockPatternUtils lpu = new LockPatternUtils(context);
728 return lpu.getCredentialTypeForUser(userId);
729 }
730
Jason Monkb37e2882016-01-11 14:27:20 -0500731 private static final StringBuilder sBuilder = new StringBuilder(50);
732 private static final java.util.Formatter sFormatter = new java.util.Formatter(
733 sBuilder, Locale.getDefault());
734
735 public static String formatDateRange(Context context, long start, long end) {
736 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
737
738 synchronized (sBuilder) {
739 sBuilder.setLength(0);
740 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
741 .toString();
742 }
743 }
Jason Monk91e2f892016-02-23 15:31:09 -0500744
Bernard Chau88d523b2016-04-14 15:08:28 +0100745 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100746 int userId) {
747 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
748 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
749 context.startActivity(intent);
750 return true;
751 }
752 return false;
753 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700754
Rubin Xu3231afe2016-08-24 10:15:07 +0100755 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
756 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800757 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100758 ActivityManager.FLAG_AND_LOCKED)) {
759 return false;
760 }
761 } catch (RemoteException e) {
762 return false;
763 }
764 if (!(new LockPatternUtils(context)).isSecure(userId)) {
765 return false;
766 }
Robin Leecccf3242017-02-10 15:32:49 +0000767 return confirmWorkProfileCredentials(context, userId);
768 }
769
Robin Leecccf3242017-02-10 15:32:49 +0000770 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100771 final KeyguardManager km = (KeyguardManager) context.getSystemService(
772 Context.KEYGUARD_SERVICE);
773 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
774 if (unlockIntent != null) {
775 context.startActivity(unlockIntent);
776 return true;
777 } else {
778 return false;
779 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100780 }
781
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700782 public static CharSequence getApplicationLabel(Context context, String packageName) {
783 try {
784 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
785 packageName,
786 PackageManager.MATCH_DISABLED_COMPONENTS
Sunny Shao7e866b62019-08-09 11:42:04 +0800787 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700788 return appInfo.loadLabel(context.getPackageManager());
789 } catch (PackageManager.NameNotFoundException e) {
Raff Tsai376ce872020-01-06 00:42:35 +0800790 Log.e(TAG, "Unable to find info for package: " + packageName);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700791 }
792 return null;
793 }
Jason Monk75199542016-05-06 15:09:32 -0400794
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600795 public static boolean isPackageDirectBootAware(Context context, String packageName) {
796 try {
797 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
798 packageName, 0);
799 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
800 } catch (NameNotFoundException ignored) {
801 }
802 return false;
803 }
Andre Lago3e398c82016-07-25 14:12:28 +0100804
805 /**
806 * Returns a context created from the given context for the given user, or null if it fails
807 */
808 public static Context createPackageContextAsUser(Context context, int userId) {
809 try {
810 return context.createPackageContextAsUser(
811 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
812 } catch (PackageManager.NameNotFoundException e) {
813 Log.e(TAG, "Failed to create user context", e);
814 }
815 return null;
816 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600817
818 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
819 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800820 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600821 } else {
822 return null;
823 }
824 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800825
Kevin Chyn82792cc2017-07-20 00:15:44 -0700826 public static boolean hasFingerprintHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800827 final FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
Kevin Chyn82792cc2017-07-20 00:15:44 -0700828 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
829 }
830
Kevin Chyn4882e872018-06-25 17:58:31 -0700831 public static FaceManager getFaceManagerOrNull(Context context) {
832 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
833 return (FaceManager) context.getSystemService(Context.FACE_SERVICE);
834 } else {
835 return null;
836 }
837 }
838
839 public static boolean hasFaceHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800840 final FaceManager faceManager = getFaceManagerOrNull(context);
Kevin Chyn4882e872018-06-25 17:58:31 -0700841 return faceManager != null && faceManager.isHardwareDetected();
842 }
843
Daniel Nishi31027da2017-01-19 14:03:57 -0800844 /**
Mill Chen7edebee2021-04-09 23:14:27 +0800845 * Return true if the device supports multiple biometrics authentications.
846 */
847 public static boolean isMultipleBiometricsSupported(Context context) {
848 return hasFingerprintHardware(context) && hasFaceHardware(context);
849 }
850
851 /**
Daniel Nishi31027da2017-01-19 14:03:57 -0800852 * Launches an intent which may optionally have a user id defined.
853 * @param fragment Fragment to use to launch the activity.
Sunny Shao7e866b62019-08-09 11:42:04 +0800854 * @param intent Intent to launch.
Daniel Nishi31027da2017-01-19 14:03:57 -0800855 */
856 public static void launchIntent(Fragment fragment, Intent intent) {
857 try {
858 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
859
860 if (userId == -1) {
861 fragment.startActivity(intent);
862 } else {
863 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
864 }
865 } catch (ActivityNotFoundException e) {
866 Log.w(TAG, "No activity found for " + intent);
867 }
868 }
869
Christine Franksc6890ab2017-06-23 14:28:21 -0700870 public static boolean isDemoUser(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800871 return UserManager.isDeviceInDemoMode(context)
872 && context.getSystemService(UserManager.class).isDemoUser();
Christine Franksc6890ab2017-06-23 14:28:21 -0700873 }
874
Justin Klaassen30257272017-08-08 21:58:05 -0700875 public static ComponentName getDeviceOwnerComponent(Context context) {
876 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
877 Context.DEVICE_POLICY_SERVICE);
878 return dpm.getDeviceOwnerComponentOnAnyUser();
Christine Franks14782222017-01-23 16:44:02 -0800879 }
Daniel Nishidfed8a22017-01-19 16:32:41 -0800880
881 /**
882 * Returns if a given user is a profile of another user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800883 * @param user The user whose profiles wibe checked.
Daniel Nishidfed8a22017-01-19 16:32:41 -0800884 * @param profile The (potential) profile.
885 * @return if the profile is actually a profile
886 */
887 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
888 return user.id == profile.id ||
889 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
890 && user.profileGroupId == profile.profileGroupId);
891 }
Daniel Nishi9f60f422017-02-15 15:25:48 -0800892
893 /**
894 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
895 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
896 */
897 @Nullable
898 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
899 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
900 VolumeInfo.ID_PRIVATE_INTERNAL);
Bonian Chen5e65da02019-11-08 07:40:35 +0800901 final VolumeInfo volume = sm.findVolumeById(volumeId);
Daniel Nishi9f60f422017-02-15 15:25:48 -0800902 return isVolumeValid(volume) ? volume : null;
903 }
904
jackqdyuleiddba9662017-03-08 19:35:02 -0800905 /**
jackqdyulei00015fb2017-08-22 11:25:30 -0700906 * Return {@code true} if the supplied package is device owner or profile owner of at
907 * least one user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800908 * @param userManager used to get profile owner app for each user
jackqdyulei00015fb2017-08-22 11:25:30 -0700909 * @param devicePolicyManager used to check whether it is device owner app
Sunny Shao7e866b62019-08-09 11:42:04 +0800910 * @param packageName package to check about
jackqdyulei00015fb2017-08-22 11:25:30 -0700911 */
912 public static boolean isProfileOrDeviceOwner(UserManager userManager,
Fan Zhangaab36de2018-03-30 16:58:28 -0700913 DevicePolicyManager devicePolicyManager, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800914 final List<UserInfo> userInfos = userManager.getUsers();
jackqdyulei00015fb2017-08-22 11:25:30 -0700915 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
916 return true;
917 }
918 for (int i = 0, size = userInfos.size(); i < size; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800919 final ComponentName cn = devicePolicyManager
920 .getProfileOwnerAsUser(userInfos.get(i).id);
jackqdyulei00015fb2017-08-22 11:25:30 -0700921 if (cn != null && cn.getPackageName().equals(packageName)) {
922 return true;
923 }
924 }
925 return false;
926 }
927
928 /**
Alex Johnston341f9952020-02-26 15:54:11 +0000929 * Return {@code true} if the supplied package is the device owner or profile owner of a
930 * given user.
931 *
932 * @param devicePolicyManager used to check whether it is device owner and profile owner app
933 * @param packageName package to check about
934 * @param userId the if of the relevant user
935 */
936 public static boolean isProfileOrDeviceOwner(DevicePolicyManager devicePolicyManager,
937 String packageName, int userId) {
938 if ((devicePolicyManager.getDeviceOwnerUserId() == userId)
939 && devicePolicyManager.isDeviceOwnerApp(packageName)) {
940 return true;
941 }
942 final ComponentName cn = devicePolicyManager.getProfileOwnerAsUser(userId);
943 if (cn != null && cn.getPackageName().equals(packageName)) {
944 return true;
945 }
946 return false;
947 }
948
949 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800950 * Return the resource id to represent the install status for an app
951 */
952 @StringRes
953 public static int getInstallationStatus(ApplicationInfo info) {
954 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
955 return R.string.not_installed;
956 }
957 return info.enabled ? R.string.installed : R.string.disabled;
958 }
959
Daniel Nishi9f60f422017-02-15 15:25:48 -0800960 private static boolean isVolumeValid(VolumeInfo volume) {
961 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
962 && volume.isMountedReadable();
963 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700964
PMS2263a05602017-06-14 07:10:15 +0000965 public static void setEditTextCursorPosition(EditText editText) {
966 editText.setSelection(editText.getText().length());
967 }
Felipe Lemebd884502017-09-15 18:16:21 -0700968
969 /**
970 * Sets the preference icon with a drawable that is scaled down to to avoid crashing Settings if
971 * it's too big.
972 */
973 public static void setSafeIcon(Preference pref, Drawable icon) {
974 Drawable safeIcon = icon;
Phil Weaver5a3e02d2018-03-08 17:38:46 -0800975 if ((icon != null) && !(icon instanceof VectorDrawable)) {
Felipe Lemebd884502017-09-15 18:16:21 -0700976 safeIcon = getSafeDrawable(icon, 500, 500);
977 }
978 pref.setIcon(safeIcon);
979 }
980
981 /**
982 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
983 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800984 * @param original original drawable, typically an app icon.
985 * @param maxWidth maximum width, in pixels.
Felipe Lemebd884502017-09-15 18:16:21 -0700986 * @param maxHeight maximum height, in pixels.
987 */
988 public static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
989 final int actualWidth = original.getMinimumWidth();
990 final int actualHeight = original.getMinimumHeight();
991
992 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
993 return original;
994 }
995
Bonian Chen5e65da02019-11-08 07:40:35 +0800996 final float scaleWidth = ((float) maxWidth) / actualWidth;
997 final float scaleHeight = ((float) maxHeight) / actualHeight;
998 final float scale = Math.min(scaleWidth, scaleHeight);
Felipe Lemebd884502017-09-15 18:16:21 -0700999 final int width = (int) (actualWidth * scale);
1000 final int height = (int) (actualHeight * scale);
1001
1002 final Bitmap bitmap;
1003 if (original instanceof BitmapDrawable) {
1004 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
1005 height, false);
1006 } else {
Jason Chiuc78c54a2019-02-13 16:07:57 +08001007 bitmap = createBitmap(original, width, height);
Felipe Lemebd884502017-09-15 18:16:21 -07001008 }
1009 return new BitmapDrawable(null, bitmap);
1010 }
jackqdyuleifde637f2018-01-02 14:51:01 -08001011
1012 /**
Jason Chiuc78c54a2019-02-13 16:07:57 +08001013 * Create an Icon pointing to a drawable.
Jason Chiu1217bbe2019-01-24 16:32:31 +08001014 */
Jason Chiuc78c54a2019-02-13 16:07:57 +08001015 public static IconCompat createIconWithDrawable(Drawable drawable) {
1016 Bitmap bitmap;
Jason Chiu1217bbe2019-01-24 16:32:31 +08001017 if (drawable instanceof BitmapDrawable) {
Sunny Shao7e866b62019-08-09 11:42:04 +08001018 bitmap = ((BitmapDrawable)drawable).getBitmap();
Jason Chiuc78c54a2019-02-13 16:07:57 +08001019 } else {
1020 final int width = drawable.getIntrinsicWidth();
1021 final int height = drawable.getIntrinsicHeight();
1022 bitmap = createBitmap(drawable,
1023 width > 0 ? width : 1,
1024 height > 0 ? height : 1);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001025 }
Jason Chiuc78c54a2019-02-13 16:07:57 +08001026 return IconCompat.createWithBitmap(bitmap);
1027 }
Jason Chiu1217bbe2019-01-24 16:32:31 +08001028
clownshen24827d32019-03-29 20:22:02 +08001029 /**
1030 * Creates a drawable with specified width and height.
1031 */
1032 public static Bitmap createBitmap(Drawable drawable, int width, int height) {
Jason Chiuc78c54a2019-02-13 16:07:57 +08001033 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001034 final Canvas canvas = new Canvas(bitmap);
1035 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1036 drawable.draw(canvas);
1037 return bitmap;
1038 }
1039
1040 /**
jackqdyuleifde637f2018-01-02 14:51:01 -08001041 * Get the {@link Drawable} that represents the app icon
1042 */
1043 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
1044 PackageManager packageManager, String packageName, int userId) {
1045 try {
Tony Mak4e292812018-03-19 15:37:21 +00001046 final ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
1047 packageName, PackageManager.GET_META_DATA, userId);
jackqdyuleifde637f2018-01-02 14:51:01 -08001048 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
1049 } catch (PackageManager.NameNotFoundException e) {
1050 return packageManager.getDefaultActivityIcon();
1051 }
1052 }
Raff Tsai2928cd42018-11-05 16:10:19 +08001053
1054 /** Returns true if the current package is installed & enabled. */
1055 public static boolean isPackageEnabled(Context context, String packageName) {
1056 try {
1057 return context.getPackageManager().getApplicationInfo(packageName, 0).enabled;
1058 } catch (Exception e) {
1059 Log.e(TAG, "Error while retrieving application info for package " + packageName, e);
1060 }
1061 return false;
1062 }
markchien1dd1d792019-01-11 16:18:20 +08001063
1064 /** Get {@link Resources} by subscription id if subscription id is valid. */
1065 public static Resources getResourcesForSubId(Context context, int subId) {
1066 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1067 return SubscriptionManager.getResourcesForSubId(context, subId);
1068 } else {
1069 return context.getResources();
1070 }
1071 }
Ng Zhi Anb97bdc32019-02-01 12:39:31 -08001072
1073 /**
1074 * Returns true if SYSTEM_ALERT_WINDOW permission is available.
1075 * Starting from Q, SYSTEM_ALERT_WINDOW is disabled on low ram phones.
1076 */
1077 public static boolean isSystemAlertWindowEnabled(Context context) {
1078 // SYSTEM_ALERT_WINDOW is disabled on on low ram devices starting from Q
1079 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
1080 return !(am.isLowRamDevice() && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q));
1081 }
tmfangaed8f362019-03-18 16:56:09 +08001082
1083 /**
1084 * Adds a shadow appear/disappear animation to action bar scroll.
1085 *
1086 * <p/>
1087 * This method must be called after {@link Fragment#onCreate(Bundle)}.
1088 */
1089 public static void setActionBarShadowAnimation(Activity activity, Lifecycle lifecycle,
1090 View scrollView) {
1091 if (activity == null) {
1092 Log.w(TAG, "No activity, cannot style actionbar.");
1093 return;
1094 }
1095 final ActionBar actionBar = activity.getActionBar();
1096 if (actionBar == null) {
1097 Log.w(TAG, "No actionbar, cannot style actionbar.");
1098 return;
1099 }
1100 actionBar.setElevation(0);
1101
1102 if (lifecycle != null && scrollView != null) {
1103 ActionBarShadowController.attachToView(activity, lifecycle, scrollView);
1104 }
1105 }
Raff Tsaiafd494d2019-10-16 15:25:21 +08001106
1107 /**
1108 * Return correct target fragment based on argument
1109 *
1110 * @param activity the activity target fragment will be launched.
1111 * @param fragmentName initial target fragment name.
1112 * @param args fragment launch arguments.
1113 */
1114 public static Fragment getTargetFragment(Activity activity, String fragmentName, Bundle args) {
1115 Fragment f = null;
Raff Tsai84327f62019-11-15 11:02:25 +08001116 final boolean isPersonal = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001117 == ProfileSelectFragment.ProfileType.PERSONAL : false;
Raff Tsai84327f62019-11-15 11:02:25 +08001118 final boolean isWork = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001119 == ProfileSelectFragment.ProfileType.WORK : false;
Raff Tsai3fbdf342020-01-16 05:27:32 +08001120 if (activity.getSystemService(UserManager.class).getUserProfiles().size() > 1
Raff Tsaiafd494d2019-10-16 15:25:21 +08001121 && ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName) != null
Raff Tsai84327f62019-11-15 11:02:25 +08001122 && !isWork && !isPersonal) {
Raff Tsaiafd494d2019-10-16 15:25:21 +08001123 f = Fragment.instantiate(activity, ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName),
1124 args);
1125 } else {
1126 f = Fragment.instantiate(activity, fragmentName, args);
1127 }
1128 return f;
1129 }
Yanting Yang96127fe2020-03-20 12:04:09 +08001130
1131 /**
1132 * Returns true if current binder uid is Settings Intelligence.
1133 */
1134 public static boolean isSettingsIntelligence(Context context) {
1135 final int callingUid = Binder.getCallingUid();
1136 final String callingPackage = context.getPackageManager().getPackagesForUid(callingUid)[0];
1137 final boolean isSettingsIntelligence = TextUtils.equals(callingPackage,
1138 context.getString(R.string.config_settingsintelligence_package_name));
1139 return isSettingsIntelligence;
1140 }
Jason Chiu8ac1e4d2020-05-11 16:13:47 +08001141
1142 /**
1143 * Returns true if the night mode is enabled.
1144 */
1145 public static boolean isNightMode(Context context) {
1146 final int currentNightMode =
1147 context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1148 return currentNightMode == Configuration.UI_MODE_NIGHT_YES;
1149 }
Tim Pengdf467882020-06-24 13:10:01 +08001150
1151 /**
1152 * Returns a bitmap with rounded corner.
1153 *
1154 * @param context application context.
1155 * @param source bitmap to apply round corner.
1156 * @param cornerRadius corner radius value.
1157 */
1158 public static Bitmap convertCornerRadiusBitmap(@NonNull Context context,
1159 @NonNull Bitmap source, @NonNull float cornerRadius) {
1160 final Bitmap roundedBitmap = Bitmap.createBitmap(source.getWidth(), source.getHeight(),
1161 Bitmap.Config.ARGB_8888);
1162 final RoundedBitmapDrawable drawable =
1163 RoundedBitmapDrawableFactory.create(context.getResources(), source);
1164 drawable.setAntiAlias(true);
1165 drawable.setCornerRadius(cornerRadius);
1166 final Canvas canvas = new Canvas(roundedBitmap);
1167 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1168 drawable.draw(canvas);
1169 return roundedBitmap;
1170 }
Zoey Chen3abe48e2020-10-28 22:46:48 +08001171
1172 public static boolean isProviderModelEnabled(Context context) {
1173 return FeatureFlagUtils.isEnabled(context, FeatureFlagUtils.SETTINGS_PROVIDER_MODEL);
1174 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001175}