blob: 9b257b60b7ea13443fa7ecac771adbd0ff0c4eee [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;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020045import android.content.res.Resources;
Jason Monkb5aa73f2015-03-31 12:59:33 -040046import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070047import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070048import android.graphics.Bitmap;
Felipe Lemebd884502017-09-15 18:16:21 -070049import android.graphics.Canvas;
50import android.graphics.drawable.BitmapDrawable;
51import android.graphics.drawable.Drawable;
Phil Weaver5a3e02d2018-03-08 17:38:46 -080052import android.graphics.drawable.VectorDrawable;
Kevin Chyn4882e872018-06-25 17:58:31 -070053import android.hardware.face.FaceManager;
Jeff Sharkeyab508072016-10-11 14:25:22 -060054import android.hardware.fingerprint.FingerprintManager;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080055import android.net.ConnectivityManager;
56import android.net.LinkProperties;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070057import android.net.Network;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070058import android.net.wifi.WifiManager;
Amith Yamasania4379d62011-07-22 10:34:58 -070059import android.os.BatteryManager;
Ng Zhi Anb97bdc32019-02-01 12:39:31 -080060import android.os.Build;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020061import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010062import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040063import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010064import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040065import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070066import android.os.UserHandle;
67import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080068import android.os.storage.StorageManager;
Daniel Nishi9f60f422017-02-15 15:25:48 -080069import android.os.storage.VolumeInfo;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070070import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070071import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070072import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070073import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070074import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070075import android.provider.ContactsContract.RawContacts;
markchien1dd1d792019-01-11 16:18:20 +080076import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070077import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040078import android.text.Spannable;
79import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020080import android.text.TextUtils;
Jason Monkb37e2882016-01-11 14:27:20 -050081import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040082import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070083import android.util.ArraySet;
Raff Tsaiafd494d2019-10-16 15:25:21 +080084import android.util.FeatureFlagUtils;
jackqdyuleifde637f2018-01-02 14:51:01 -080085import android.util.IconDrawableFactory;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010086import android.util.Log;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000087import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070088import android.view.View;
89import android.view.ViewGroup;
PMS2263a05602017-06-14 07:10:15 +000090import android.widget.EditText;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070091import android.widget.ListView;
92import android.widget.TabWidget;
Fan Zhangcc335d92016-09-29 14:37:14 -070093
Fan Zhang23f8d592018-08-28 15:11:40 -070094import androidx.annotation.StringRes;
Jason Chiuc78c54a2019-02-13 16:07:57 +080095import androidx.core.graphics.drawable.IconCompat;
Fan Zhang23f8d592018-08-28 15:11:40 -070096import androidx.fragment.app.Fragment;
tmfangaed8f362019-03-18 16:56:09 +080097import androidx.lifecycle.Lifecycle;
Fan Zhang23f8d592018-08-28 15:11:40 -070098import androidx.preference.Preference;
99import androidx.preference.PreferenceGroup;
100
Ricky Wai616342b2016-04-13 10:40:22 +0100101import com.android.internal.app.UnlaunchableAppActivity;
Ricky Wai72500162016-06-07 16:54:25 +0100102import com.android.internal.util.ArrayUtils;
Rubin Xu3231afe2016-08-24 10:15:07 +0100103import com.android.internal.widget.LockPatternUtils;
Antony Sargent627f14b2019-03-04 16:00:59 -0800104import com.android.settings.core.FeatureFlags;
Raff Tsaiafd494d2019-10-16 15:25:21 +0800105import com.android.settings.dashboard.profileselector.ProfileFragmentBridge;
Raff Tsai84327f62019-11-15 11:02:25 +0800106import com.android.settings.dashboard.profileselector.ProfileSelectFragment;
Jeff Sharkey219ec912017-12-19 14:57:39 -0700107import com.android.settings.password.ChooseLockSettingsHelper;
tmfangaed8f362019-03-18 16:56:09 +0800108import com.android.settingslib.widget.ActionBarShadowController;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700109
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800110import java.net.InetAddress;
111import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700112import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900113import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800114
Jason Monk27985e12016-01-08 14:13:05 -0500115public final class Utils extends com.android.settingslib.Utils {
116
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100117 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100118
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800119 /**
120 * Set the preference's title to the matching activity's label.
121 */
122 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
123
Fan Zhangc3fd2892019-01-29 16:00:19 -0800124 public static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100125
Jason Monkbeb171d2015-05-21 15:24:37 -0400126 public static final String OS_PKG = "os";
127
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200128 /**
Svet Ganov864765f2019-04-05 19:00:05 -0700129 * Whether to disable the new device identifier access restrictions.
130 */
131 public static final String PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED =
132 "device_identifier_access_restrictions_disabled";
133
134 /**
Joel Galenson2118f8a2019-05-31 07:54:20 -0700135 * Whether to show the Permissions Hub.
136 */
137 public static final String PROPERTY_PERMISSIONS_HUB_ENABLED = "permissions_hub_enabled";
138
139 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800140 * Finds a matching activity for a preference's intent. If a matching
141 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800142 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800143 * @param context The context.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800144 * @param parentPreferenceGroup The preference group that contains the
Sunny Shao7e866b62019-08-09 11:42:04 +0800145 * preference whose intent is being resolved.
146 * @param preferenceKey The key of the preference whose intent is being
147 * resolved.
148 * @param flags 0 or one or more of
149 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
150 * .
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800151 * @return Whether an activity was found. If false, the preference was
Sunny Shao7e866b62019-08-09 11:42:04 +0800152 * removed.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800153 */
154 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
155 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800156
Bonian Chen5e65da02019-11-08 07:40:35 +0800157 final Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800158 if (preference == null) {
159 return false;
160 }
Ying Wanga7188322010-01-04 18:45:10 -0800161
Bonian Chen5e65da02019-11-08 07:40:35 +0800162 final Intent intent = preference.getIntent();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800163 if (intent != null) {
164 // Find the activity that is in the system image
Bonian Chen5e65da02019-11-08 07:40:35 +0800165 final PackageManager pm = context.getPackageManager();
166 final List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
167 final int listSize = list.size();
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800168 for (int i = 0; i < listSize; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800169 final ResolveInfo resolveInfo = list.get(i);
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800170 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
171 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800172
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800173 // Replace the intent with this specific activity
174 preference.setIntent(new Intent().setClassName(
175 resolveInfo.activityInfo.packageName,
176 resolveInfo.activityInfo.name));
177
178 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
179 // Set the preference title to the activity's label
180 preference.setTitle(resolveInfo.loadLabel(pm));
181 }
Ying Wanga7188322010-01-04 18:45:10 -0800182
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800183 return true;
184 }
185 }
186 }
187
188 // Did not find a matching activity, so remove the preference
189 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800190
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900191 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800192 }
Ying Wanga7188322010-01-04 18:45:10 -0800193
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200194 /**
Ying Wanga7188322010-01-04 18:45:10 -0800195 * Returns true if Monkey is running.
196 */
197 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700198 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800199 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700200
201 /**
202 * Returns whether the device is voice-capable (meaning, it is also a phone).
203 */
204 public static boolean isVoiceCapable(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800205 final TelephonyManager telephony =
Amith Yamasani60133dd2010-09-11 14:17:31 -0700206 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
207 return telephony != null && telephony.isVoiceCapable();
208 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800209
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800210 /**
211 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
212 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900213 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800214 */
215 public static String getWifiIpAddresses(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800216 final WifiManager wifiManager = context.getSystemService(WifiManager.class);
217 final Network currentNetwork = wifiManager.getCurrentNetwork();
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700218 if (currentNetwork != null) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800219 final ConnectivityManager cm = (ConnectivityManager)
Sunny Shao7e866b62019-08-09 11:42:04 +0800220 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800221 final LinkProperties prop = cm.getLinkProperties(currentNetwork);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700222 return formatIpAddresses(prop);
223 }
224 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700225 }
226
Amith Yamasani6822b742011-10-17 16:41:00 -0700227 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800228 if (prop == null) return null;
Bonian Chen5e65da02019-11-08 07:40:35 +0800229 final Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800230 // If there are no entries, return null
231 if (!iter.hasNext()) return null;
232 // Concatenate all available addresses, comma separated
233 String addresses = "";
234 while (iter.hasNext()) {
235 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900236 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800237 }
238 return addresses;
239 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900240
241 public static Locale createLocaleFromString(String localeStr) {
242 // TODO: is there a better way to actually construct a locale that will match?
243 // The main problem is, on top of Java specs, locale.toString() and
244 // new Locale(locale.toString()).toString() do not return equal() strings in
245 // many cases, because the constructor takes the only string as the language
246 // code. So : new Locale("en", "US").toString() => "en_US"
247 // And : new Locale("en_US").toString() => "en_us"
Sunny Shao7e866b62019-08-09 11:42:04 +0800248 if (null == localeStr)
Jean Chalard71ad1f42011-05-12 15:06:16 +0900249 return Locale.getDefault();
Bonian Chen5e65da02019-11-08 07:40:35 +0800250 final String[] brokenDownLocale = localeStr.split("_", 3);
Jean Chalard71ad1f42011-05-12 15:06:16 +0900251 // split may not return a 0-length array.
252 if (1 == brokenDownLocale.length) {
253 return new Locale(brokenDownLocale[0]);
254 } else if (2 == brokenDownLocale.length) {
255 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
256 } else {
257 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
258 }
259 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700260
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900261 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
262 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
263 }
264
Amith Yamasania4379d62011-07-22 10:34:58 -0700265 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700266 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700267 }
268
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700269 /**
270 * Prepare a custom preferences layout, moving padding to {@link ListView}
271 * when outside scrollbars are requested. Usually used to display
272 * {@link ListView} and {@link TabWidget} with correct padding.
273 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700274 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800275 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700276 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700277 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700278 final Resources res = list.getResources();
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700279 final int paddingBottom = res.getDimensionPixelSize(
280 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700281
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700282 if (parent instanceof PreferenceFrameLayout) {
283 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700284 }
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800285 list.setPaddingRelative(0 /* start */, 0 /* top */, 0 /* end */, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700286 }
287 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700288
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700289 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700290 final Resources res = view.getResources();
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700291
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800292 final int paddingStart = additive ? view.getPaddingStart() : 0;
293 final int paddingEnd = additive ? view.getPaddingEnd() : 0;
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700294 final int paddingBottom = res.getDimensionPixelSize(
295 com.android.internal.R.dimen.preference_fragment_padding_bottom);
296
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700297 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700298 }
299
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700300 public static String getMeProfileName(Context context, boolean full) {
301 if (full) {
302 return getProfileDisplayName(context);
303 } else {
304 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700305 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700306 }
307
308 private static String getShorterNameIfPossible(Context context) {
309 final String given = getLocalProfileGivenName(context);
310 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
311 }
312
313 private static String getLocalProfileGivenName(Context context) {
314 final ContentResolver cr = context.getContentResolver();
315
316 // Find the raw contact ID for the local ME profile raw contact.
317 final long localRowProfileId;
318 final Cursor localRawProfile = cr.query(
319 Profile.CONTENT_RAW_CONTACTS_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800320 new String[] {RawContacts._ID},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700321 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
322 RawContacts.ACCOUNT_NAME + " IS NULL",
323 null, null);
324 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700325
326 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700327 if (!localRawProfile.moveToFirst()) {
328 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700329 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700330 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700331 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700332 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700333 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700334
335 // Find the structured name for the raw contact.
336 final Cursor structuredName = cr.query(
337 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
Sunny Shao7e866b62019-08-09 11:42:04 +0800338 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
339 CommonDataKinds.StructuredName.FAMILY_NAME},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700340 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
341 null, null);
342 if (structuredName == null) return null;
343
344 try {
345 if (!structuredName.moveToFirst()) {
346 return null;
347 }
348 String partialName = structuredName.getString(0);
349 if (TextUtils.isEmpty(partialName)) {
350 partialName = structuredName.getString(1);
351 }
352 return partialName;
353 } finally {
354 structuredName.close();
355 }
356 }
357
358 private static final String getProfileDisplayName(Context context) {
359 final ContentResolver cr = context.getContentResolver();
360 final Cursor profile = cr.query(Profile.CONTENT_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800361 new String[] {Profile.DISPLAY_NAME}, null, null, null);
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700362 if (profile == null) return null;
363
364 try {
365 if (!profile.moveToFirst()) {
366 return null;
367 }
368 return profile.getString(0);
369 } finally {
370 profile.close();
371 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700372 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700373
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700374 public static boolean hasMultipleUsers(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800375 return context.getSystemService(UserManager.class)
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700376 .getUsers().size() > 1;
377 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700378
379 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100380 * Returns the managed profile of the current user or {@code null} if none is found or a profile
381 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100382 */
383 public static UserHandle getManagedProfile(UserManager userManager) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800384 final List<UserHandle> userProfiles = userManager.getUserProfiles();
Aarthi Balachanderd0f83592018-07-10 17:04:53 -0700385 for (UserHandle profile : userProfiles) {
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100386 if (profile.getIdentifier() == userManager.getUserHandle()) {
387 continue;
388 }
389 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
390 if (userInfo.isManagedProfile()) {
391 return profile;
392 }
393 }
394 return null;
395 }
396
397 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100398 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
399 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
400 */
401 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
402 // TODO: Call getManagedProfileId from here once Robolectric supports
403 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
404 // yet another implementation that loops over user profiles in this method). In the meantime
405 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
406 // used for Settings Robolectric tests).
407 final int myUserId = UserHandle.myUserId();
Bonian Chen5e65da02019-11-08 07:40:35 +0800408 final List<UserInfo> profiles = userManager.getProfiles(myUserId);
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100409 final int count = profiles.size();
410 for (int i = 0; i < count; i++) {
411 final UserInfo profile = profiles.get(i);
412 if (profile.isManagedProfile()
413 && profile.getUserHandle().getIdentifier() != myUserId) {
414 return profile.getUserHandle();
415 }
416 }
417 return null;
418 }
419
420 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000421 * Retrieves the id for the given user's managed profile.
422 *
423 * @return the managed profile id or UserHandle.USER_NULL if there is none.
424 */
425 public static int getManagedProfileId(UserManager um, int parentUserId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800426 final int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700427 for (int profileId : profileIds) {
428 if (profileId != parentUserId) {
429 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000430 }
431 }
432 return UserHandle.USER_NULL;
433 }
434
435 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100436 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000437 * <p>
438 * User would be retrieved in this order:
439 * <ul>
440 * <li> If this activity is launched from other user, return that user id.
441 * <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 +0800442 * extra in the arguments or intent extras.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000443 * <li> Otherwise, return UserHandle.myUserId().
444 * </ul>
445 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100446 * Note: This is secure in the sense that it only returns a target user different to the current
447 * one if the app launching this activity is the Settings app itself, running in the same user
448 * 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 +0100449 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100450 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000451 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800452 final UserHandle currentUser = new UserHandle(UserHandle.myUserId());
453 final IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100454 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800455 final String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
456 final boolean launchedFromSettingsApp =
457 SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100458
Bonian Chen5e65da02019-11-08 07:40:35 +0800459 final UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100460 am.getLaunchedFromUid(activityToken)));
461 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
462 // Check it's secure
463 if (isProfileOf(um, launchedFromUser)) {
464 return launchedFromUser;
465 }
466 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800467 final UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100468 if (extrasUser != null && !extrasUser.equals(currentUser)) {
469 // Check it's secure
470 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
471 return extrasUser;
472 }
473 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800474 final UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100475 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
476 // Check it's secure
477 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
478 return argumentsUser;
479 }
480 }
481 } catch (RemoteException e) {
482 // Should not happen
483 Log.v(TAG, "Could not talk to activity manager.", e);
484 }
485 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000486 }
487
488 /**
489 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
490 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
491 */
Sunny Shao7e866b62019-08-09 11:42:04 +0800492 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
Tony Mak8f41b9b2016-11-23 11:36:18 +0000493 if (bundle == null) {
494 return null;
495 }
496 final UserHandle user = bundle.getParcelable(EXTRA_USER);
497 if (user != null) {
498 return user;
499 }
500 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
501 if (userId != -1) {
502 return UserHandle.of(userId);
503 }
504 return null;
505 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100506
Sunny Shao7e866b62019-08-09 11:42:04 +0800507 /**
508 * Returns true if the user provided is in the same profiles group as the current user.
509 */
510 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
511 if (um == null || otherUser == null) return false;
512 return (UserHandle.myUserId() == otherUser.getIdentifier())
513 || um.getUserProfiles().contains(otherUser);
514 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530515
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100516 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800517 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
518 * @param userManager Instance of UserManager
Sunny Shao7e866b62019-08-09 11:42:04 +0800519 * @param checkUser The user to check the existence of.
Amith Yamasani45f86232014-11-19 17:12:46 -0800520 * @return UserInfo of the user or null for non-existent user.
521 */
522 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
523 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
524 final int checkUserId = checkUser.getIdentifier();
525 for (UserInfo user : users) {
526 if (user.id == checkUserId) {
527 return user;
528 }
529 }
530 return null;
531 }
532
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000533 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
534 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
535 com.android.internal.R.styleable.Preference,
536 com.android.internal.R.attr.preferenceCategoryStyle, 0);
537 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
538 0);
539 a.recycle();
540 return inflater.inflate(resId, parent, false);
541 }
542
Christopher Tatea08a2252015-07-01 16:52:43 -0700543 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800544 final List<IntentFilterVerificationInfo> iviList =
545 pm.getIntentFilterVerifications(packageName);
546 final List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
Christopher Tatea08a2252015-07-01 16:52:43 -0700547
Bonian Chen5e65da02019-11-08 07:40:35 +0800548 final ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800549 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700550 for (IntentFilterVerificationInfo ivi : iviList) {
551 for (String host : ivi.getDomains()) {
552 result.add(host);
553 }
554 }
555 }
556 if (filters != null && filters.size() > 0) {
557 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700558 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
559 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
Sunny Shao7e866b62019-08-09 11:42:04 +0800560 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700561 result.addAll(filter.getHostsList());
562 }
563 }
564 }
565 return result;
566 }
567
Sudheer Shankabc956302015-04-09 12:19:53 +0100568 /**
569 * Returns the application info of the currently installed MDM package.
570 */
571 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800572 final DevicePolicyManager dpm =
Sudheer Shankabc956302015-04-09 12:19:53 +0100573 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
Bonian Chen5e65da02019-11-08 07:40:35 +0800574 final ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
Sudheer Shankabc956302015-04-09 12:19:53 +0100575 if (mdmPackage == null) {
576 return null;
577 }
Bonian Chen5e65da02019-11-08 07:40:35 +0800578 final String mdmPackageName = mdmPackage.getPackageName();
Sudheer Shankabc956302015-04-09 12:19:53 +0100579 try {
Bonian Chen5e65da02019-11-08 07:40:35 +0800580 final IPackageManager ipm = AppGlobals.getPackageManager();
581 final ApplicationInfo mdmApplicationInfo =
Sudheer Shankabc956302015-04-09 12:19:53 +0100582 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
583 return mdmApplicationInfo;
584 } catch (RemoteException e) {
585 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
586 + ", userId " + profileId, e);
587 return null;
588 }
589 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400590
591 public static boolean isBandwidthControlEnabled() {
592 final INetworkManagementService netManager = INetworkManagementService.Stub
593 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
594 try {
595 return netManager.isBandwidthControlEnabled();
596 } catch (RemoteException e) {
597 return false;
598 }
599 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400600
601 /**
602 * Returns an accessible SpannableString.
Sunny Shao7e866b62019-08-09 11:42:04 +0800603 * @param displayText the text to display
Julia Reynoldsce25af42015-07-08 16:56:31 -0400604 * @param accessibileText the text text-to-speech engines should read
605 */
606 public static SpannableString createAccessibleSequence(CharSequence displayText,
607 String accessibileText) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800608 final SpannableString str = new SpannableString(displayText);
Julia Reynoldsce25af42015-07-08 16:56:31 -0400609 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
610 displayText.length(),
611 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
612 return str;
613 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700614
Clara Bayarrife432e82015-10-12 12:07:02 +0100615 /**
Jeff Sharkey219ec912017-12-19 14:57:39 -0700616 * Returns the user id present in the bundle with
617 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
Clara Bayarrife432e82015-10-12 12:07:02 +0100618 *
Jeff Sharkey219ec912017-12-19 14:57:39 -0700619 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800620 * current user group.
Clara Bayarrife432e82015-10-12 12:07:02 +0100621 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000622 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700623 return getUserIdFromBundle(context, bundle, false);
624 }
625
626 /**
627 * Returns the user id present in the bundle with
628 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
629 *
630 * @param isInternal indicating if the caller is "internal" to the system,
Sunny Shao7e866b62019-08-09 11:42:04 +0800631 * meaning we're willing to trust extras like
632 * {@link ChooseLockSettingsHelper#EXTRA_ALLOW_ANY_USER}.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700633 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800634 * current user group.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700635 */
636 public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
Clara Bayarrife432e82015-10-12 12:07:02 +0100637 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +0000638 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +0100639 }
Jeff Sharkey219ec912017-12-19 14:57:39 -0700640 final boolean allowAnyUser = isInternal
641 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_ALLOW_ANY_USER, false);
Bonian Chen5e65da02019-11-08 07:40:35 +0800642 final int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700643 if (userId == LockPatternUtils.USER_FRP) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700644 return allowAnyUser ? userId : enforceSystemUser(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700645 } else {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700646 return allowAnyUser ? userId : enforceSameOwner(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700647 }
648 }
649
650 /**
651 * Returns the given user id if the current user is the system user.
652 *
653 * @throws SecurityException if the current user is not the system user.
654 */
655 public static int enforceSystemUser(Context context, int userId) {
656 if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
657 return userId;
658 }
659 throw new SecurityException("Given user id " + userId + " must only be used from "
660 + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100661 }
662
663 /**
664 * Returns the given user id if it belongs to the current user.
665 *
666 * @throws SecurityException if the given userId does not belong to the current user group.
667 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000668 public static int enforceSameOwner(Context context, int userId) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800669 final UserManager um = context.getSystemService(UserManager.class);
Ricky Wai72500162016-06-07 16:54:25 +0100670 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
671 if (ArrayUtils.contains(profileIds, userId)) {
672 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +0100673 }
Ricky Wai72500162016-06-07 16:54:25 +0100674 throw new SecurityException("Given user id " + userId + " does not belong to user "
675 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100676 }
677
Benjamin Franz194300d2016-01-13 12:16:25 +0000678 /**
679 * Returns the effective credential owner of the calling user.
680 */
681 public static int getCredentialOwnerUserId(Context context) {
682 return getCredentialOwnerUserId(context, UserHandle.myUserId());
683 }
684
685 /**
686 * Returns the user id of the credential owner of the given user id.
687 */
688 public static int getCredentialOwnerUserId(Context context, int userId) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800689 final UserManager um = context.getSystemService(UserManager.class);
Benjamin Franz194300d2016-01-13 12:16:25 +0000690 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700691 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500692
Jason Monkb37e2882016-01-11 14:27:20 -0500693 private static final StringBuilder sBuilder = new StringBuilder(50);
694 private static final java.util.Formatter sFormatter = new java.util.Formatter(
695 sBuilder, Locale.getDefault());
696
697 public static String formatDateRange(Context context, long start, long end) {
698 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
699
700 synchronized (sBuilder) {
701 sBuilder.setLength(0);
702 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
703 .toString();
704 }
705 }
Jason Monk91e2f892016-02-23 15:31:09 -0500706
Bernard Chau88d523b2016-04-14 15:08:28 +0100707 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100708 int userId) {
709 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
710 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
711 context.startActivity(intent);
712 return true;
713 }
714 return false;
715 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700716
Rubin Xu3231afe2016-08-24 10:15:07 +0100717 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
718 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800719 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100720 ActivityManager.FLAG_AND_LOCKED)) {
721 return false;
722 }
723 } catch (RemoteException e) {
724 return false;
725 }
726 if (!(new LockPatternUtils(context)).isSecure(userId)) {
727 return false;
728 }
Robin Leecccf3242017-02-10 15:32:49 +0000729 return confirmWorkProfileCredentials(context, userId);
730 }
731
Robin Leecccf3242017-02-10 15:32:49 +0000732 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100733 final KeyguardManager km = (KeyguardManager) context.getSystemService(
734 Context.KEYGUARD_SERVICE);
735 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
736 if (unlockIntent != null) {
737 context.startActivity(unlockIntent);
738 return true;
739 } else {
740 return false;
741 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100742 }
743
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700744 public static CharSequence getApplicationLabel(Context context, String packageName) {
745 try {
746 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
747 packageName,
748 PackageManager.MATCH_DISABLED_COMPONENTS
Sunny Shao7e866b62019-08-09 11:42:04 +0800749 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700750 return appInfo.loadLabel(context.getPackageManager());
751 } catch (PackageManager.NameNotFoundException e) {
Raff Tsai376ce872020-01-06 00:42:35 +0800752 Log.e(TAG, "Unable to find info for package: " + packageName);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700753 }
754 return null;
755 }
Jason Monk75199542016-05-06 15:09:32 -0400756
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600757 public static boolean isPackageDirectBootAware(Context context, String packageName) {
758 try {
759 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
760 packageName, 0);
761 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
762 } catch (NameNotFoundException ignored) {
763 }
764 return false;
765 }
Andre Lago3e398c82016-07-25 14:12:28 +0100766
767 /**
768 * Returns a context created from the given context for the given user, or null if it fails
769 */
770 public static Context createPackageContextAsUser(Context context, int userId) {
771 try {
772 return context.createPackageContextAsUser(
773 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
774 } catch (PackageManager.NameNotFoundException e) {
775 Log.e(TAG, "Failed to create user context", e);
776 }
777 return null;
778 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600779
780 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
781 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800782 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600783 } else {
784 return null;
785 }
786 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800787
Kevin Chyn82792cc2017-07-20 00:15:44 -0700788 public static boolean hasFingerprintHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800789 final FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
Kevin Chyn82792cc2017-07-20 00:15:44 -0700790 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
791 }
792
Kevin Chyn4882e872018-06-25 17:58:31 -0700793 public static FaceManager getFaceManagerOrNull(Context context) {
794 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
795 return (FaceManager) context.getSystemService(Context.FACE_SERVICE);
796 } else {
797 return null;
798 }
799 }
800
801 public static boolean hasFaceHardware(Context context) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800802 final FaceManager faceManager = getFaceManagerOrNull(context);
Kevin Chyn4882e872018-06-25 17:58:31 -0700803 return faceManager != null && faceManager.isHardwareDetected();
804 }
805
Daniel Nishi31027da2017-01-19 14:03:57 -0800806 /**
807 * Launches an intent which may optionally have a user id defined.
808 * @param fragment Fragment to use to launch the activity.
Sunny Shao7e866b62019-08-09 11:42:04 +0800809 * @param intent Intent to launch.
Daniel Nishi31027da2017-01-19 14:03:57 -0800810 */
811 public static void launchIntent(Fragment fragment, Intent intent) {
812 try {
813 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
814
815 if (userId == -1) {
816 fragment.startActivity(intent);
817 } else {
818 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
819 }
820 } catch (ActivityNotFoundException e) {
821 Log.w(TAG, "No activity found for " + intent);
822 }
823 }
824
Christine Franksc6890ab2017-06-23 14:28:21 -0700825 public static boolean isDemoUser(Context context) {
Bonian Chenf399bd12020-01-09 14:50:03 +0800826 return UserManager.isDeviceInDemoMode(context)
827 && context.getSystemService(UserManager.class).isDemoUser();
Christine Franksc6890ab2017-06-23 14:28:21 -0700828 }
829
Justin Klaassen30257272017-08-08 21:58:05 -0700830 public static ComponentName getDeviceOwnerComponent(Context context) {
831 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
832 Context.DEVICE_POLICY_SERVICE);
833 return dpm.getDeviceOwnerComponentOnAnyUser();
Christine Franks14782222017-01-23 16:44:02 -0800834 }
Daniel Nishidfed8a22017-01-19 16:32:41 -0800835
836 /**
837 * Returns if a given user is a profile of another user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800838 * @param user The user whose profiles wibe checked.
Daniel Nishidfed8a22017-01-19 16:32:41 -0800839 * @param profile The (potential) profile.
840 * @return if the profile is actually a profile
841 */
842 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
843 return user.id == profile.id ||
844 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
845 && user.profileGroupId == profile.profileGroupId);
846 }
Daniel Nishi9f60f422017-02-15 15:25:48 -0800847
848 /**
849 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
850 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
851 */
852 @Nullable
853 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
854 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
855 VolumeInfo.ID_PRIVATE_INTERNAL);
Bonian Chen5e65da02019-11-08 07:40:35 +0800856 final VolumeInfo volume = sm.findVolumeById(volumeId);
Daniel Nishi9f60f422017-02-15 15:25:48 -0800857 return isVolumeValid(volume) ? volume : null;
858 }
859
jackqdyuleiddba9662017-03-08 19:35:02 -0800860 /**
jackqdyulei00015fb2017-08-22 11:25:30 -0700861 * Return {@code true} if the supplied package is device owner or profile owner of at
862 * least one user.
Sunny Shao7e866b62019-08-09 11:42:04 +0800863 * @param userManager used to get profile owner app for each user
jackqdyulei00015fb2017-08-22 11:25:30 -0700864 * @param devicePolicyManager used to check whether it is device owner app
Sunny Shao7e866b62019-08-09 11:42:04 +0800865 * @param packageName package to check about
jackqdyulei00015fb2017-08-22 11:25:30 -0700866 */
867 public static boolean isProfileOrDeviceOwner(UserManager userManager,
Fan Zhangaab36de2018-03-30 16:58:28 -0700868 DevicePolicyManager devicePolicyManager, String packageName) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800869 final List<UserInfo> userInfos = userManager.getUsers();
jackqdyulei00015fb2017-08-22 11:25:30 -0700870 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
871 return true;
872 }
873 for (int i = 0, size = userInfos.size(); i < size; i++) {
Bonian Chen5e65da02019-11-08 07:40:35 +0800874 final ComponentName cn = devicePolicyManager
875 .getProfileOwnerAsUser(userInfos.get(i).id);
jackqdyulei00015fb2017-08-22 11:25:30 -0700876 if (cn != null && cn.getPackageName().equals(packageName)) {
877 return true;
878 }
879 }
880 return false;
881 }
882
883 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800884 * Return the resource id to represent the install status for an app
885 */
886 @StringRes
887 public static int getInstallationStatus(ApplicationInfo info) {
888 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
889 return R.string.not_installed;
890 }
891 return info.enabled ? R.string.installed : R.string.disabled;
892 }
893
Daniel Nishi9f60f422017-02-15 15:25:48 -0800894 private static boolean isVolumeValid(VolumeInfo volume) {
895 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
896 && volume.isMountedReadable();
897 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700898
PMS2263a05602017-06-14 07:10:15 +0000899 public static void setEditTextCursorPosition(EditText editText) {
900 editText.setSelection(editText.getText().length());
901 }
Felipe Lemebd884502017-09-15 18:16:21 -0700902
903 /**
904 * Sets the preference icon with a drawable that is scaled down to to avoid crashing Settings if
905 * it's too big.
906 */
907 public static void setSafeIcon(Preference pref, Drawable icon) {
908 Drawable safeIcon = icon;
Phil Weaver5a3e02d2018-03-08 17:38:46 -0800909 if ((icon != null) && !(icon instanceof VectorDrawable)) {
Felipe Lemebd884502017-09-15 18:16:21 -0700910 safeIcon = getSafeDrawable(icon, 500, 500);
911 }
912 pref.setIcon(safeIcon);
913 }
914
915 /**
916 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
917 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800918 * @param original original drawable, typically an app icon.
919 * @param maxWidth maximum width, in pixels.
Felipe Lemebd884502017-09-15 18:16:21 -0700920 * @param maxHeight maximum height, in pixels.
921 */
922 public static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
923 final int actualWidth = original.getMinimumWidth();
924 final int actualHeight = original.getMinimumHeight();
925
926 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
927 return original;
928 }
929
Bonian Chen5e65da02019-11-08 07:40:35 +0800930 final float scaleWidth = ((float) maxWidth) / actualWidth;
931 final float scaleHeight = ((float) maxHeight) / actualHeight;
932 final float scale = Math.min(scaleWidth, scaleHeight);
Felipe Lemebd884502017-09-15 18:16:21 -0700933 final int width = (int) (actualWidth * scale);
934 final int height = (int) (actualHeight * scale);
935
936 final Bitmap bitmap;
937 if (original instanceof BitmapDrawable) {
938 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
939 height, false);
940 } else {
Jason Chiuc78c54a2019-02-13 16:07:57 +0800941 bitmap = createBitmap(original, width, height);
Felipe Lemebd884502017-09-15 18:16:21 -0700942 }
943 return new BitmapDrawable(null, bitmap);
944 }
jackqdyuleifde637f2018-01-02 14:51:01 -0800945
946 /**
Jason Chiuc78c54a2019-02-13 16:07:57 +0800947 * Create an Icon pointing to a drawable.
Jason Chiu1217bbe2019-01-24 16:32:31 +0800948 */
Jason Chiuc78c54a2019-02-13 16:07:57 +0800949 public static IconCompat createIconWithDrawable(Drawable drawable) {
950 Bitmap bitmap;
Jason Chiu1217bbe2019-01-24 16:32:31 +0800951 if (drawable instanceof BitmapDrawable) {
Sunny Shao7e866b62019-08-09 11:42:04 +0800952 bitmap = ((BitmapDrawable)drawable).getBitmap();
Jason Chiuc78c54a2019-02-13 16:07:57 +0800953 } else {
954 final int width = drawable.getIntrinsicWidth();
955 final int height = drawable.getIntrinsicHeight();
956 bitmap = createBitmap(drawable,
957 width > 0 ? width : 1,
958 height > 0 ? height : 1);
Jason Chiu1217bbe2019-01-24 16:32:31 +0800959 }
Jason Chiuc78c54a2019-02-13 16:07:57 +0800960 return IconCompat.createWithBitmap(bitmap);
961 }
Jason Chiu1217bbe2019-01-24 16:32:31 +0800962
clownshen24827d32019-03-29 20:22:02 +0800963 /**
964 * Creates a drawable with specified width and height.
965 */
966 public static Bitmap createBitmap(Drawable drawable, int width, int height) {
Jason Chiuc78c54a2019-02-13 16:07:57 +0800967 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Jason Chiu1217bbe2019-01-24 16:32:31 +0800968 final Canvas canvas = new Canvas(bitmap);
969 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
970 drawable.draw(canvas);
971 return bitmap;
972 }
973
974 /**
jackqdyuleifde637f2018-01-02 14:51:01 -0800975 * Get the {@link Drawable} that represents the app icon
976 */
977 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
978 PackageManager packageManager, String packageName, int userId) {
979 try {
Tony Mak4e292812018-03-19 15:37:21 +0000980 final ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
981 packageName, PackageManager.GET_META_DATA, userId);
jackqdyuleifde637f2018-01-02 14:51:01 -0800982 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
983 } catch (PackageManager.NameNotFoundException e) {
984 return packageManager.getDefaultActivityIcon();
985 }
986 }
Raff Tsai2928cd42018-11-05 16:10:19 +0800987
988 /** Returns true if the current package is installed & enabled. */
989 public static boolean isPackageEnabled(Context context, String packageName) {
990 try {
991 return context.getPackageManager().getApplicationInfo(packageName, 0).enabled;
992 } catch (Exception e) {
993 Log.e(TAG, "Error while retrieving application info for package " + packageName, e);
994 }
995 return false;
996 }
markchien1dd1d792019-01-11 16:18:20 +0800997
998 /** Get {@link Resources} by subscription id if subscription id is valid. */
999 public static Resources getResourcesForSubId(Context context, int subId) {
1000 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1001 return SubscriptionManager.getResourcesForSubId(context, subId);
1002 } else {
1003 return context.getResources();
1004 }
1005 }
Ng Zhi Anb97bdc32019-02-01 12:39:31 -08001006
1007 /**
1008 * Returns true if SYSTEM_ALERT_WINDOW permission is available.
1009 * Starting from Q, SYSTEM_ALERT_WINDOW is disabled on low ram phones.
1010 */
1011 public static boolean isSystemAlertWindowEnabled(Context context) {
1012 // SYSTEM_ALERT_WINDOW is disabled on on low ram devices starting from Q
1013 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
1014 return !(am.isLowRamDevice() && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q));
1015 }
tmfangaed8f362019-03-18 16:56:09 +08001016
1017 /**
1018 * Adds a shadow appear/disappear animation to action bar scroll.
1019 *
1020 * <p/>
1021 * This method must be called after {@link Fragment#onCreate(Bundle)}.
1022 */
1023 public static void setActionBarShadowAnimation(Activity activity, Lifecycle lifecycle,
1024 View scrollView) {
1025 if (activity == null) {
1026 Log.w(TAG, "No activity, cannot style actionbar.");
1027 return;
1028 }
1029 final ActionBar actionBar = activity.getActionBar();
1030 if (actionBar == null) {
1031 Log.w(TAG, "No actionbar, cannot style actionbar.");
1032 return;
1033 }
1034 actionBar.setElevation(0);
1035
1036 if (lifecycle != null && scrollView != null) {
1037 ActionBarShadowController.attachToView(activity, lifecycle, scrollView);
1038 }
1039 }
Raff Tsaiafd494d2019-10-16 15:25:21 +08001040
1041 /**
1042 * Return correct target fragment based on argument
1043 *
1044 * @param activity the activity target fragment will be launched.
1045 * @param fragmentName initial target fragment name.
1046 * @param args fragment launch arguments.
1047 */
1048 public static Fragment getTargetFragment(Activity activity, String fragmentName, Bundle args) {
1049 Fragment f = null;
Raff Tsai84327f62019-11-15 11:02:25 +08001050 final boolean isPersonal = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001051 == ProfileSelectFragment.ProfileType.PERSONAL : false;
Raff Tsai84327f62019-11-15 11:02:25 +08001052 final boolean isWork = args != null ? args.getInt(ProfileSelectFragment.EXTRA_PROFILE)
Raff Tsai1e5d8142019-12-12 11:45:41 +08001053 == ProfileSelectFragment.ProfileType.WORK : false;
Raff Tsaiafd494d2019-10-16 15:25:21 +08001054 if (FeatureFlagUtils.isEnabled(activity, FeatureFlags.PERSONAL_WORK_PROFILE)
Bonian Chenf399bd12020-01-09 14:50:03 +08001055 && activity.getSystemService(UserManager.class).getUserProfiles().size() > 1
Raff Tsaiafd494d2019-10-16 15:25:21 +08001056 && ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName) != null
Raff Tsai84327f62019-11-15 11:02:25 +08001057 && !isWork && !isPersonal) {
Raff Tsaiafd494d2019-10-16 15:25:21 +08001058 f = Fragment.instantiate(activity, ProfileFragmentBridge.FRAGMENT_MAP.get(fragmentName),
1059 args);
1060 } else {
1061 f = Fragment.instantiate(activity, fragmentName, args);
1062 }
1063 return f;
1064 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001065}