blob: 75db3e18188eed5514d993b10198df6243bf4a7e [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;
Udam Saini679f7ad2016-03-25 10:47:00 -070076import android.provider.Settings;
markchien1dd1d792019-01-11 16:18:20 +080077import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070078import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040079import android.text.Spannable;
80import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020081import android.text.TextUtils;
Jason Monkb37e2882016-01-11 14:27:20 -050082import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040083import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070084import android.util.ArraySet;
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;
105import com.android.settings.development.featureflags.FeatureFlagPersistent;
Jeff Sharkey219ec912017-12-19 14:57:39 -0700106import com.android.settings.password.ChooseLockSettingsHelper;
tmfangaed8f362019-03-18 16:56:09 +0800107import com.android.settingslib.widget.ActionBarShadowController;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700108
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800109import java.net.InetAddress;
110import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700111import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900112import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800113
Jason Monk27985e12016-01-08 14:13:05 -0500114public final class Utils extends com.android.settingslib.Utils {
115
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100116 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100117
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800118 /**
119 * Set the preference's title to the matching activity's label.
120 */
121 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
122
Fan Zhangc3fd2892019-01-29 16:00:19 -0800123 public static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100124
Jason Monkbeb171d2015-05-21 15:24:37 -0400125 public static final String OS_PKG = "os";
126
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200127 /**
Svet Ganov864765f2019-04-05 19:00:05 -0700128 * Whether to disable the new device identifier access restrictions.
129 */
130 public static final String PROPERTY_DEVICE_IDENTIFIER_ACCESS_RESTRICTIONS_DISABLED =
131 "device_identifier_access_restrictions_disabled";
132
133 /**
Joel Galenson2118f8a2019-05-31 07:54:20 -0700134 * Whether to show the Permissions Hub.
135 */
136 public static final String PROPERTY_PERMISSIONS_HUB_ENABLED = "permissions_hub_enabled";
137
138 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800139 * Finds a matching activity for a preference's intent. If a matching
140 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800141 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800142 * @param context The context.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800143 * @param parentPreferenceGroup The preference group that contains the
Sunny Shao7e866b62019-08-09 11:42:04 +0800144 * preference whose intent is being resolved.
145 * @param preferenceKey The key of the preference whose intent is being
146 * resolved.
147 * @param flags 0 or one or more of
148 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
149 * .
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800150 * @return Whether an activity was found. If false, the preference was
Sunny Shao7e866b62019-08-09 11:42:04 +0800151 * removed.
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800152 */
153 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
154 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800155
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800156 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
157 if (preference == null) {
158 return false;
159 }
Ying Wanga7188322010-01-04 18:45:10 -0800160
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800161 Intent intent = preference.getIntent();
162 if (intent != null) {
163 // Find the activity that is in the system image
164 PackageManager pm = context.getPackageManager();
165 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
166 int listSize = list.size();
167 for (int i = 0; i < listSize; i++) {
168 ResolveInfo resolveInfo = list.get(i);
169 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
170 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800171
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800172 // Replace the intent with this specific activity
173 preference.setIntent(new Intent().setClassName(
174 resolveInfo.activityInfo.packageName,
175 resolveInfo.activityInfo.name));
176
177 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
178 // Set the preference title to the activity's label
179 preference.setTitle(resolveInfo.loadLabel(pm));
180 }
Ying Wanga7188322010-01-04 18:45:10 -0800181
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800182 return true;
183 }
184 }
185 }
186
187 // Did not find a matching activity, so remove the preference
188 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800189
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900190 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800191 }
Ying Wanga7188322010-01-04 18:45:10 -0800192
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200193 /**
Benjamin Franz194300d2016-01-13 12:16:25 +0000194 * Returns the UserManager for a given context
195 *
196 * @throws IllegalStateException if no UserManager could be retrieved.
197 */
198 public static UserManager getUserManager(Context context) {
199 UserManager um = UserManager.get(context);
200 if (um == null) {
201 throw new IllegalStateException("Unable to load UserManager");
202 }
203 return um;
204 }
205
206 /**
Ying Wanga7188322010-01-04 18:45:10 -0800207 * Returns true if Monkey is running.
208 */
209 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700210 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800211 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700212
213 /**
214 * Returns whether the device is voice-capable (meaning, it is also a phone).
215 */
216 public static boolean isVoiceCapable(Context context) {
217 TelephonyManager telephony =
218 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
219 return telephony != null && telephony.isVoiceCapable();
220 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800221
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800222 /**
223 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
224 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900225 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800226 */
227 public static String getWifiIpAddresses(Context context) {
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700228 WifiManager wifiManager = context.getSystemService(WifiManager.class);
229 Network currentNetwork = wifiManager.getCurrentNetwork();
230 if (currentNetwork != null) {
231 ConnectivityManager cm = (ConnectivityManager)
Sunny Shao7e866b62019-08-09 11:42:04 +0800232 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700233 LinkProperties prop = cm.getLinkProperties(currentNetwork);
234 return formatIpAddresses(prop);
235 }
236 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700237 }
238
Amith Yamasani6822b742011-10-17 16:41:00 -0700239 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800240 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900241 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800242 // If there are no entries, return null
243 if (!iter.hasNext()) return null;
244 // Concatenate all available addresses, comma separated
245 String addresses = "";
246 while (iter.hasNext()) {
247 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900248 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800249 }
250 return addresses;
251 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900252
253 public static Locale createLocaleFromString(String localeStr) {
254 // TODO: is there a better way to actually construct a locale that will match?
255 // The main problem is, on top of Java specs, locale.toString() and
256 // new Locale(locale.toString()).toString() do not return equal() strings in
257 // many cases, because the constructor takes the only string as the language
258 // code. So : new Locale("en", "US").toString() => "en_US"
259 // And : new Locale("en_US").toString() => "en_us"
Sunny Shao7e866b62019-08-09 11:42:04 +0800260 if (null == localeStr)
Jean Chalard71ad1f42011-05-12 15:06:16 +0900261 return Locale.getDefault();
262 String[] brokenDownLocale = localeStr.split("_", 3);
263 // split may not return a 0-length array.
264 if (1 == brokenDownLocale.length) {
265 return new Locale(brokenDownLocale[0]);
266 } else if (2 == brokenDownLocale.length) {
267 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
268 } else {
269 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
270 }
271 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700272
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900273 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
274 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
275 }
276
Amith Yamasania4379d62011-07-22 10:34:58 -0700277 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700278 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700279 }
280
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700281 /**
282 * Prepare a custom preferences layout, moving padding to {@link ListView}
283 * when outside scrollbars are requested. Usually used to display
284 * {@link ListView} and {@link TabWidget} with correct padding.
285 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700286 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800287 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700288 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700289 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700290 final Resources res = list.getResources();
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700291 final int paddingBottom = res.getDimensionPixelSize(
292 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700293
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700294 if (parent instanceof PreferenceFrameLayout) {
295 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700296 }
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800297 list.setPaddingRelative(0 /* start */, 0 /* top */, 0 /* end */, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700298 }
299 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700300
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700301 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700302 final Resources res = view.getResources();
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700303
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800304 final int paddingStart = additive ? view.getPaddingStart() : 0;
305 final int paddingEnd = additive ? view.getPaddingEnd() : 0;
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700306 final int paddingBottom = res.getDimensionPixelSize(
307 com.android.internal.R.dimen.preference_fragment_padding_bottom);
308
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700309 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700310 }
311
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700312 public static String getMeProfileName(Context context, boolean full) {
313 if (full) {
314 return getProfileDisplayName(context);
315 } else {
316 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700317 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700318 }
319
320 private static String getShorterNameIfPossible(Context context) {
321 final String given = getLocalProfileGivenName(context);
322 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
323 }
324
325 private static String getLocalProfileGivenName(Context context) {
326 final ContentResolver cr = context.getContentResolver();
327
328 // Find the raw contact ID for the local ME profile raw contact.
329 final long localRowProfileId;
330 final Cursor localRawProfile = cr.query(
331 Profile.CONTENT_RAW_CONTACTS_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800332 new String[] {RawContacts._ID},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700333 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
334 RawContacts.ACCOUNT_NAME + " IS NULL",
335 null, null);
336 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700337
338 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700339 if (!localRawProfile.moveToFirst()) {
340 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700341 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700342 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700343 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700344 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700345 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700346
347 // Find the structured name for the raw contact.
348 final Cursor structuredName = cr.query(
349 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
Sunny Shao7e866b62019-08-09 11:42:04 +0800350 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
351 CommonDataKinds.StructuredName.FAMILY_NAME},
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700352 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
353 null, null);
354 if (structuredName == null) return null;
355
356 try {
357 if (!structuredName.moveToFirst()) {
358 return null;
359 }
360 String partialName = structuredName.getString(0);
361 if (TextUtils.isEmpty(partialName)) {
362 partialName = structuredName.getString(1);
363 }
364 return partialName;
365 } finally {
366 structuredName.close();
367 }
368 }
369
370 private static final String getProfileDisplayName(Context context) {
371 final ContentResolver cr = context.getContentResolver();
372 final Cursor profile = cr.query(Profile.CONTENT_URI,
Sunny Shao7e866b62019-08-09 11:42:04 +0800373 new String[] {Profile.DISPLAY_NAME}, null, null, null);
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700374 if (profile == null) return null;
375
376 try {
377 if (!profile.moveToFirst()) {
378 return null;
379 }
380 return profile.getString(0);
381 } finally {
382 profile.close();
383 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700384 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700385
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700386 public static boolean hasMultipleUsers(Context context) {
387 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
388 .getUsers().size() > 1;
389 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700390
391 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100392 * Returns the managed profile of the current user or {@code null} if none is found or a profile
393 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100394 */
395 public static UserHandle getManagedProfile(UserManager userManager) {
396 List<UserHandle> userProfiles = userManager.getUserProfiles();
Aarthi Balachanderd0f83592018-07-10 17:04:53 -0700397 for (UserHandle profile : userProfiles) {
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100398 if (profile.getIdentifier() == userManager.getUserHandle()) {
399 continue;
400 }
401 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
402 if (userInfo.isManagedProfile()) {
403 return profile;
404 }
405 }
406 return null;
407 }
408
409 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100410 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
411 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
412 */
413 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
414 // TODO: Call getManagedProfileId from here once Robolectric supports
415 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
416 // yet another implementation that loops over user profiles in this method). In the meantime
417 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
418 // used for Settings Robolectric tests).
419 final int myUserId = UserHandle.myUserId();
420 List<UserInfo> profiles = userManager.getProfiles(myUserId);
421 final int count = profiles.size();
422 for (int i = 0; i < count; i++) {
423 final UserInfo profile = profiles.get(i);
424 if (profile.isManagedProfile()
425 && profile.getUserHandle().getIdentifier() != myUserId) {
426 return profile.getUserHandle();
427 }
428 }
429 return null;
430 }
431
432 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000433 * Retrieves the id for the given user's managed profile.
434 *
435 * @return the managed profile id or UserHandle.USER_NULL if there is none.
436 */
437 public static int getManagedProfileId(UserManager um, int parentUserId) {
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700438 int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
439 for (int profileId : profileIds) {
440 if (profileId != parentUserId) {
441 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000442 }
443 }
444 return UserHandle.USER_NULL;
445 }
446
447 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100448 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000449 * <p>
450 * User would be retrieved in this order:
451 * <ul>
452 * <li> If this activity is launched from other user, return that user id.
453 * <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 +0800454 * extra in the arguments or intent extras.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000455 * <li> Otherwise, return UserHandle.myUserId().
456 * </ul>
457 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100458 * Note: This is secure in the sense that it only returns a target user different to the current
459 * one if the app launching this activity is the Settings app itself, running in the same user
460 * 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 +0100461 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100462 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000463 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100464 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800465 IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100466 try {
467 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
468 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
469
470 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
471 am.getLaunchedFromUid(activityToken)));
472 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
473 // Check it's secure
474 if (isProfileOf(um, launchedFromUser)) {
475 return launchedFromUser;
476 }
477 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000478 UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100479 if (extrasUser != null && !extrasUser.equals(currentUser)) {
480 // Check it's secure
481 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
482 return extrasUser;
483 }
484 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000485 UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100486 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
487 // Check it's secure
488 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
489 return argumentsUser;
490 }
491 }
492 } catch (RemoteException e) {
493 // Should not happen
494 Log.v(TAG, "Could not talk to activity manager.", e);
495 }
496 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000497 }
498
499 /**
500 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
501 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
502 */
Sunny Shao7e866b62019-08-09 11:42:04 +0800503 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
Tony Mak8f41b9b2016-11-23 11:36:18 +0000504 if (bundle == null) {
505 return null;
506 }
507 final UserHandle user = bundle.getParcelable(EXTRA_USER);
508 if (user != null) {
509 return user;
510 }
511 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
512 if (userId != -1) {
513 return UserHandle.of(userId);
514 }
515 return null;
516 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100517
Sunny Shao7e866b62019-08-09 11:42:04 +0800518 /**
519 * Returns true if the user provided is in the same profiles group as the current user.
520 */
521 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
522 if (um == null || otherUser == null) return false;
523 return (UserHandle.myUserId() == otherUser.getIdentifier())
524 || um.getUserProfiles().contains(otherUser);
525 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530526
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100527 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700528 * Return whether or not the user should have a SIM Cards option in Settings.
529 * TODO: Change back to returning true if count is greater than one after testing.
530 * TODO: See bug 16533525.
531 */
532 public static boolean showSimCardTile(Context context) {
Antony Sargent627f14b2019-03-04 16:00:59 -0800533 if (FeatureFlagPersistent.isEnabled(context, FeatureFlags.NETWORK_INTERNET_V2)) {
534 return false;
535 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700536 final TelephonyManager tm =
537 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
538
PauloftheWestdbd03822014-12-04 11:56:35 -0800539 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700540 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200541
542 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800543 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
544 * @param userManager Instance of UserManager
Sunny Shao7e866b62019-08-09 11:42:04 +0800545 * @param checkUser The user to check the existence of.
Amith Yamasani45f86232014-11-19 17:12:46 -0800546 * @return UserInfo of the user or null for non-existent user.
547 */
548 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
549 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
550 final int checkUserId = checkUser.getIdentifier();
551 for (UserInfo user : users) {
552 if (user.id == checkUserId) {
553 return user;
554 }
555 }
556 return null;
557 }
558
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000559 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
560 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
561 com.android.internal.R.styleable.Preference,
562 com.android.internal.R.attr.preferenceCategoryStyle, 0);
563 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
564 0);
565 a.recycle();
566 return inflater.inflate(resId, parent, false);
567 }
568
Christopher Tatea08a2252015-07-01 16:52:43 -0700569 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
570 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
571 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
572
573 ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800574 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700575 for (IntentFilterVerificationInfo ivi : iviList) {
576 for (String host : ivi.getDomains()) {
577 result.add(host);
578 }
579 }
580 }
581 if (filters != null && filters.size() > 0) {
582 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700583 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
584 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
Sunny Shao7e866b62019-08-09 11:42:04 +0800585 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700586 result.addAll(filter.getHostsList());
587 }
588 }
589 }
590 return result;
591 }
592
Sudheer Shankabc956302015-04-09 12:19:53 +0100593 /**
594 * Returns the application info of the currently installed MDM package.
595 */
596 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
597 DevicePolicyManager dpm =
598 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
599 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
600 if (mdmPackage == null) {
601 return null;
602 }
603 String mdmPackageName = mdmPackage.getPackageName();
604 try {
605 IPackageManager ipm = AppGlobals.getPackageManager();
606 ApplicationInfo mdmApplicationInfo =
607 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
608 return mdmApplicationInfo;
609 } catch (RemoteException e) {
610 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
611 + ", userId " + profileId, e);
612 return null;
613 }
614 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400615
616 public static boolean isBandwidthControlEnabled() {
617 final INetworkManagementService netManager = INetworkManagementService.Stub
618 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
619 try {
620 return netManager.isBandwidthControlEnabled();
621 } catch (RemoteException e) {
622 return false;
623 }
624 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400625
626 /**
627 * Returns an accessible SpannableString.
Sunny Shao7e866b62019-08-09 11:42:04 +0800628 * @param displayText the text to display
Julia Reynoldsce25af42015-07-08 16:56:31 -0400629 * @param accessibileText the text text-to-speech engines should read
630 */
631 public static SpannableString createAccessibleSequence(CharSequence displayText,
632 String accessibileText) {
633 SpannableString str = new SpannableString(displayText);
634 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
635 displayText.length(),
636 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
637 return str;
638 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700639
Clara Bayarrife432e82015-10-12 12:07:02 +0100640 /**
Jeff Sharkey219ec912017-12-19 14:57:39 -0700641 * Returns the user id present in the bundle with
642 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
Clara Bayarrife432e82015-10-12 12:07:02 +0100643 *
Jeff Sharkey219ec912017-12-19 14:57:39 -0700644 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800645 * current user group.
Clara Bayarrife432e82015-10-12 12:07:02 +0100646 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000647 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700648 return getUserIdFromBundle(context, bundle, false);
649 }
650
651 /**
652 * Returns the user id present in the bundle with
653 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
654 *
655 * @param isInternal indicating if the caller is "internal" to the system,
Sunny Shao7e866b62019-08-09 11:42:04 +0800656 * meaning we're willing to trust extras like
657 * {@link ChooseLockSettingsHelper#EXTRA_ALLOW_ANY_USER}.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700658 * @throws SecurityException if the given userId does not belong to the
Sunny Shao7e866b62019-08-09 11:42:04 +0800659 * current user group.
Jeff Sharkey219ec912017-12-19 14:57:39 -0700660 */
661 public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
Clara Bayarrife432e82015-10-12 12:07:02 +0100662 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +0000663 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +0100664 }
Jeff Sharkey219ec912017-12-19 14:57:39 -0700665 final boolean allowAnyUser = isInternal
666 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_ALLOW_ANY_USER, false);
Clara Bayarri6934a042015-10-14 11:07:35 +0100667 int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700668 if (userId == LockPatternUtils.USER_FRP) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700669 return allowAnyUser ? userId : enforceSystemUser(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700670 } else {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700671 return allowAnyUser ? userId : enforceSameOwner(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700672 }
673 }
674
675 /**
676 * Returns the given user id if the current user is the system user.
677 *
678 * @throws SecurityException if the current user is not the system user.
679 */
680 public static int enforceSystemUser(Context context, int userId) {
681 if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
682 return userId;
683 }
684 throw new SecurityException("Given user id " + userId + " must only be used from "
685 + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100686 }
687
688 /**
689 * Returns the given user id if it belongs to the current user.
690 *
691 * @throws SecurityException if the given userId does not belong to the current user group.
692 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000693 public static int enforceSameOwner(Context context, int userId) {
Ricky Wai72500162016-06-07 16:54:25 +0100694 final UserManager um = getUserManager(context);
695 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
696 if (ArrayUtils.contains(profileIds, userId)) {
697 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +0100698 }
Ricky Wai72500162016-06-07 16:54:25 +0100699 throw new SecurityException("Given user id " + userId + " does not belong to user "
700 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100701 }
702
Benjamin Franz194300d2016-01-13 12:16:25 +0000703 /**
704 * Returns the effective credential owner of the calling user.
705 */
706 public static int getCredentialOwnerUserId(Context context) {
707 return getCredentialOwnerUserId(context, UserHandle.myUserId());
708 }
709
710 /**
711 * Returns the user id of the credential owner of the given user id.
712 */
713 public static int getCredentialOwnerUserId(Context context, int userId) {
714 UserManager um = getUserManager(context);
715 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700716 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500717
Jason Monkb37e2882016-01-11 14:27:20 -0500718 private static final StringBuilder sBuilder = new StringBuilder(50);
719 private static final java.util.Formatter sFormatter = new java.util.Formatter(
720 sBuilder, Locale.getDefault());
721
722 public static String formatDateRange(Context context, long start, long end) {
723 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
724
725 synchronized (sBuilder) {
726 sBuilder.setLength(0);
727 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
728 .toString();
729 }
730 }
Jason Monk91e2f892016-02-23 15:31:09 -0500731
Udam Saini679f7ad2016-03-25 10:47:00 -0700732 public static boolean isDeviceProvisioned(Context context) {
733 return Settings.Global.getInt(context.getContentResolver(),
734 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
735 }
Ricky Wai616342b2016-04-13 10:40:22 +0100736
Bernard Chau88d523b2016-04-14 15:08:28 +0100737 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100738 int userId) {
739 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
740 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
741 context.startActivity(intent);
742 return true;
743 }
744 return false;
745 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700746
Rubin Xu3231afe2016-08-24 10:15:07 +0100747 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
748 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800749 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100750 ActivityManager.FLAG_AND_LOCKED)) {
751 return false;
752 }
753 } catch (RemoteException e) {
754 return false;
755 }
756 if (!(new LockPatternUtils(context)).isSecure(userId)) {
757 return false;
758 }
Robin Leecccf3242017-02-10 15:32:49 +0000759 return confirmWorkProfileCredentials(context, userId);
760 }
761
Robin Leecccf3242017-02-10 15:32:49 +0000762 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100763 final KeyguardManager km = (KeyguardManager) context.getSystemService(
764 Context.KEYGUARD_SERVICE);
765 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
766 if (unlockIntent != null) {
767 context.startActivity(unlockIntent);
768 return true;
769 } else {
770 return false;
771 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100772 }
773
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700774 public static CharSequence getApplicationLabel(Context context, String packageName) {
775 try {
776 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
777 packageName,
778 PackageManager.MATCH_DISABLED_COMPONENTS
Sunny Shao7e866b62019-08-09 11:42:04 +0800779 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700780 return appInfo.loadLabel(context.getPackageManager());
781 } catch (PackageManager.NameNotFoundException e) {
782 Log.w(TAG, "Unable to find info for package: " + packageName);
783 }
784 return null;
785 }
Jason Monk75199542016-05-06 15:09:32 -0400786
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600787 public static boolean isPackageDirectBootAware(Context context, String packageName) {
788 try {
789 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
790 packageName, 0);
791 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
792 } catch (NameNotFoundException ignored) {
793 }
794 return false;
795 }
Andre Lago3e398c82016-07-25 14:12:28 +0100796
797 /**
798 * Returns a context created from the given context for the given user, or null if it fails
799 */
800 public static Context createPackageContextAsUser(Context context, int userId) {
801 try {
802 return context.createPackageContextAsUser(
803 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
804 } catch (PackageManager.NameNotFoundException e) {
805 Log.e(TAG, "Failed to create user context", e);
806 }
807 return null;
808 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600809
810 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
811 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800812 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600813 } else {
814 return null;
815 }
816 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800817
Kevin Chyn82792cc2017-07-20 00:15:44 -0700818 public static boolean hasFingerprintHardware(Context context) {
819 FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
820 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
821 }
822
Kevin Chyn4882e872018-06-25 17:58:31 -0700823 public static FaceManager getFaceManagerOrNull(Context context) {
824 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
825 return (FaceManager) context.getSystemService(Context.FACE_SERVICE);
826 } else {
827 return null;
828 }
829 }
830
831 public static boolean hasFaceHardware(Context context) {
832 FaceManager faceManager = getFaceManagerOrNull(context);
833 return faceManager != null && faceManager.isHardwareDetected();
834 }
835
Daniel Nishi31027da2017-01-19 14:03:57 -0800836 /**
837 * Launches an intent which may optionally have a user id defined.
838 * @param fragment Fragment to use to launch the activity.
Sunny Shao7e866b62019-08-09 11:42:04 +0800839 * @param intent Intent to launch.
Daniel Nishi31027da2017-01-19 14:03:57 -0800840 */
841 public static void launchIntent(Fragment fragment, Intent intent) {
842 try {
843 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
844
845 if (userId == -1) {
846 fragment.startActivity(intent);
847 } else {
848 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
849 }
850 } catch (ActivityNotFoundException e) {
851 Log.w(TAG, "No activity found for " + intent);
852 }
853 }
854
Christine Franksc6890ab2017-06-23 14:28:21 -0700855 public static boolean isDemoUser(Context context) {
856 return UserManager.isDeviceInDemoMode(context) && getUserManager(context).isDemoUser();
857 }
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);
885 VolumeInfo volume = sm.findVolumeById(volumeId);
886 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) {
jackqdyulei00015fb2017-08-22 11:25:30 -0700898 List<UserInfo> userInfos = userManager.getUsers();
899 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
900 return true;
901 }
902 for (int i = 0, size = userInfos.size(); i < size; i++) {
903 ComponentName cn = devicePolicyManager.getProfileOwnerAsUser(userInfos.get(i).id);
904 if (cn != null && cn.getPackageName().equals(packageName)) {
905 return true;
906 }
907 }
908 return false;
909 }
910
911 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800912 * Return the resource id to represent the install status for an app
913 */
914 @StringRes
915 public static int getInstallationStatus(ApplicationInfo info) {
916 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
917 return R.string.not_installed;
918 }
919 return info.enabled ? R.string.installed : R.string.disabled;
920 }
921
Daniel Nishi9f60f422017-02-15 15:25:48 -0800922 private static boolean isVolumeValid(VolumeInfo volume) {
923 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
924 && volume.isMountedReadable();
925 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700926
PMS2263a05602017-06-14 07:10:15 +0000927 public static void setEditTextCursorPosition(EditText editText) {
928 editText.setSelection(editText.getText().length());
929 }
Felipe Lemebd884502017-09-15 18:16:21 -0700930
931 /**
932 * Sets the preference icon with a drawable that is scaled down to to avoid crashing Settings if
933 * it's too big.
934 */
935 public static void setSafeIcon(Preference pref, Drawable icon) {
936 Drawable safeIcon = icon;
Phil Weaver5a3e02d2018-03-08 17:38:46 -0800937 if ((icon != null) && !(icon instanceof VectorDrawable)) {
Felipe Lemebd884502017-09-15 18:16:21 -0700938 safeIcon = getSafeDrawable(icon, 500, 500);
939 }
940 pref.setIcon(safeIcon);
941 }
942
943 /**
944 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
945 *
Sunny Shao7e866b62019-08-09 11:42:04 +0800946 * @param original original drawable, typically an app icon.
947 * @param maxWidth maximum width, in pixels.
Felipe Lemebd884502017-09-15 18:16:21 -0700948 * @param maxHeight maximum height, in pixels.
949 */
950 public static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
951 final int actualWidth = original.getMinimumWidth();
952 final int actualHeight = original.getMinimumHeight();
953
954 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
955 return original;
956 }
957
958 float scaleWidth = ((float) maxWidth) / actualWidth;
959 float scaleHeight = ((float) maxHeight) / actualHeight;
960 float scale = Math.min(scaleWidth, scaleHeight);
961 final int width = (int) (actualWidth * scale);
962 final int height = (int) (actualHeight * scale);
963
964 final Bitmap bitmap;
965 if (original instanceof BitmapDrawable) {
966 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
967 height, false);
968 } else {
Jason Chiuc78c54a2019-02-13 16:07:57 +0800969 bitmap = createBitmap(original, width, height);
Felipe Lemebd884502017-09-15 18:16:21 -0700970 }
971 return new BitmapDrawable(null, bitmap);
972 }
jackqdyuleifde637f2018-01-02 14:51:01 -0800973
974 /**
Jason Chiuc78c54a2019-02-13 16:07:57 +0800975 * Create an Icon pointing to a drawable.
Jason Chiu1217bbe2019-01-24 16:32:31 +0800976 */
Jason Chiuc78c54a2019-02-13 16:07:57 +0800977 public static IconCompat createIconWithDrawable(Drawable drawable) {
978 Bitmap bitmap;
Jason Chiu1217bbe2019-01-24 16:32:31 +0800979 if (drawable instanceof BitmapDrawable) {
Sunny Shao7e866b62019-08-09 11:42:04 +0800980 bitmap = ((BitmapDrawable)drawable).getBitmap();
Jason Chiuc78c54a2019-02-13 16:07:57 +0800981 } else {
982 final int width = drawable.getIntrinsicWidth();
983 final int height = drawable.getIntrinsicHeight();
984 bitmap = createBitmap(drawable,
985 width > 0 ? width : 1,
986 height > 0 ? height : 1);
Jason Chiu1217bbe2019-01-24 16:32:31 +0800987 }
Jason Chiuc78c54a2019-02-13 16:07:57 +0800988 return IconCompat.createWithBitmap(bitmap);
989 }
Jason Chiu1217bbe2019-01-24 16:32:31 +0800990
clownshen24827d32019-03-29 20:22:02 +0800991 /**
992 * Creates a drawable with specified width and height.
993 */
994 public static Bitmap createBitmap(Drawable drawable, int width, int height) {
Jason Chiuc78c54a2019-02-13 16:07:57 +0800995 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Jason Chiu1217bbe2019-01-24 16:32:31 +0800996 final Canvas canvas = new Canvas(bitmap);
997 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
998 drawable.draw(canvas);
999 return bitmap;
1000 }
1001
1002 /**
jackqdyuleifde637f2018-01-02 14:51:01 -08001003 * Get the {@link Drawable} that represents the app icon
1004 */
1005 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
1006 PackageManager packageManager, String packageName, int userId) {
1007 try {
Tony Mak4e292812018-03-19 15:37:21 +00001008 final ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
1009 packageName, PackageManager.GET_META_DATA, userId);
jackqdyuleifde637f2018-01-02 14:51:01 -08001010 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
1011 } catch (PackageManager.NameNotFoundException e) {
1012 return packageManager.getDefaultActivityIcon();
1013 }
1014 }
Raff Tsai2928cd42018-11-05 16:10:19 +08001015
1016 /** Returns true if the current package is installed & enabled. */
1017 public static boolean isPackageEnabled(Context context, String packageName) {
1018 try {
1019 return context.getPackageManager().getApplicationInfo(packageName, 0).enabled;
1020 } catch (Exception e) {
1021 Log.e(TAG, "Error while retrieving application info for package " + packageName, e);
1022 }
1023 return false;
1024 }
markchien1dd1d792019-01-11 16:18:20 +08001025
1026 /** Get {@link Resources} by subscription id if subscription id is valid. */
1027 public static Resources getResourcesForSubId(Context context, int subId) {
1028 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1029 return SubscriptionManager.getResourcesForSubId(context, subId);
1030 } else {
1031 return context.getResources();
1032 }
1033 }
Ng Zhi Anb97bdc32019-02-01 12:39:31 -08001034
1035 /**
1036 * Returns true if SYSTEM_ALERT_WINDOW permission is available.
1037 * Starting from Q, SYSTEM_ALERT_WINDOW is disabled on low ram phones.
1038 */
1039 public static boolean isSystemAlertWindowEnabled(Context context) {
1040 // SYSTEM_ALERT_WINDOW is disabled on on low ram devices starting from Q
1041 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
1042 return !(am.isLowRamDevice() && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q));
1043 }
tmfangaed8f362019-03-18 16:56:09 +08001044
1045 /**
1046 * Adds a shadow appear/disappear animation to action bar scroll.
1047 *
1048 * <p/>
1049 * This method must be called after {@link Fragment#onCreate(Bundle)}.
1050 */
1051 public static void setActionBarShadowAnimation(Activity activity, Lifecycle lifecycle,
1052 View scrollView) {
1053 if (activity == null) {
1054 Log.w(TAG, "No activity, cannot style actionbar.");
1055 return;
1056 }
1057 final ActionBar actionBar = activity.getActionBar();
1058 if (actionBar == null) {
1059 Log.w(TAG, "No actionbar, cannot style actionbar.");
1060 return;
1061 }
1062 actionBar.setElevation(0);
1063
1064 if (lifecycle != null && scrollView != null) {
1065 ActionBarShadowController.attachToView(activity, lifecycle, scrollView);
1066 }
1067 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001068}