blob: 36230d17dcaec8bb8698a3cfe7dda9ce3e9b6eea [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 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800128 * Finds a matching activity for a preference's intent. If a matching
129 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800130 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800131 * @param context The context.
132 * @param parentPreferenceGroup The preference group that contains the
133 * preference whose intent is being resolved.
134 * @param preferenceKey The key of the preference whose intent is being
135 * resolved.
136 * @param flags 0 or one or more of
137 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
138 * .
139 * @return Whether an activity was found. If false, the preference was
140 * removed.
141 */
142 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
143 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800144
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800145 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
146 if (preference == null) {
147 return false;
148 }
Ying Wanga7188322010-01-04 18:45:10 -0800149
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800150 Intent intent = preference.getIntent();
151 if (intent != null) {
152 // Find the activity that is in the system image
153 PackageManager pm = context.getPackageManager();
154 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
155 int listSize = list.size();
156 for (int i = 0; i < listSize; i++) {
157 ResolveInfo resolveInfo = list.get(i);
158 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
159 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800160
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800161 // Replace the intent with this specific activity
162 preference.setIntent(new Intent().setClassName(
163 resolveInfo.activityInfo.packageName,
164 resolveInfo.activityInfo.name));
165
166 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
167 // Set the preference title to the activity's label
168 preference.setTitle(resolveInfo.loadLabel(pm));
169 }
Ying Wanga7188322010-01-04 18:45:10 -0800170
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800171 return true;
172 }
173 }
174 }
175
176 // Did not find a matching activity, so remove the preference
177 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800178
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900179 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800180 }
Ying Wanga7188322010-01-04 18:45:10 -0800181
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200182 /**
Benjamin Franz194300d2016-01-13 12:16:25 +0000183 * Returns the UserManager for a given context
184 *
185 * @throws IllegalStateException if no UserManager could be retrieved.
186 */
187 public static UserManager getUserManager(Context context) {
188 UserManager um = UserManager.get(context);
189 if (um == null) {
190 throw new IllegalStateException("Unable to load UserManager");
191 }
192 return um;
193 }
194
195 /**
Ying Wanga7188322010-01-04 18:45:10 -0800196 * Returns true if Monkey is running.
197 */
198 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700199 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800200 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700201
202 /**
203 * Returns whether the device is voice-capable (meaning, it is also a phone).
204 */
205 public static boolean isVoiceCapable(Context context) {
206 TelephonyManager telephony =
207 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
208 return telephony != null && telephony.isVoiceCapable();
209 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800210
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800211 /**
212 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
213 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900214 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800215 */
216 public static String getWifiIpAddresses(Context context) {
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700217 WifiManager wifiManager = context.getSystemService(WifiManager.class);
218 Network currentNetwork = wifiManager.getCurrentNetwork();
219 if (currentNetwork != null) {
220 ConnectivityManager cm = (ConnectivityManager)
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800221 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700222 LinkProperties prop = cm.getLinkProperties(currentNetwork);
223 return formatIpAddresses(prop);
224 }
225 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700226 }
227
Amith Yamasani6822b742011-10-17 16:41:00 -0700228 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800229 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900230 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800231 // If there are no entries, return null
232 if (!iter.hasNext()) return null;
233 // Concatenate all available addresses, comma separated
234 String addresses = "";
235 while (iter.hasNext()) {
236 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900237 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800238 }
239 return addresses;
240 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900241
242 public static Locale createLocaleFromString(String localeStr) {
243 // TODO: is there a better way to actually construct a locale that will match?
244 // The main problem is, on top of Java specs, locale.toString() and
245 // new Locale(locale.toString()).toString() do not return equal() strings in
246 // many cases, because the constructor takes the only string as the language
247 // code. So : new Locale("en", "US").toString() => "en_US"
248 // And : new Locale("en_US").toString() => "en_us"
249 if (null == localeStr)
250 return Locale.getDefault();
251 String[] brokenDownLocale = localeStr.split("_", 3);
252 // split may not return a 0-length array.
253 if (1 == brokenDownLocale.length) {
254 return new Locale(brokenDownLocale[0]);
255 } else if (2 == brokenDownLocale.length) {
256 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
257 } else {
258 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
259 }
260 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700261
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900262 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
263 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
264 }
265
Amith Yamasania4379d62011-07-22 10:34:58 -0700266 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700267 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700268 }
269
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700270 /**
271 * Prepare a custom preferences layout, moving padding to {@link ListView}
272 * when outside scrollbars are requested. Usually used to display
273 * {@link ListView} and {@link TabWidget} with correct padding.
274 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700275 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800276 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700277 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700278 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700279 final Resources res = list.getResources();
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700280 final int paddingBottom = res.getDimensionPixelSize(
281 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700282
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700283 if (parent instanceof PreferenceFrameLayout) {
284 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700285 }
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800286 list.setPaddingRelative(0 /* start */, 0 /* top */, 0 /* end */, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700287 }
288 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700289
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700290 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700291 final Resources res = view.getResources();
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700292
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800293 final int paddingStart = additive ? view.getPaddingStart() : 0;
294 final int paddingEnd = additive ? view.getPaddingEnd() : 0;
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700295 final int paddingBottom = res.getDimensionPixelSize(
296 com.android.internal.R.dimen.preference_fragment_padding_bottom);
297
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700298 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700299 }
300
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700301 public static String getMeProfileName(Context context, boolean full) {
302 if (full) {
303 return getProfileDisplayName(context);
304 } else {
305 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700306 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700307 }
308
309 private static String getShorterNameIfPossible(Context context) {
310 final String given = getLocalProfileGivenName(context);
311 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
312 }
313
314 private static String getLocalProfileGivenName(Context context) {
315 final ContentResolver cr = context.getContentResolver();
316
317 // Find the raw contact ID for the local ME profile raw contact.
318 final long localRowProfileId;
319 final Cursor localRawProfile = cr.query(
320 Profile.CONTENT_RAW_CONTACTS_URI,
321 new String[] {RawContacts._ID},
322 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
323 RawContacts.ACCOUNT_NAME + " IS NULL",
324 null, null);
325 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700326
327 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700328 if (!localRawProfile.moveToFirst()) {
329 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700330 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700331 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700332 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700333 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700334 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700335
336 // Find the structured name for the raw contact.
337 final Cursor structuredName = cr.query(
338 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
339 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
340 CommonDataKinds.StructuredName.FAMILY_NAME},
341 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
342 null, null);
343 if (structuredName == null) return null;
344
345 try {
346 if (!structuredName.moveToFirst()) {
347 return null;
348 }
349 String partialName = structuredName.getString(0);
350 if (TextUtils.isEmpty(partialName)) {
351 partialName = structuredName.getString(1);
352 }
353 return partialName;
354 } finally {
355 structuredName.close();
356 }
357 }
358
359 private static final String getProfileDisplayName(Context context) {
360 final ContentResolver cr = context.getContentResolver();
361 final Cursor profile = cr.query(Profile.CONTENT_URI,
362 new String[] {Profile.DISPLAY_NAME}, null, null, null);
363 if (profile == null) return null;
364
365 try {
366 if (!profile.moveToFirst()) {
367 return null;
368 }
369 return profile.getString(0);
370 } finally {
371 profile.close();
372 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700373 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700374
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700375 public static boolean hasMultipleUsers(Context context) {
376 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
377 .getUsers().size() > 1;
378 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700379
380 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100381 * Returns the managed profile of the current user or {@code null} if none is found or a profile
382 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100383 */
384 public static UserHandle getManagedProfile(UserManager userManager) {
385 List<UserHandle> userProfiles = userManager.getUserProfiles();
Aarthi Balachanderd0f83592018-07-10 17:04:53 -0700386 for (UserHandle profile : userProfiles) {
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100387 if (profile.getIdentifier() == userManager.getUserHandle()) {
388 continue;
389 }
390 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
391 if (userInfo.isManagedProfile()) {
392 return profile;
393 }
394 }
395 return null;
396 }
397
398 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100399 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
400 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
401 */
402 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
403 // TODO: Call getManagedProfileId from here once Robolectric supports
404 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
405 // yet another implementation that loops over user profiles in this method). In the meantime
406 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
407 // used for Settings Robolectric tests).
408 final int myUserId = UserHandle.myUserId();
409 List<UserInfo> profiles = userManager.getProfiles(myUserId);
410 final int count = profiles.size();
411 for (int i = 0; i < count; i++) {
412 final UserInfo profile = profiles.get(i);
413 if (profile.isManagedProfile()
414 && profile.getUserHandle().getIdentifier() != myUserId) {
415 return profile.getUserHandle();
416 }
417 }
418 return null;
419 }
420
421 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000422 * Retrieves the id for the given user's managed profile.
423 *
424 * @return the managed profile id or UserHandle.USER_NULL if there is none.
425 */
426 public static int getManagedProfileId(UserManager um, int parentUserId) {
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700427 int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
428 for (int profileId : profileIds) {
429 if (profileId != parentUserId) {
430 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000431 }
432 }
433 return UserHandle.USER_NULL;
434 }
435
436 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100437 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000438 * <p>
439 * User would be retrieved in this order:
440 * <ul>
441 * <li> If this activity is launched from other user, return that user id.
442 * <li> If this is launched from the Settings app in same user, return the user contained as an
443 * extra in the arguments or intent extras.
444 * <li> Otherwise, return UserHandle.myUserId().
445 * </ul>
446 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100447 * Note: This is secure in the sense that it only returns a target user different to the current
448 * one if the app launching this activity is the Settings app itself, running in the same user
449 * 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 +0100450 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100451 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000452 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100453 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800454 IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100455 try {
456 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
457 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
458
459 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
460 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 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000467 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 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000474 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 */
492 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
493 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
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100507 /**
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);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100514 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530515
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100516 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700517 * Return whether or not the user should have a SIM Cards option in Settings.
518 * TODO: Change back to returning true if count is greater than one after testing.
519 * TODO: See bug 16533525.
520 */
521 public static boolean showSimCardTile(Context context) {
Antony Sargent627f14b2019-03-04 16:00:59 -0800522 if (FeatureFlagPersistent.isEnabled(context, FeatureFlags.NETWORK_INTERNET_V2)) {
523 return false;
524 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700525 final TelephonyManager tm =
526 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
527
PauloftheWestdbd03822014-12-04 11:56:35 -0800528 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700529 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200530
531 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800532 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
533 * @param userManager Instance of UserManager
534 * @param checkUser The user to check the existence of.
535 * @return UserInfo of the user or null for non-existent user.
536 */
537 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
538 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
539 final int checkUserId = checkUser.getIdentifier();
540 for (UserInfo user : users) {
541 if (user.id == checkUserId) {
542 return user;
543 }
544 }
545 return null;
546 }
547
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000548 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
549 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
550 com.android.internal.R.styleable.Preference,
551 com.android.internal.R.attr.preferenceCategoryStyle, 0);
552 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
553 0);
554 a.recycle();
555 return inflater.inflate(resId, parent, false);
556 }
557
Christopher Tatea08a2252015-07-01 16:52:43 -0700558 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
559 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
560 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
561
562 ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800563 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700564 for (IntentFilterVerificationInfo ivi : iviList) {
565 for (String host : ivi.getDomains()) {
566 result.add(host);
567 }
568 }
569 }
570 if (filters != null && filters.size() > 0) {
571 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700572 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
573 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
574 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700575 result.addAll(filter.getHostsList());
576 }
577 }
578 }
579 return result;
580 }
581
Sudheer Shankabc956302015-04-09 12:19:53 +0100582 /**
583 * Returns the application info of the currently installed MDM package.
584 */
585 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
586 DevicePolicyManager dpm =
587 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
588 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
589 if (mdmPackage == null) {
590 return null;
591 }
592 String mdmPackageName = mdmPackage.getPackageName();
593 try {
594 IPackageManager ipm = AppGlobals.getPackageManager();
595 ApplicationInfo mdmApplicationInfo =
596 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
597 return mdmApplicationInfo;
598 } catch (RemoteException e) {
599 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
600 + ", userId " + profileId, e);
601 return null;
602 }
603 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400604
605 public static boolean isBandwidthControlEnabled() {
606 final INetworkManagementService netManager = INetworkManagementService.Stub
607 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
608 try {
609 return netManager.isBandwidthControlEnabled();
610 } catch (RemoteException e) {
611 return false;
612 }
613 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400614
615 /**
616 * Returns an accessible SpannableString.
617 * @param displayText the text to display
618 * @param accessibileText the text text-to-speech engines should read
619 */
620 public static SpannableString createAccessibleSequence(CharSequence displayText,
621 String accessibileText) {
622 SpannableString str = new SpannableString(displayText);
623 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
624 displayText.length(),
625 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
626 return str;
627 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700628
Clara Bayarrife432e82015-10-12 12:07:02 +0100629 /**
Jeff Sharkey219ec912017-12-19 14:57:39 -0700630 * Returns the user id present in the bundle with
631 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
Clara Bayarrife432e82015-10-12 12:07:02 +0100632 *
Jeff Sharkey219ec912017-12-19 14:57:39 -0700633 * @throws SecurityException if the given userId does not belong to the
634 * current user group.
Clara Bayarrife432e82015-10-12 12:07:02 +0100635 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000636 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700637 return getUserIdFromBundle(context, bundle, false);
638 }
639
640 /**
641 * Returns the user id present in the bundle with
642 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
643 *
644 * @param isInternal indicating if the caller is "internal" to the system,
645 * meaning we're willing to trust extras like
646 * {@link ChooseLockSettingsHelper#EXTRA_ALLOW_ANY_USER}.
647 * @throws SecurityException if the given userId does not belong to the
648 * current user group.
649 */
650 public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
Clara Bayarrife432e82015-10-12 12:07:02 +0100651 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +0000652 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +0100653 }
Jeff Sharkey219ec912017-12-19 14:57:39 -0700654 final boolean allowAnyUser = isInternal
655 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_ALLOW_ANY_USER, false);
Clara Bayarri6934a042015-10-14 11:07:35 +0100656 int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700657 if (userId == LockPatternUtils.USER_FRP) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700658 return allowAnyUser ? userId : enforceSystemUser(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700659 } else {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700660 return allowAnyUser ? userId : enforceSameOwner(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700661 }
662 }
663
664 /**
665 * Returns the given user id if the current user is the system user.
666 *
667 * @throws SecurityException if the current user is not the system user.
668 */
669 public static int enforceSystemUser(Context context, int userId) {
670 if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
671 return userId;
672 }
673 throw new SecurityException("Given user id " + userId + " must only be used from "
674 + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100675 }
676
677 /**
678 * Returns the given user id if it belongs to the current user.
679 *
680 * @throws SecurityException if the given userId does not belong to the current user group.
681 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000682 public static int enforceSameOwner(Context context, int userId) {
Ricky Wai72500162016-06-07 16:54:25 +0100683 final UserManager um = getUserManager(context);
684 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
685 if (ArrayUtils.contains(profileIds, userId)) {
686 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +0100687 }
Ricky Wai72500162016-06-07 16:54:25 +0100688 throw new SecurityException("Given user id " + userId + " does not belong to user "
689 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100690 }
691
Benjamin Franz194300d2016-01-13 12:16:25 +0000692 /**
693 * Returns the effective credential owner of the calling user.
694 */
695 public static int getCredentialOwnerUserId(Context context) {
696 return getCredentialOwnerUserId(context, UserHandle.myUserId());
697 }
698
699 /**
700 * Returns the user id of the credential owner of the given user id.
701 */
702 public static int getCredentialOwnerUserId(Context context, int userId) {
703 UserManager um = getUserManager(context);
704 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700705 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500706
Jason Monkb37e2882016-01-11 14:27:20 -0500707 private static final StringBuilder sBuilder = new StringBuilder(50);
708 private static final java.util.Formatter sFormatter = new java.util.Formatter(
709 sBuilder, Locale.getDefault());
710
711 public static String formatDateRange(Context context, long start, long end) {
712 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
713
714 synchronized (sBuilder) {
715 sBuilder.setLength(0);
716 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
717 .toString();
718 }
719 }
Jason Monk91e2f892016-02-23 15:31:09 -0500720
Udam Saini679f7ad2016-03-25 10:47:00 -0700721 public static boolean isDeviceProvisioned(Context context) {
722 return Settings.Global.getInt(context.getContentResolver(),
723 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
724 }
Ricky Wai616342b2016-04-13 10:40:22 +0100725
Bernard Chau88d523b2016-04-14 15:08:28 +0100726 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100727 int userId) {
728 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
729 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
730 context.startActivity(intent);
731 return true;
732 }
733 return false;
734 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700735
Rubin Xu3231afe2016-08-24 10:15:07 +0100736 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
737 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800738 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100739 ActivityManager.FLAG_AND_LOCKED)) {
740 return false;
741 }
742 } catch (RemoteException e) {
743 return false;
744 }
745 if (!(new LockPatternUtils(context)).isSecure(userId)) {
746 return false;
747 }
Robin Leecccf3242017-02-10 15:32:49 +0000748 return confirmWorkProfileCredentials(context, userId);
749 }
750
Robin Leecccf3242017-02-10 15:32:49 +0000751 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100752 final KeyguardManager km = (KeyguardManager) context.getSystemService(
753 Context.KEYGUARD_SERVICE);
754 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
755 if (unlockIntent != null) {
756 context.startActivity(unlockIntent);
757 return true;
758 } else {
759 return false;
760 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100761 }
762
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700763 public static CharSequence getApplicationLabel(Context context, String packageName) {
764 try {
765 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
766 packageName,
767 PackageManager.MATCH_DISABLED_COMPONENTS
Amith Yamasani21556cd2016-11-01 15:49:21 -0700768 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700769 return appInfo.loadLabel(context.getPackageManager());
770 } catch (PackageManager.NameNotFoundException e) {
771 Log.w(TAG, "Unable to find info for package: " + packageName);
772 }
773 return null;
774 }
Jason Monk75199542016-05-06 15:09:32 -0400775
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600776 public static boolean isPackageDirectBootAware(Context context, String packageName) {
777 try {
778 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
779 packageName, 0);
780 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
781 } catch (NameNotFoundException ignored) {
782 }
783 return false;
784 }
Andre Lago3e398c82016-07-25 14:12:28 +0100785
786 /**
787 * Returns a context created from the given context for the given user, or null if it fails
788 */
789 public static Context createPackageContextAsUser(Context context, int userId) {
790 try {
791 return context.createPackageContextAsUser(
792 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
793 } catch (PackageManager.NameNotFoundException e) {
794 Log.e(TAG, "Failed to create user context", e);
795 }
796 return null;
797 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600798
799 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
800 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800801 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600802 } else {
803 return null;
804 }
805 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800806
Kevin Chyn82792cc2017-07-20 00:15:44 -0700807 public static boolean hasFingerprintHardware(Context context) {
808 FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
809 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
810 }
811
Kevin Chyn4882e872018-06-25 17:58:31 -0700812 public static FaceManager getFaceManagerOrNull(Context context) {
813 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
814 return (FaceManager) context.getSystemService(Context.FACE_SERVICE);
815 } else {
816 return null;
817 }
818 }
819
820 public static boolean hasFaceHardware(Context context) {
821 FaceManager faceManager = getFaceManagerOrNull(context);
822 return faceManager != null && faceManager.isHardwareDetected();
823 }
824
Daniel Nishi31027da2017-01-19 14:03:57 -0800825 /**
826 * Launches an intent which may optionally have a user id defined.
827 * @param fragment Fragment to use to launch the activity.
828 * @param intent Intent to launch.
829 */
830 public static void launchIntent(Fragment fragment, Intent intent) {
831 try {
832 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
833
834 if (userId == -1) {
835 fragment.startActivity(intent);
836 } else {
837 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
838 }
839 } catch (ActivityNotFoundException e) {
840 Log.w(TAG, "No activity found for " + intent);
841 }
842 }
843
Christine Franksc6890ab2017-06-23 14:28:21 -0700844 public static boolean isDemoUser(Context context) {
845 return UserManager.isDeviceInDemoMode(context) && getUserManager(context).isDemoUser();
846 }
847
Justin Klaassen30257272017-08-08 21:58:05 -0700848 public static ComponentName getDeviceOwnerComponent(Context context) {
849 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
850 Context.DEVICE_POLICY_SERVICE);
851 return dpm.getDeviceOwnerComponentOnAnyUser();
Christine Franks14782222017-01-23 16:44:02 -0800852 }
Daniel Nishidfed8a22017-01-19 16:32:41 -0800853
854 /**
855 * Returns if a given user is a profile of another user.
Christine Franksa0dd9872017-07-11 17:32:57 -0700856 * @param user The user whose profiles wibe checked.
Daniel Nishidfed8a22017-01-19 16:32:41 -0800857 * @param profile The (potential) profile.
858 * @return if the profile is actually a profile
859 */
860 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
861 return user.id == profile.id ||
862 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
863 && user.profileGroupId == profile.profileGroupId);
864 }
Daniel Nishi9f60f422017-02-15 15:25:48 -0800865
866 /**
867 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
868 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
869 */
870 @Nullable
871 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
872 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
873 VolumeInfo.ID_PRIVATE_INTERNAL);
874 VolumeInfo volume = sm.findVolumeById(volumeId);
875 return isVolumeValid(volume) ? volume : null;
876 }
877
jackqdyuleiddba9662017-03-08 19:35:02 -0800878 /**
jackqdyulei00015fb2017-08-22 11:25:30 -0700879 * Return {@code true} if the supplied package is device owner or profile owner of at
880 * least one user.
881 * @param userManager used to get profile owner app for each user
882 * @param devicePolicyManager used to check whether it is device owner app
883 * @param packageName package to check about
884 */
885 public static boolean isProfileOrDeviceOwner(UserManager userManager,
Fan Zhangaab36de2018-03-30 16:58:28 -0700886 DevicePolicyManager devicePolicyManager, String packageName) {
jackqdyulei00015fb2017-08-22 11:25:30 -0700887 List<UserInfo> userInfos = userManager.getUsers();
888 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
889 return true;
890 }
891 for (int i = 0, size = userInfos.size(); i < size; i++) {
892 ComponentName cn = devicePolicyManager.getProfileOwnerAsUser(userInfos.get(i).id);
893 if (cn != null && cn.getPackageName().equals(packageName)) {
894 return true;
895 }
896 }
897 return false;
898 }
899
900 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800901 * Return the resource id to represent the install status for an app
902 */
903 @StringRes
904 public static int getInstallationStatus(ApplicationInfo info) {
905 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
906 return R.string.not_installed;
907 }
908 return info.enabled ? R.string.installed : R.string.disabled;
909 }
910
Daniel Nishi9f60f422017-02-15 15:25:48 -0800911 private static boolean isVolumeValid(VolumeInfo volume) {
912 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
913 && volume.isMountedReadable();
914 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700915
PMS2263a05602017-06-14 07:10:15 +0000916 public static void setEditTextCursorPosition(EditText editText) {
917 editText.setSelection(editText.getText().length());
918 }
Felipe Lemebd884502017-09-15 18:16:21 -0700919
920 /**
921 * Sets the preference icon with a drawable that is scaled down to to avoid crashing Settings if
922 * it's too big.
923 */
924 public static void setSafeIcon(Preference pref, Drawable icon) {
925 Drawable safeIcon = icon;
Phil Weaver5a3e02d2018-03-08 17:38:46 -0800926 if ((icon != null) && !(icon instanceof VectorDrawable)) {
Felipe Lemebd884502017-09-15 18:16:21 -0700927 safeIcon = getSafeDrawable(icon, 500, 500);
928 }
929 pref.setIcon(safeIcon);
930 }
931
932 /**
933 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
934 *
935 * @param original original drawable, typically an app icon.
936 * @param maxWidth maximum width, in pixels.
937 * @param maxHeight maximum height, in pixels.
938 */
939 public static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
940 final int actualWidth = original.getMinimumWidth();
941 final int actualHeight = original.getMinimumHeight();
942
943 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
944 return original;
945 }
946
947 float scaleWidth = ((float) maxWidth) / actualWidth;
948 float scaleHeight = ((float) maxHeight) / actualHeight;
949 float scale = Math.min(scaleWidth, scaleHeight);
950 final int width = (int) (actualWidth * scale);
951 final int height = (int) (actualHeight * scale);
952
953 final Bitmap bitmap;
954 if (original instanceof BitmapDrawable) {
955 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
956 height, false);
957 } else {
Jason Chiuc78c54a2019-02-13 16:07:57 +0800958 bitmap = createBitmap(original, width, height);
Felipe Lemebd884502017-09-15 18:16:21 -0700959 }
960 return new BitmapDrawable(null, bitmap);
961 }
jackqdyuleifde637f2018-01-02 14:51:01 -0800962
963 /**
Jason Chiuc78c54a2019-02-13 16:07:57 +0800964 * Create an Icon pointing to a drawable.
Jason Chiu1217bbe2019-01-24 16:32:31 +0800965 */
Jason Chiuc78c54a2019-02-13 16:07:57 +0800966 public static IconCompat createIconWithDrawable(Drawable drawable) {
967 Bitmap bitmap;
Jason Chiu1217bbe2019-01-24 16:32:31 +0800968 if (drawable instanceof BitmapDrawable) {
Jason Chiuc78c54a2019-02-13 16:07:57 +0800969 bitmap = ((BitmapDrawable)drawable).getBitmap();
970 } else {
971 final int width = drawable.getIntrinsicWidth();
972 final int height = drawable.getIntrinsicHeight();
973 bitmap = createBitmap(drawable,
974 width > 0 ? width : 1,
975 height > 0 ? height : 1);
Jason Chiu1217bbe2019-01-24 16:32:31 +0800976 }
Jason Chiuc78c54a2019-02-13 16:07:57 +0800977 return IconCompat.createWithBitmap(bitmap);
978 }
Jason Chiu1217bbe2019-01-24 16:32:31 +0800979
Jason Chiuc78c54a2019-02-13 16:07:57 +0800980 private static Bitmap createBitmap(Drawable drawable, int width, int height) {
981 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Jason Chiu1217bbe2019-01-24 16:32:31 +0800982 final Canvas canvas = new Canvas(bitmap);
983 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
984 drawable.draw(canvas);
985 return bitmap;
986 }
987
988 /**
jackqdyuleifde637f2018-01-02 14:51:01 -0800989 * Get the {@link Drawable} that represents the app icon
990 */
991 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
992 PackageManager packageManager, String packageName, int userId) {
993 try {
Tony Mak4e292812018-03-19 15:37:21 +0000994 final ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
995 packageName, PackageManager.GET_META_DATA, userId);
jackqdyuleifde637f2018-01-02 14:51:01 -0800996 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
997 } catch (PackageManager.NameNotFoundException e) {
998 return packageManager.getDefaultActivityIcon();
999 }
1000 }
Raff Tsai2928cd42018-11-05 16:10:19 +08001001
1002 /** Returns true if the current package is installed & enabled. */
1003 public static boolean isPackageEnabled(Context context, String packageName) {
1004 try {
1005 return context.getPackageManager().getApplicationInfo(packageName, 0).enabled;
1006 } catch (Exception e) {
1007 Log.e(TAG, "Error while retrieving application info for package " + packageName, e);
1008 }
1009 return false;
1010 }
markchien1dd1d792019-01-11 16:18:20 +08001011
1012 /** Get {@link Resources} by subscription id if subscription id is valid. */
1013 public static Resources getResourcesForSubId(Context context, int subId) {
1014 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1015 return SubscriptionManager.getResourcesForSubId(context, subId);
1016 } else {
1017 return context.getResources();
1018 }
1019 }
Ng Zhi Anb97bdc32019-02-01 12:39:31 -08001020
1021 /**
1022 * Returns true if SYSTEM_ALERT_WINDOW permission is available.
1023 * Starting from Q, SYSTEM_ALERT_WINDOW is disabled on low ram phones.
1024 */
1025 public static boolean isSystemAlertWindowEnabled(Context context) {
1026 // SYSTEM_ALERT_WINDOW is disabled on on low ram devices starting from Q
1027 ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
1028 return !(am.isLowRamDevice() && (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q));
1029 }
tmfangaed8f362019-03-18 16:56:09 +08001030
1031 /**
1032 * Adds a shadow appear/disappear animation to action bar scroll.
1033 *
1034 * <p/>
1035 * This method must be called after {@link Fragment#onCreate(Bundle)}.
1036 */
1037 public static void setActionBarShadowAnimation(Activity activity, Lifecycle lifecycle,
1038 View scrollView) {
1039 if (activity == null) {
1040 Log.w(TAG, "No activity, cannot style actionbar.");
1041 return;
1042 }
1043 final ActionBar actionBar = activity.getActionBar();
1044 if (actionBar == null) {
1045 Log.w(TAG, "No actionbar, cannot style actionbar.");
1046 return;
1047 }
1048 actionBar.setElevation(0);
1049
1050 if (lifecycle != null && scrollView != null) {
1051 ActionBarShadowController.attachToView(activity, lifecycle, scrollView);
1052 }
1053 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001054}