blob: 4390aad2512b6e1a65db52593434d6be16e81d34 [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;
57import android.net.LinkProperties;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070058import android.net.Network;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070059import android.net.wifi.WifiManager;
Amith Yamasania4379d62011-07-22 10:34:58 -070060import android.os.BatteryManager;
Yanting Yang96127fe2020-03-20 12:04:09 +080061import android.os.Binder;
Ng Zhi Anb97bdc32019-02-01 12:39:31 -080062import android.os.Build;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020063import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010064import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040065import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010066import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040067import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070068import android.os.UserHandle;
69import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080070import android.os.storage.StorageManager;
Daniel Nishi9f60f422017-02-15 15:25:48 -080071import android.os.storage.VolumeInfo;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070072import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070073import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070074import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070075import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070076import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070077import android.provider.ContactsContract.RawContacts;
markchien1dd1d792019-01-11 16:18:20 +080078import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070079import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040080import android.text.Spannable;
81import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020082import android.text.TextUtils;
Jason Monkb37e2882016-01-11 14:27:20 -050083import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040084import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070085import android.util.ArraySet;
Zoey Chen3abe48e2020-10-28 22:46:48 +080086import android.util.FeatureFlagUtils;
jackqdyuleifde637f2018-01-02 14:51:01 -080087import android.util.IconDrawableFactory;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010088import android.util.Log;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000089import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070090import android.view.View;
91import android.view.ViewGroup;
PMS2263a05602017-06-14 07:10:15 +000092import android.widget.EditText;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070093import android.widget.ListView;
94import android.widget.TabWidget;
Fan Zhangcc335d92016-09-29 14:37:14 -070095
Tim Pengdf467882020-06-24 13:10:01 +080096import androidx.annotation.NonNull;
Fan Zhang23f8d592018-08-28 15:11:40 -070097import androidx.annotation.StringRes;
Jason Chiuc78c54a2019-02-13 16:07:57 +080098import androidx.core.graphics.drawable.IconCompat;
Tim Pengdf467882020-06-24 13:10:01 +080099import androidx.core.graphics.drawable.RoundedBitmapDrawable;
100import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
Fan Zhang23f8d592018-08-28 15:11:40 -0700101import androidx.fragment.app.Fragment;
tmfangaed8f362019-03-18 16:56:09 +0800102import androidx.lifecycle.Lifecycle;
Fan Zhang23f8d592018-08-28 15:11:40 -0700103import androidx.preference.Preference;
104import androidx.preference.PreferenceGroup;
105
Ricky Wai616342b2016-04-13 10:40:22 +0100106import com.android.internal.app.UnlaunchableAppActivity;
Ricky Wai72500162016-06-07 16:54:25 +0100107import com.android.internal.util.ArrayUtils;
Rubin Xu3231afe2016-08-24 10:15:07 +0100108import com.android.internal.widget.LockPatternUtils;
Raff Tsaiafd494d2019-10-16 15:25:21 +0800109import com.android.settings.dashboard.profileselector.ProfileFragmentBridge;
Raff Tsai84327f62019-11-15 11:02:25 +0800110import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
Jeff Sharkey219ec912017-12-19 14:57:39 -0700111import com.android.settings.password.ChooseLockSettingsHelper;
tmfangaed8f362019-03-18 16:56:09 +0800112import com.android.settingslib.widget.ActionBarShadowController;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700113
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800114import java.net.InetAddress;
115import 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 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800151 * Finds a matching activity for a preference's intent. If a matching
152 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800153 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800154 * @param context The context.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800155 * @param parentPreferenceGroup The preference group that contains the
Sunny Shao7e866b62019-08-09 11:42:04 +0800156 * preference whose intent is being resolved.
157 * @param preferenceKey The key of the preference whose intent is being
158 * resolved.
159 * @param flags 0 or one or more of
160 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
161 * .
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800162 * @return Whether an activity was found. If false, the preference was
Sunny Shao7e866b62019-08-09 11:42:04 +0800163 * removed.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800164 */
165 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
166 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800167
Bonian Chen5e65da02019-11-08 07:40:35 +0800168 final Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800169 if (preference == null) {
170 return false;
171 }
Ying Wanga7188322010-01-04 18:45:10 -0800172
Bonian Chen5e65da02019-11-08 07:40:35 +0800173 final Intent intent = preference.getIntent();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800174 if (intent != null) {
175 // Find the activity that is in the system image
Bonian Chen5e65da02019-11-08 07:40:35 +0800176 final PackageManager pm = context.getPackageManager();
177 final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
178 final int listSize = list.size();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800179 for (int i = 0; i < listSize; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800180 final ResolveInfo resolveInfo = list.get(i);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800181 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
182 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800183
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800184 // Replace the intent with this specific activity
185 preference.setIntent(new Intent().setClassName(
186 resolveInfo.activityInfo.packageName,
187 resolveInfo.activityInfo.name));
188
189 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
190 // Set the preference title to the activity's label
191 preference.setTitle(resolveInfo.loadLabel(pm));
192 }
Ying Wanga7188322010-01-04 18:45:10 -0800193
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800194 return true;
195 }
196 }
197 }
198
199 // Did not find a matching activity, so remove the preference
200 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800201
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900202 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800203 }
Ying Wanga7188322010-01-04 18:45:10 -0800204
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200205 /**
Ying Wanga7188322010-01-04 18:45:10 -0800206 * Returns true if Monkey is running.
207 */
208 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700209 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800210 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700211
212 /**
213 * Returns whether the device is voice-capable (meaning, it is also a phone).
214 */
215 public static boolean isVoiceCapable(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800216 final TelephonyManager telephony =
Amith Yamasani60133dd2010-09-11 14:17:31 -0700217 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
218 return telephony != null && telephony.isVoiceCapable();
219 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800220
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800221 /**
222 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
223 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900224 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800225 */
226 public static String getWifiIpAddresses(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800227 final WifiManager wifiManager = context.getSystemService(WifiManager.class);
228 final Network currentNetwork = wifiManager.getCurrentNetwork();
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700229 if (currentNetwork != null) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800230 final ConnectivityManager cm = (ConnectivityManager)
Sunny Shao7e866b62019-08-09 11:42:04 +0800231 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800232 final LinkProperties prop = cm.getLinkProperties(currentNetwork);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700233 return formatIpAddresses(prop);
234 }
235 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700236 }
237
Amith Yamasani6822b742011-10-17 16:41:00 -0700238 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800239 if (prop == null) return null;
Bonian Chen5e65da02019-11-08 07:40:35 +0800240 final Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800241 // If there are no entries, return null
242 if (!iter.hasNext()) return null;
243 // Concatenate all available addresses, comma separated
244 String addresses = "";
245 while (iter.hasNext()) {
246 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900247 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800248 }
249 return addresses;
250 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900251
252 public static Locale createLocaleFromString(String localeStr) {
253 // TODO: is there a better way to actually construct a locale that will match?
254 // The main problem is, on top of Java specs, locale.toString() and
255 // new Locale(locale.toString()).toString() do not return equal() strings in
256 // many cases, because the constructor takes the only string as the language
257 // code. So : new Locale("en", "US").toString() => "en_US"
258 // And : new Locale("en_US").toString() => "en_us"
Sunny Shao7e866b62019-08-09 11:42:04 +0800259 if (null == localeStr)
Jean Chalard71ad1f42011-05-12 15:06:16 +0900260 return Locale.getDefault();
Bonian Chen5e65da02019-11-08 07:40:35 +0800261 final String[] brokenDownLocale = localeStr.split("_", 3);
Jean Chalard71ad1f42011-05-12 15:06:16 +0900262 // split may not return a 0-length array.
263 if (1 == brokenDownLocale.length) {
264 return new Locale(brokenDownLocale[0]);
265 } else if (2 == brokenDownLocale.length) {
266 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
267 } else {
268 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
269 }
270 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700271
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900272 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
273 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
274 }
275
Mill Chenad99e2e2020-10-21 16:32:56 +0800276 /**
277 * Return true if battery is present.
278 */
279 public static boolean isBatteryPresent(Context context) {
280 Intent batteryBroadcast = context.registerReceiver(null /* receiver */,
281 new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
282 return isBatteryPresent(batteryBroadcast);
283 }
284
Amith Yamasania4379d62011-07-22 10:34:58 -0700285 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700286 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700287 }
288
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700289 /**
290 * Prepare a custom preferences layout, moving padding to {@link ListView}
291 * when outside scrollbars are requested. Usually used to display
292 * {@link ListView} and {@link TabWidget} with correct padding.
293 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700294 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800295 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700296 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700297 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700298 final Resources res = list.getResources();
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700299 final int paddingBottom = res.getDimensionPixelSize(
300 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700301
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700302 if (parent instanceof PreferenceFrameLayout) {
303 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700304 }
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800305 list.setPaddingRelative(0 /* start */, 0 /* top */, 0 /* end */, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700306 }
307 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700308
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700309 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700310 final Resources res = view.getResources();
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700311
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800312 final int paddingStart = additive ? view.getPaddingStart() : 0;
313 final int paddingEnd = additive ? view.getPaddingEnd() : 0;
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700314 final int paddingBottom = res.getDimensionPixelSize(
315 com.android.internal.R.dimen.preference_fragment_padding_bottom);
316
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700317 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700318 }
319
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700320 public static String getMeProfileName(Context context, boolean full) {
321 if (full) {
322 return getProfileDisplayName(context);
323 } else {
324 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700325 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700326 }
327
328 private static String getShorterNameIfPossible(Context context) {
329 final String given = getLocalProfileGivenName(context);
330 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
331 }
332
333 private static String getLocalProfileGivenName(Context context) {
334 final ContentResolver cr = context.getContentResolver();
335
336 // Find the raw contact ID for the local ME profile raw contact.
337 final long localRowProfileId;
338 final Cursor localRawProfile = cr.query(
339 Profile.CONTENT_RAW_CONTACTS_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800340 new String[] {RawContacts._ID},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700341 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
342 RawContacts.ACCOUNT_NAME + " IS NULL",
343 null, null);
344 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700345
346 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700347 if (!localRawProfile.moveToFirst()) {
348 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700349 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700350 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700351 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700352 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700353 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700354
355 // Find the structured name for the raw contact.
356 final Cursor structuredName = cr.query(
357 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
Sunny Shao7e866b62019-08-09 11:42:04 +0800358 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
359 CommonDataKinds.StructuredName.FAMILY_NAME},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700360 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
361 null, null);
362 if (structuredName == null) return null;
363
364 try {
365 if (!structuredName.moveToFirst()) {
366 return null;
367 }
368 String partialName = structuredName.getString(0);
369 if (TextUtils.isEmpty(partialName)) {
370 partialName = structuredName.getString(1);
371 }
372 return partialName;
373 } finally {
374 structuredName.close();
375 }
376 }
377
378 private static final String getProfileDisplayName(Context context) {
379 final ContentResolver cr = context.getContentResolver();
380 final Cursor profile = cr.query(Profile.CONTENT_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800381 new String[] {Profile.DISPLAY_NAME}, null, null, null);
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700382 if (profile == null) return null;
383
384 try {
385 if (!profile.moveToFirst()) {
386 return null;
387 }
388 return profile.getString(0);
389 } finally {
390 profile.close();
391 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700392 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700393
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700394 public static boolean hasMultipleUsers(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800395 return context.getSystemService(UserManager.class)
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700396 .getUsers().size() > 1;
397 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700398
399 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100400 * Returns the managed profile of the current user or {@code null} if none is found or a profile
401 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100402 */
403 public static UserHandle getManagedProfile(UserManager userManager) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800404 final List<UserHandle> userProfiles = userManager.getUserProfiles();
Aarthi Balachanderd0f83592018-07-10 17:04:53 -0700405 for (UserHandle profile : userProfiles) {
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100406 if (profile.getIdentifier() == userManager.getUserHandle()) {
407 continue;
408 }
409 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
410 if (userInfo.isManagedProfile()) {
411 return profile;
412 }
413 }
414 return null;
415 }
416
417 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100418 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
419 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
420 */
421 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
422 // TODO: Call getManagedProfileId from here once Robolectric supports
423 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
424 // yet another implementation that loops over user profiles in this method). In the meantime
425 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
426 // used for Settings Robolectric tests).
427 final int myUserId = UserHandle.myUserId();
Bonian Chen5e65da02019-11-08 07:40:35 +0800428 final List<UserInfo> profiles = userManager.getProfiles(myUserId);
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100429 final int count = profiles.size();
430 for (int i = 0; i < count; i++) {
431 final UserInfo profile = profiles.get(i);
432 if (profile.isManagedProfile()
433 && profile.getUserHandle().getIdentifier() != myUserId) {
434 return profile.getUserHandle();
435 }
436 }
437 return null;
438 }
439
440 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000441 * Retrieves the id for the given user's managed profile.
442 *
443 * @return the managed profile id or UserHandle.USER_NULL if there is none.
444 */
445 public static int getManagedProfileId(UserManager um, int parentUserId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800446 final int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700447 for (int profileId : profileIds) {
448 if (profileId != parentUserId) {
449 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000450 }
451 }
452 return UserHandle.USER_NULL;
453 }
454
455 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100456 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000457 * <p>
458 * User would be retrieved in this order:
459 * <ul>
460 * <li> If this activity is launched from other user, return that user id.
461 * <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 +0800462 * extra in the arguments or intent extras.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000463 * <li> Otherwise, return UserHandle.myUserId().
464 * </ul>
465 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100466 * Note: This is secure in the sense that it only returns a target user different to the current
467 * one if the app launching this activity is the Settings app itself, running in the same user
468 * 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 +0100469 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100470 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000471 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800472 final UserHandle currentUser = new UserHandle(UserHandle.myUserId());
473 final IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100474 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800475 final String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
476 final boolean launchedFromSettingsApp =
477 SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100478
Bonian Chen5e65da02019-11-08 07:40:35 +0800479 final UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100480 am.getLaunchedFromUid(activityToken)));
481 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
482 // Check it's secure
483 if (isProfileOf(um, launchedFromUser)) {
484 return launchedFromUser;
485 }
486 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800487 final UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100488 if (extrasUser != null && !extrasUser.equals(currentUser)) {
489 // Check it's secure
490 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
491 return extrasUser;
492 }
493 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800494 final UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100495 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
496 // Check it's secure
497 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
498 return argumentsUser;
499 }
500 }
501 } catch (RemoteException e) {
502 // Should not happen
503 Log.v(TAG, "Could not talk to activity manager.", e);
504 }
505 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000506 }
507
508 /**
509 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
510 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
511 */
Sunny Shao7e866b62019-08-09 11:42:04 +0800512 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
Tony Mak8f41b9b2016-11-23 11:36:18 +0000513 if (bundle == null) {
514 return null;
515 }
516 final UserHandle user = bundle.getParcelable(EXTRA_USER);
517 if (user != null) {
518 return user;
519 }
520 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
521 if (userId != -1) {
522 return UserHandle.of(userId);
523 }
524 return null;
525 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100526
Sunny Shao7e866b62019-08-09 11:42:04 +0800527 /**
528 * Returns true if the user provided is in the same profiles group as the current user.
529 */
530 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
531 if (um == null || otherUser == null) return false;
532 return (UserHandle.myUserId() == otherUser.getIdentifier())
533 || um.getUserProfiles().contains(otherUser);
534 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530535
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100536 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800537 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
538 * @param userManager Instance of UserManager
Sunny Shao7e866b62019-08-09 11:42:04 +0800539 * @param checkUser The user to check the existence of.
Amith Yamasani45f86232014-11-19 17:12:46 -0800540 * @return UserInfo of the user or null for non-existent user.
541 */
542 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
Colin Cross38fa1852020-08-27 04:12:26 +0000543 final List<UserInfo> users = userManager.getAliveUsers();
Amith Yamasani45f86232014-11-19 17:12:46 -0800544 final int checkUserId = checkUser.getIdentifier();
545 for (UserInfo user : users) {
546 if (user.id == checkUserId) {
547 return user;
548 }
549 }
550 return null;
551 }
552
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000553 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
554 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
555 com.android.internal.R.styleable.Preference,
556 com.android.internal.R.attr.preferenceCategoryStyle, 0);
557 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
558 0);
559 a.recycle();
560 return inflater.inflate(resId, parent, false);
561 }
562
Christopher Tatea08a2252015-07-01 16:52:43 -0700563 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800564 final List<IntentFilterVerificationInfo> iviList =
565 pm.getIntentFilterVerifications(packageName);
566 final List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
Christopher Tatea08a2252015-07-01 16:52:43 -0700567
Bonian Chen5e65da02019-11-08 07:40:35 +0800568 final ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800569 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700570 for (IntentFilterVerificationInfo ivi : iviList) {
571 for (String host : ivi.getDomains()) {
572 result.add(host);
573 }
574 }
575 }
576 if (filters != null && filters.size() > 0) {
577 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700578 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
579 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
Sunny Shao7e866b62019-08-09 11:42:04 +0800580 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700581 result.addAll(filter.getHostsList());
582 }
583 }
584 }
585 return result;
586 }
587
Sudheer Shankabc956302015-04-09 12:19:53 +0100588 /**
589 * Returns the application info of the currently installed MDM package.
590 */
591 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800592 final DevicePolicyManager dpm =
Sudheer Shankabc956302015-04-09 12:19:53 +0100593 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800594 final ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
Sudheer Shankabc956302015-04-09 12:19:53 +0100595 if (mdmPackage == null) {
596 return null;
597 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800598 final String mdmPackageName = mdmPackage.getPackageName();
Sudheer Shankabc956302015-04-09 12:19:53 +0100599 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800600 final IPackageManager ipm = AppGlobals.getPackageManager();
601 final ApplicationInfo mdmApplicationInfo =
Sudheer Shankabc956302015-04-09 12:19:53 +0100602 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
603 return mdmApplicationInfo;
604 } catch (RemoteException e) {
605 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
606 + ", userId " + profileId, e);
607 return null;
608 }
609 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400610
611 public static boolean isBandwidthControlEnabled() {
612 final INetworkManagementService netManager = INetworkManagementService.Stub
613 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
614 try {
615 return netManager.isBandwidthControlEnabled();
616 } catch (RemoteException e) {
617 return false;
618 }
619 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400620
621 /**
622 * Returns an accessible SpannableString.
Sunny Shao7e866b62019-08-09 11:42:04 +0800623 * @param displayText the text to display
Julia Reynoldsce25af42015-07-08 16:56:31 -0400624 * @param accessibileText the text text-to-speech engines should read
625 */
626 public static SpannableString createAccessibleSequence(CharSequence displayText,
627 String accessibileText) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800628 final SpannableString str = new SpannableString(displayText);
Julia Reynoldsce25af42015-07-08 16:56:31 -0400629 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
630 displayText.length(),
631 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
632 return str;
633 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700634
Clara Bayarrife432e82015-10-12 12:07:02 +0100635 /**
Jeff Sharkey219ec912017-12-19 14:57:39 -0700636 * Returns the user id present in the bundle with
637 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
Clara Bayarrife432e82015-10-12 12:07:02 +0100638 *
Jeff Sharkey219ec912017-12-19 14:57:39 -0700639 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800640 * current user group.
Clara Bayarrife432e82015-10-12 12:07:02 +0100641 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000642 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700643 return getUserIdFromBundle(context, bundle, false);
644 }
645
646 /**
647 * Returns the user id present in the bundle with
648 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
649 *
650 * @param isInternal indicating if the caller is "internal" to the system,
Sunny Shao7e866b62019-08-09 11:42:04 +0800651 * meaning we're willing to trust extras like
Kevin Chynb13bc502020-07-20 23:35:21 -0700652 * {@link ChooseLockSettingsHelper#EXTRA_KEY_ALLOW_ANY_USER}.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700653 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800654 * current user group.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700655 */
656 public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
Clara Bayarrife432e82015-10-12 12:07:02 +0100657 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +0000658 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +0100659 }
Jeff Sharkey219ec912017-12-19 14:57:39 -0700660 final boolean allowAnyUser = isInternal
Kevin Chynb13bc502020-07-20 23:35:21 -0700661 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_KEY_ALLOW_ANY_USER, false);
Bonian Chen5e65da02019-11-08 07:40:35 +0800662 final int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700663 if (userId == LockPatternUtils.USER_FRP) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700664 return allowAnyUser ? userId : enforceSystemUser(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700665 } else {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700666 return allowAnyUser ? userId : enforceSameOwner(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700667 }
668 }
669
670 /**
671 * Returns the given user id if the current user is the system user.
672 *
673 * @throws SecurityException if the current user is not the system user.
674 */
675 public static int enforceSystemUser(Context context, int userId) {
676 if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
677 return userId;
678 }
679 throw new SecurityException("Given user id " + userId + " must only be used from "
680 + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100681 }
682
683 /**
684 * Returns the given user id if it belongs to the current user.
685 *
686 * @throws SecurityException if the given userId does not belong to the current user group.
687 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000688 public static int enforceSameOwner(Context context, int userId) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800689 final UserManager um = context.getSystemService(UserManager.class);
Ricky Wai72500162016-06-07 16:54:25 +0100690 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
691 if (ArrayUtils.contains(profileIds, userId)) {
692 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +0100693 }
Ricky Wai72500162016-06-07 16:54:25 +0100694 throw new SecurityException("Given user id " + userId + " does not belong to user "
695 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100696 }
697
Benjamin Franz194300d2016-01-13 12:16:25 +0000698 /**
699 * Returns the effective credential owner of the calling user.
700 */
701 public static int getCredentialOwnerUserId(Context context) {
702 return getCredentialOwnerUserId(context, UserHandle.myUserId());
703 }
704
705 /**
706 * Returns the user id of the credential owner of the given user id.
707 */
708 public static int getCredentialOwnerUserId(Context context, int userId) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800709 final UserManager um = context.getSystemService(UserManager.class);
Benjamin Franz194300d2016-01-13 12:16:25 +0000710 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700711 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500712
Alex Johnston403c3302020-01-07 15:40:05 +0000713 /**
714 * Returns the credential type of the given user id.
715 */
716 public static @LockPatternUtils.CredentialType int getCredentialType(Context context,
717 int userId) {
718 final LockPatternUtils lpu = new LockPatternUtils(context);
719 return lpu.getCredentialTypeForUser(userId);
720 }
721
Jason Monkb37e2882016-01-11 14:27:20 -0500722 private static final StringBuilder sBuilder = new StringBuilder(50);
723 private static final java.util.Formatter sFormatter = new java.util.Formatter(
724 sBuilder, Locale.getDefault());
725
726 public static String formatDateRange(Context context, long start, long end) {
727 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
728
729 synchronized (sBuilder) {
730 sBuilder.setLength(0);
731 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
732 .toString();
733 }
734 }
Jason Monk91e2f892016-02-23 15:31:09 -0500735
Bernard Chau88d523b2016-04-14 15:08:28 +0100736 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100737 int userId) {
738 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
739 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
740 context.startActivity(intent);
741 return true;
742 }
743 return false;
744 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700745
Rubin Xu3231afe2016-08-24 10:15:07 +0100746 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
747 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800748 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100749 ActivityManager.FLAG_AND_LOCKED)) {
750 return false;
751 }
752 } catch (RemoteException e) {
753 return false;
754 }
755 if (!(new LockPatternUtils(context)).isSecure(userId)) {
756 return false;
757 }
Robin Leecccf3242017-02-10 15:32:49 +0000758 return confirmWorkProfileCredentials(context, userId);
759 }
760
Robin Leecccf3242017-02-10 15:32:49 +0000761 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100762 final KeyguardManager km = (KeyguardManager) context.getSystemService(
763 Context.KEYGUARD_SERVICE);
764 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
765 if (unlockIntent != null) {
766 context.startActivity(unlockIntent);
767 return true;
768 } else {
769 return false;
770 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100771 }
772
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700773 public static CharSequence getApplicationLabel(Context context, String packageName) {
774 try {
775 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
776 packageName,
777 PackageManager.MATCH_DISABLED_COMPONENTS
Sunny Shao7e866b62019-08-09 11:42:04 +0800778 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700779 return appInfo.loadLabel(context.getPackageManager());
780 } catch (PackageManager.NameNotFoundException e) {
Raff Tsai376ce872020-01-06 00:42:35 +0800781 Log.e(TAG, "Unable to find info for package: " + packageName);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700782 }
783 return null;
784 }
Jason Monk75199542016-05-06 15:09:32 -0400785
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600786 public static boolean isPackageDirectBootAware(Context context, String packageName) {
787 try {
788 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
789 packageName, 0);
790 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
791 } catch (NameNotFoundException ignored) {
792 }
793 return false;
794 }
Andre Lago3e398c82016-07-25 14:12:28 +0100795
796 /**
797 * Returns a context created from the given context for the given user, or null if it fails
798 */
799 public static Context createPackageContextAsUser(Context context, int userId) {
800 try {
801 return context.createPackageContextAsUser(
802 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
803 } catch (PackageManager.NameNotFoundException e) {
804 Log.e(TAG, "Failed to create user context", e);
805 }
806 return null;
807 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600808
809 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
810 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800811 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600812 } else {
813 return null;
814 }
815 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800816
Kevin Chyn82792cc2017-07-20 00:15:44 -0700817 public static boolean hasFingerprintHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800818 final FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
Kevin Chyn82792cc2017-07-20 00:15:44 -0700819 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
820 }
821
Kevin Chyn4882e872018-06-25 17:58:31 -0700822 public static FaceManager getFaceManagerOrNull(Context context) {
823 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
824 return (FaceManager) context.getSystemService(Context.FACE_SERVICE);
825 } else {
826 return null;
827 }
828 }
829
830 public static boolean hasFaceHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800831 final FaceManager faceManager = getFaceManagerOrNull(context);
Kevin Chyn4882e872018-06-25 17:58:31 -0700832 return faceManager != null && faceManager.isHardwareDetected();
833 }
834
Daniel Nishi31027da2017-01-19 14:03:57 -0800835 /**
836 * Launches an intent which may optionally have a user id defined.
837 * @param fragment Fragment to use to launch the activity.
Sunny Shao7e866b62019-08-09 11:42:04 +0800838 * @param intent Intent to launch.
Daniel Nishi31027da2017-01-19 14:03:57 -0800839 */
840 public static void launchIntent(Fragment fragment, Intent intent) {
841 try {
842 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
843
844 if (userId == -1) {
845 fragment.startActivity(intent);
846 } else {
847 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
848 }
849 } catch (ActivityNotFoundException e) {
850 Log.w(TAG, "No activity found for " + intent);
851 }
852 }
853
Christine Franksc6890ab2017-06-23 14:28:21 -0700854 public static boolean isDemoUser(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800855 return UserManager.isDeviceInDemoMode(context)
856 && context.getSystemService(UserManager.class).isDemoUser();
Christine Franksc6890ab2017-06-23 14:28:21 -0700857 }
858
Justin Klaassen30257272017-08-08 21:58:05 -0700859 public static ComponentName getDeviceOwnerComponent(Context context) {
860 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
861 Context.DEVICE_POLICY_SERVICE);
862 return dpm.getDeviceOwnerComponentOnAnyUser();
Christine Franks14782222017-01-23 16:44:02 -0800863 }
Daniel Nishidfed8a22017-01-19 16:32:41 -0800864
865 /**
866 * Returns if a given user is a profile of another user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800867 * @param user The user whose profiles wibe checked.
Daniel Nishidfed8a22017-01-19 16:32:41 -0800868 * @param profile The (potential) profile.
869 * @return if the profile is actually a profile
870 */
871 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
872 return user.id == profile.id ||
873 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
874 && user.profileGroupId == profile.profileGroupId);
875 }
Daniel Nishi9f60f422017-02-15 15:25:48 -0800876
877 /**
878 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
879 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
880 */
881 @Nullable
882 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
883 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
884 VolumeInfo.ID_PRIVATE_INTERNAL);
Bonian Chen5e65da02019-11-08 07:40:35 +0800885 final VolumeInfo volume = sm.findVolumeById(volumeId);
Daniel Nishi9f60f422017-02-15 15:25:48 -0800886 return isVolumeValid(volume) ? volume : null;
887 }
888
jackqdyuleiddba9662017-03-08 19:35:02 -0800889 /**
jackqdyulei00015fb2017-08-22 11:25:30 -0700890 * Return {@code true} if the supplied package is device owner or profile owner of at
891 * least one user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800892 * @param userManager used to get profile owner app for each user
jackqdyulei00015fb2017-08-22 11:25:30 -0700893 * @param devicePolicyManager used to check whether it is device owner app
Sunny Shao7e866b62019-08-09 11:42:04 +0800894 * @param packageName package to check about
jackqdyulei00015fb2017-08-22 11:25:30 -0700895 */
896 public static boolean isProfileOrDeviceOwner(UserManager userManager,
Fan Zhangaab36de2018-03-30 16:58:28 -0700897 DevicePolicyManager devicePolicyManager, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800898 final List<UserInfo> userInfos = userManager.getUsers();
jackqdyulei00015fb2017-08-22 11:25:30 -0700899 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
900 return true;
901 }
902 for (int i = 0, size = userInfos.size(); i < size; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800903 final ComponentName cn = devicePolicyManager
904 .getProfileOwnerAsUser(userInfos.get(i).id);
jackqdyulei00015fb2017-08-22 11:25:30 -0700905 if (cn != null && cn.getPackageName().equals(packageName)) {
906 return true;
907 }
908 }
909 return false;
910 }
911
912 /**
Alex Johnston341f9952020-02-26 15:54:11 +0000913 * Return {@code true} if the supplied package is the device owner or profile owner of a
914 * given user.
915 *
916 * @param devicePolicyManager used to check whether it is device owner and profile owner app
917 * @param packageName package to check about
918 * @param userId the if of the relevant user
919 */
920 public static boolean isProfileOrDeviceOwner(DevicePolicyManager devicePolicyManager,
921 String packageName, int userId) {
922 if ((devicePolicyManager.getDeviceOwnerUserId() == userId)
923 && devicePolicyManager.isDeviceOwnerApp(packageName)) {
924 return true;
925 }
926 final ComponentName cn = devicePolicyManager.getProfileOwnerAsUser(userId);
927 if (cn != null && cn.getPackageName().equals(packageName)) {
928 return true;
929 }
930 return false;
931 }
932
933 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800934 * Return the resource id to represent the install status for an app
935 */
936 @StringRes
937 public static int getInstallationStatus(ApplicationInfo info) {
938 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
939 return R.string.not_installed;
940 }
941 return info.enabled ? R.string.installed : R.string.disabled;
942 }
943
Daniel Nishi9f60f422017-02-15 15:25:48 -0800944 private static boolean isVolumeValid(VolumeInfo volume) {
945 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
946 && volume.isMountedReadable();
947 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700948
PMS2263a05602017-06-14 07:10:15 +0000949 public static void setEditTextCursorPosition(EditText editText) {
950 editText.setSelection(editText.getText().length());
951 }
Felipe Lemebd884502017-09-15 18:16:21 -0700952
953 /**
954 * Sets the preference icon with a drawable that is scaled down to to avoid crashing Settings if
955 * it's too big.
956 */
957 public static void setSafeIcon(Preference pref, Drawable icon) {
958 Drawable safeIcon = icon;
Phil Weaver5a3e02d2018-03-08 17:38:46 -0800959 if ((icon != null) && !(icon instanceof VectorDrawable)) {
Felipe Lemebd884502017-09-15 18:16:21 -0700960 safeIcon = getSafeDrawable(icon, 500, 500);
961 }
962 pref.setIcon(safeIcon);
963 }
964
965 /**
966 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
967 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800968 * @param original original drawable, typically an app icon.
969 * @param maxWidth maximum width, in pixels.
Felipe Lemebd884502017-09-15 18:16:21 -0700970 * @param maxHeight maximum height, in pixels.
971 */
972 public static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
973 final int actualWidth = original.getMinimumWidth();
974 final int actualHeight = original.getMinimumHeight();
975
976 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
977 return original;
978 }
979
Bonian Chen5e65da02019-11-08 07:40:35 +0800980 final float scaleWidth = ((float) maxWidth) / actualWidth;
981 final float scaleHeight = ((float) maxHeight) / actualHeight;
982 final float scale = Math.min(scaleWidth, scaleHeight);
Felipe Lemebd884502017-09-15 18:16:21 -0700983 final int width = (int) (actualWidth * scale);
984 final int height = (int) (actualHeight * scale);
985
986 final Bitmap bitmap;
987 if (original instanceof BitmapDrawable) {
988 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
989 height, false);
990 } else {
Jason Chiuc78c54a2019-02-13 16:07:57 +0800991 bitmap = createBitmap(original, width, height);
Felipe Lemebd884502017-09-15 18:16:21 -0700992 }
993 return new BitmapDrawable(null, bitmap);
994 }
jackqdyuleifde637f2018-01-02 14:51:01 -0800995
996 /**
Jason Chiuc78c54a2019-02-13 16:07:57 +0800997 * Create an Icon pointing to a drawable.
Jason Chiu1217bbe2019-01-24 16:32:31 +0800998 */
Jason Chiuc78c54a2019-02-13 16:07:57 +0800999 public static IconCompat createIconWithDrawable(Drawable drawable) {
1000 Bitmap bitmap;
Jason Chiu1217bbe2019-01-24 16:32:31 +08001001 if (drawable instanceof BitmapDrawable) {
Sunny Shao7e866b62019-08-09 11:42:04 +08001002 bitmap = ((BitmapDrawable)drawable).getBitmap();
Jason Chiuc78c54a2019-02-13 16:07:57 +08001003 } else {
1004 final int width = drawable.getIntrinsicWidth();
1005 final int height = drawable.getIntrinsicHeight();
1006 bitmap = createBitmap(drawable,
1007 width > 0 ? width : 1,
1008 height > 0 ? height : 1);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001009 }
Jason Chiuc78c54a2019-02-13 16:07:57 +08001010 return IconCompat.createWithBitmap(bitmap);
1011 }
Jason Chiu1217bbe2019-01-24 16:32:31 +08001012
clownshen24827d32019-03-29 20:22:02 +08001013 /**
1014 * Creates a drawable with specified width and height.
1015 */
1016 public static Bitmap createBitmap(Drawable drawable, int width, int height) {
Jason Chiuc78c54a2019-02-13 16:07:57 +08001017 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Jason Chiu1217bbe2019-01-24 16:32:31 +08001018 final Canvas canvas = new Canvas(bitmap);
1019 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1020 drawable.draw(canvas);
1021 return bitmap;
1022 }
1023
1024 /**
jackqdyuleifde637f2018-01-02 14:51:01 -08001025 * Get the {@link Drawable} that represents the app icon
1026 */
1027 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
1028 PackageManager packageManager, String packageName, int userId) {
1029 try {
Tony Mak4e292812018-03-19 15:37:21 +00001030 final ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
1031 packageName, PackageManager.GET_META_DATA, userId);
jackqdyuleifde637f2018-01-02 14:51:01 -08001032 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
1033 } catch (PackageManager.NameNotFoundException e) {
1034 return packageManager.getDefaultActivityIcon();
1035 }
1036 }
Raff Tsai2928cd42018-11-05 16:10:19 +08001037
1038 /** Returns true if the current package is installed & enabled. */
1039 public static boolean isPackageEnabled(Context context, String packageName) {
1040 try {
1041 return context.getPackageManager().getApplicationInfo(packageName, 0).enabled;
1042 } catch (Exception e) {
1043 Log.e(TAG, "Error while retrieving application info for package " + packageName, e);
1044 }
1045 return false;
1046 }
markchien1dd1d792019-01-11 16:18:20 +08001047
1048 /** Get {@link Resources} by subscription id if subscription id is valid. */
1049 public static Resources getResourcesForSubId(Context context, int subId) {
1050 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1051 return SubscriptionManager.getResourcesForSubId(context, subId);
1052 } else {
1053 return context.getResources();
1054 }
1055 }
Ng Zhi Anb97bdc32019-02-01 12:39:31 -08001056
1057 /**
1058 * Returns true if SYSTEM_ALERT_WINDOW permission is available.
1059 * Starting from Q, SYSTEM_ALERT_WINDOW is disabled on low ram phones.
1060 */
1061 public static boolean isSystemAlertWindowEnabled(Context context) {
1062 // SYSTEM_ALERT_WINDOW is disabled on on low ram devices starting from Q
1063 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
1064 return !(am.isLowRamDevice() && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q));
1065 }
tmfangaed8f362019-03-18 16:56:09 +08001066
1067 /**
1068 * Adds a shadow appear/disappear animation to action bar scroll.
1069 *
1070 * <p/>
1071 * This method must be called after {@link Fragment#onCreate(Bundle)}.
1072 */
1073 public static void setActionBarShadowAnimation(Activity activity, Lifecycle lifecycle,
1074 View scrollView) {
1075 if (activity == null) {
1076 Log.w(TAG, "No activity, cannot style actionbar.");
1077 return;
1078 }
1079 final ActionBar actionBar = activity.getActionBar();
1080 if (actionBar == null) {
1081 Log.w(TAG, "No actionbar, cannot style actionbar.");
1082 return;
1083 }
1084 actionBar.setElevation(0);
1085
1086 if (lifecycle != null && scrollView != null) {
1087 ActionBarShadowController.attachToView(activity, lifecycle, scrollView);
1088 }
1089 }
Raff Tsaiafd494d2019-10-16 15:25:21 +08001090
1091 /**
1092 * Return correct target fragment based on argument
1093 *
1094 * @param activity the activity target fragment will be launched.
1095 * @param fragmentName initial target fragment name.
1096 * @param args fragment launch arguments.
1097 */
1098 public static Fragment getTargetFragment(Activity activity, String fragmentName, Bundle args) {
1099 Fragment f = null;
Raff Tsai84327f62019-11-15 11:02:25 +08001100 final boolean isPersonal = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001101 == ProfileSelectFragment.ProfileType.PERSONAL : false;
Raff Tsai84327f62019-11-15 11:02:25 +08001102 final boolean isWork = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001103 == ProfileSelectFragment.ProfileType.WORK : false;
Raff Tsai3fbdf342020-01-16 05:27:32 +08001104 if (activity.getSystemService(UserManager.class).getUserProfiles().size() > 1
Raff Tsaiafd494d2019-10-16 15:25:21 +08001105 && ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName) != null
Raff Tsai84327f62019-11-15 11:02:25 +08001106 && !isWork && !isPersonal) {
Raff Tsaiafd494d2019-10-16 15:25:21 +08001107 f = Fragment.instantiate(activity, ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName),
1108 args);
1109 } else {
1110 f = Fragment.instantiate(activity, fragmentName, args);
1111 }
1112 return f;
1113 }
Yanting Yang96127fe2020-03-20 12:04:09 +08001114
1115 /**
1116 * Returns true if current binder uid is Settings Intelligence.
1117 */
1118 public static boolean isSettingsIntelligence(Context context) {
1119 final int callingUid = Binder.getCallingUid();
1120 final String callingPackage = context.getPackageManager().getPackagesForUid(callingUid)[0];
1121 final boolean isSettingsIntelligence = TextUtils.equals(callingPackage,
1122 context.getString(R.string.config_settingsintelligence_package_name));
1123 return isSettingsIntelligence;
1124 }
Jason Chiu8ac1e4d2020-05-11 16:13:47 +08001125
1126 /**
1127 * Returns true if the night mode is enabled.
1128 */
1129 public static boolean isNightMode(Context context) {
1130 final int currentNightMode =
1131 context.getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
1132 return currentNightMode == Configuration.UI_MODE_NIGHT_YES;
1133 }
Tim Pengdf467882020-06-24 13:10:01 +08001134
1135 /**
1136 * Returns a bitmap with rounded corner.
1137 *
1138 * @param context application context.
1139 * @param source bitmap to apply round corner.
1140 * @param cornerRadius corner radius value.
1141 */
1142 public static Bitmap convertCornerRadiusBitmap(@NonNull Context context,
1143 @NonNull Bitmap source, @NonNull float cornerRadius) {
1144 final Bitmap roundedBitmap = Bitmap.createBitmap(source.getWidth(), source.getHeight(),
1145 Bitmap.Config.ARGB_8888);
1146 final RoundedBitmapDrawable drawable =
1147 RoundedBitmapDrawableFactory.create(context.getResources(), source);
1148 drawable.setAntiAlias(true);
1149 drawable.setCornerRadius(cornerRadius);
1150 final Canvas canvas = new Canvas(roundedBitmap);
1151 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1152 drawable.draw(canvas);
1153 return roundedBitmap;
1154 }
Zoey Chen3abe48e2020-10-28 22:46:48 +08001155
1156 public static boolean isProviderModelEnabled(Context context) {
1157 return FeatureFlagUtils.isEnabled(context, FeatureFlagUtils.SETTINGS_PROVIDER_MODEL);
1158 }
1159
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001160}