blob: 804c7830d20d775f485e2f98750594c8e9bc1c9e [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;
Amith Yamasaniae697552011-09-27 11:33:17 -070025import android.app.ActivityManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010026import android.app.AppGlobals;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010027import android.app.IActivityManager;
Rubin Xu3231afe2016-08-24 10:15:07 +010028import android.app.KeyguardManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010029import android.app.admin.DevicePolicyManager;
Daniel Nishi31027da2017-01-19 14:03:57 -080030import android.content.ActivityNotFoundException;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080031import android.content.ComponentName;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070032import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080033import android.content.Context;
34import android.content.Intent;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080035import android.content.IntentFilter;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080036import android.content.pm.ApplicationInfo;
Sudheer Shankabc956302015-04-09 12:19:53 +010037import android.content.pm.IPackageManager;
Christopher Tatea08a2252015-07-01 16:52:43 -070038import android.content.pm.IntentFilterVerificationInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080039import android.content.pm.PackageManager;
Jason Monk75199542016-05-06 15:09:32 -040040import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070041import android.content.pm.ResolveInfo;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070042import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020043import android.content.res.Resources;
Jason Monkb5aa73f2015-03-31 12:59:33 -040044import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070045import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070046import android.graphics.Bitmap;
Felipe Lemebd884502017-09-15 18:16:21 -070047import android.graphics.Canvas;
48import android.graphics.drawable.BitmapDrawable;
49import android.graphics.drawable.Drawable;
Phil Weaver5a3e02d2018-03-08 17:38:46 -080050import android.graphics.drawable.VectorDrawable;
Kevin Chyn4882e872018-06-25 17:58:31 -070051import android.hardware.face.FaceManager;
Jeff Sharkeyab508072016-10-11 14:25:22 -060052import android.hardware.fingerprint.FingerprintManager;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080053import android.net.ConnectivityManager;
54import android.net.LinkProperties;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070055import android.net.Network;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070056import android.net.wifi.WifiManager;
Amith Yamasania4379d62011-07-22 10:34:58 -070057import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020058import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010059import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040060import android.os.INetworkManagementService;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010061import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040062import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070063import android.os.UserHandle;
64import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080065import android.os.storage.StorageManager;
Daniel Nishi9f60f422017-02-15 15:25:48 -080066import android.os.storage.VolumeInfo;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070067import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070068import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070069import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070070import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070071import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070072import android.provider.ContactsContract.RawContacts;
Udam Saini679f7ad2016-03-25 10:47:00 -070073import android.provider.Settings;
markchien1dd1d792019-01-11 16:18:20 +080074import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070075import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040076import android.text.Spannable;
77import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020078import android.text.TextUtils;
Jason Monkb37e2882016-01-11 14:27:20 -050079import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040080import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070081import android.util.ArraySet;
jackqdyuleifde637f2018-01-02 14:51:01 -080082import android.util.IconDrawableFactory;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010083import android.util.Log;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000084import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070085import android.view.View;
86import android.view.ViewGroup;
PMS2263a05602017-06-14 07:10:15 +000087import android.widget.EditText;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070088import android.widget.ListView;
89import android.widget.TabWidget;
Fan Zhangcc335d92016-09-29 14:37:14 -070090
Fan Zhang23f8d592018-08-28 15:11:40 -070091import androidx.annotation.StringRes;
Jason Chiuc78c54a2019-02-13 16:07:57 +080092import androidx.core.graphics.drawable.IconCompat;
Fan Zhang23f8d592018-08-28 15:11:40 -070093import androidx.fragment.app.Fragment;
94import androidx.preference.Preference;
95import androidx.preference.PreferenceGroup;
96
Ricky Wai616342b2016-04-13 10:40:22 +010097import com.android.internal.app.UnlaunchableAppActivity;
Ricky Wai72500162016-06-07 16:54:25 +010098import com.android.internal.util.ArrayUtils;
Rubin Xu3231afe2016-08-24 10:15:07 +010099import com.android.internal.widget.LockPatternUtils;
Jeff Sharkey219ec912017-12-19 14:57:39 -0700100import com.android.settings.password.ChooseLockSettingsHelper;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700101
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800102import java.net.InetAddress;
103import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700104import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900105import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800106
Jason Monk27985e12016-01-08 14:13:05 -0500107public final class Utils extends com.android.settingslib.Utils {
108
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100109 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100110
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800111 /**
112 * Set the preference's title to the matching activity's label.
113 */
114 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
115
Fan Zhangc3fd2892019-01-29 16:00:19 -0800116 public static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100117
Jason Monkbeb171d2015-05-21 15:24:37 -0400118 public static final String OS_PKG = "os";
119
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200120 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800121 * Finds a matching activity for a preference's intent. If a matching
122 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800123 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800124 * @param context The context.
125 * @param parentPreferenceGroup The preference group that contains the
126 * preference whose intent is being resolved.
127 * @param preferenceKey The key of the preference whose intent is being
128 * resolved.
129 * @param flags 0 or one or more of
130 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
131 * .
132 * @return Whether an activity was found. If false, the preference was
133 * removed.
134 */
135 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
136 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800137
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800138 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
139 if (preference == null) {
140 return false;
141 }
Ying Wanga7188322010-01-04 18:45:10 -0800142
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800143 Intent intent = preference.getIntent();
144 if (intent != null) {
145 // Find the activity that is in the system image
146 PackageManager pm = context.getPackageManager();
147 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
148 int listSize = list.size();
149 for (int i = 0; i < listSize; i++) {
150 ResolveInfo resolveInfo = list.get(i);
151 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
152 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800153
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800154 // Replace the intent with this specific activity
155 preference.setIntent(new Intent().setClassName(
156 resolveInfo.activityInfo.packageName,
157 resolveInfo.activityInfo.name));
158
159 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
160 // Set the preference title to the activity's label
161 preference.setTitle(resolveInfo.loadLabel(pm));
162 }
Ying Wanga7188322010-01-04 18:45:10 -0800163
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800164 return true;
165 }
166 }
167 }
168
169 // Did not find a matching activity, so remove the preference
170 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800171
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900172 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800173 }
Ying Wanga7188322010-01-04 18:45:10 -0800174
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200175 /**
Benjamin Franz194300d2016-01-13 12:16:25 +0000176 * Returns the UserManager for a given context
177 *
178 * @throws IllegalStateException if no UserManager could be retrieved.
179 */
180 public static UserManager getUserManager(Context context) {
181 UserManager um = UserManager.get(context);
182 if (um == null) {
183 throw new IllegalStateException("Unable to load UserManager");
184 }
185 return um;
186 }
187
188 /**
Ying Wanga7188322010-01-04 18:45:10 -0800189 * Returns true if Monkey is running.
190 */
191 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700192 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800193 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700194
195 /**
196 * Returns whether the device is voice-capable (meaning, it is also a phone).
197 */
198 public static boolean isVoiceCapable(Context context) {
199 TelephonyManager telephony =
200 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
201 return telephony != null && telephony.isVoiceCapable();
202 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800203
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800204 /**
205 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
206 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900207 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800208 */
209 public static String getWifiIpAddresses(Context context) {
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700210 WifiManager wifiManager = context.getSystemService(WifiManager.class);
211 Network currentNetwork = wifiManager.getCurrentNetwork();
212 if (currentNetwork != null) {
213 ConnectivityManager cm = (ConnectivityManager)
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800214 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700215 LinkProperties prop = cm.getLinkProperties(currentNetwork);
216 return formatIpAddresses(prop);
217 }
218 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700219 }
220
Amith Yamasani6822b742011-10-17 16:41:00 -0700221 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800222 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900223 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800224 // If there are no entries, return null
225 if (!iter.hasNext()) return null;
226 // Concatenate all available addresses, comma separated
227 String addresses = "";
228 while (iter.hasNext()) {
229 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900230 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800231 }
232 return addresses;
233 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900234
235 public static Locale createLocaleFromString(String localeStr) {
236 // TODO: is there a better way to actually construct a locale that will match?
237 // The main problem is, on top of Java specs, locale.toString() and
238 // new Locale(locale.toString()).toString() do not return equal() strings in
239 // many cases, because the constructor takes the only string as the language
240 // code. So : new Locale("en", "US").toString() => "en_US"
241 // And : new Locale("en_US").toString() => "en_us"
242 if (null == localeStr)
243 return Locale.getDefault();
244 String[] brokenDownLocale = localeStr.split("_", 3);
245 // split may not return a 0-length array.
246 if (1 == brokenDownLocale.length) {
247 return new Locale(brokenDownLocale[0]);
248 } else if (2 == brokenDownLocale.length) {
249 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
250 } else {
251 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
252 }
253 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700254
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900255 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
256 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
257 }
258
Amith Yamasania4379d62011-07-22 10:34:58 -0700259 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700260 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700261 }
262
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700263 /**
264 * Prepare a custom preferences layout, moving padding to {@link ListView}
265 * when outside scrollbars are requested. Usually used to display
266 * {@link ListView} and {@link TabWidget} with correct padding.
267 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700268 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800269 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700270 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700271 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700272 final Resources res = list.getResources();
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700273 final int paddingBottom = res.getDimensionPixelSize(
274 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700275
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700276 if (parent instanceof PreferenceFrameLayout) {
277 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700278 }
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800279 list.setPaddingRelative(0 /* start */, 0 /* top */, 0 /* end */, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700280 }
281 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700282
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700283 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700284 final Resources res = view.getResources();
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700285
Doris Lingc5a1b4f2019-02-20 16:33:24 -0800286 final int paddingStart = additive ? view.getPaddingStart() : 0;
287 final int paddingEnd = additive ? view.getPaddingEnd() : 0;
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700288 final int paddingBottom = res.getDimensionPixelSize(
289 com.android.internal.R.dimen.preference_fragment_padding_bottom);
290
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700291 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700292 }
293
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700294 public static String getMeProfileName(Context context, boolean full) {
295 if (full) {
296 return getProfileDisplayName(context);
297 } else {
298 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700299 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700300 }
301
302 private static String getShorterNameIfPossible(Context context) {
303 final String given = getLocalProfileGivenName(context);
304 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
305 }
306
307 private static String getLocalProfileGivenName(Context context) {
308 final ContentResolver cr = context.getContentResolver();
309
310 // Find the raw contact ID for the local ME profile raw contact.
311 final long localRowProfileId;
312 final Cursor localRawProfile = cr.query(
313 Profile.CONTENT_RAW_CONTACTS_URI,
314 new String[] {RawContacts._ID},
315 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
316 RawContacts.ACCOUNT_NAME + " IS NULL",
317 null, null);
318 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700319
320 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700321 if (!localRawProfile.moveToFirst()) {
322 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700323 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700324 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700325 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700326 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700327 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700328
329 // Find the structured name for the raw contact.
330 final Cursor structuredName = cr.query(
331 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
332 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
333 CommonDataKinds.StructuredName.FAMILY_NAME},
334 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
335 null, null);
336 if (structuredName == null) return null;
337
338 try {
339 if (!structuredName.moveToFirst()) {
340 return null;
341 }
342 String partialName = structuredName.getString(0);
343 if (TextUtils.isEmpty(partialName)) {
344 partialName = structuredName.getString(1);
345 }
346 return partialName;
347 } finally {
348 structuredName.close();
349 }
350 }
351
352 private static final String getProfileDisplayName(Context context) {
353 final ContentResolver cr = context.getContentResolver();
354 final Cursor profile = cr.query(Profile.CONTENT_URI,
355 new String[] {Profile.DISPLAY_NAME}, null, null, null);
356 if (profile == null) return null;
357
358 try {
359 if (!profile.moveToFirst()) {
360 return null;
361 }
362 return profile.getString(0);
363 } finally {
364 profile.close();
365 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700366 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700367
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700368 public static boolean hasMultipleUsers(Context context) {
369 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
370 .getUsers().size() > 1;
371 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700372
373 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100374 * Returns the managed profile of the current user or {@code null} if none is found or a profile
375 * exists but it is disabled.
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100376 */
377 public static UserHandle getManagedProfile(UserManager userManager) {
378 List<UserHandle> userProfiles = userManager.getUserProfiles();
Aarthi Balachanderd0f83592018-07-10 17:04:53 -0700379 for (UserHandle profile : userProfiles) {
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100380 if (profile.getIdentifier() == userManager.getUserHandle()) {
381 continue;
382 }
383 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
384 if (userInfo.isManagedProfile()) {
385 return profile;
386 }
387 }
388 return null;
389 }
390
391 /**
Esteban Talavera9b86e9c2017-05-30 16:48:08 +0100392 * Returns the managed profile of the current user or {@code null} if none is found. Unlike
393 * {@link #getManagedProfile} this method returns enabled and disabled managed profiles.
394 */
395 public static UserHandle getManagedProfileWithDisabled(UserManager userManager) {
396 // TODO: Call getManagedProfileId from here once Robolectric supports
397 // API level 24 and UserManager.getProfileIdsWithDisabled can be Mocked (to avoid having
398 // yet another implementation that loops over user profiles in this method). In the meantime
399 // we need to use UserManager.getProfiles that is available on API 23 (the one currently
400 // used for Settings Robolectric tests).
401 final int myUserId = UserHandle.myUserId();
402 List<UserInfo> profiles = userManager.getProfiles(myUserId);
403 final int count = profiles.size();
404 for (int i = 0; i < count; i++) {
405 final UserInfo profile = profiles.get(i);
406 if (profile.isManagedProfile()
407 && profile.getUserHandle().getIdentifier() != myUserId) {
408 return profile.getUserHandle();
409 }
410 }
411 return null;
412 }
413
414 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000415 * Retrieves the id for the given user's managed profile.
416 *
417 * @return the managed profile id or UserHandle.USER_NULL if there is none.
418 */
419 public static int getManagedProfileId(UserManager um, int parentUserId) {
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700420 int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
421 for (int profileId : profileIds) {
422 if (profileId != parentUserId) {
423 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000424 }
425 }
426 return UserHandle.USER_NULL;
427 }
428
429 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100430 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000431 * <p>
432 * User would be retrieved in this order:
433 * <ul>
434 * <li> If this activity is launched from other user, return that user id.
435 * <li> If this is launched from the Settings app in same user, return the user contained as an
436 * extra in the arguments or intent extras.
437 * <li> Otherwise, return UserHandle.myUserId().
438 * </ul>
439 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100440 * Note: This is secure in the sense that it only returns a target user different to the current
441 * one if the app launching this activity is the Settings app itself, running in the same user
442 * 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 +0100443 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100444 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000445 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100446 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800447 IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100448 try {
449 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
450 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
451
452 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
453 am.getLaunchedFromUid(activityToken)));
454 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
455 // Check it's secure
456 if (isProfileOf(um, launchedFromUser)) {
457 return launchedFromUser;
458 }
459 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000460 UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100461 if (extrasUser != null && !extrasUser.equals(currentUser)) {
462 // Check it's secure
463 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
464 return extrasUser;
465 }
466 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000467 UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100468 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
469 // Check it's secure
470 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
471 return argumentsUser;
472 }
473 }
474 } catch (RemoteException e) {
475 // Should not happen
476 Log.v(TAG, "Could not talk to activity manager.", e);
477 }
478 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000479 }
480
481 /**
482 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
483 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
484 */
485 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
486 if (bundle == null) {
487 return null;
488 }
489 final UserHandle user = bundle.getParcelable(EXTRA_USER);
490 if (user != null) {
491 return user;
492 }
493 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
494 if (userId != -1) {
495 return UserHandle.of(userId);
496 }
497 return null;
498 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100499
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100500 /**
501 * Returns true if the user provided is in the same profiles group as the current user.
502 */
503 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
504 if (um == null || otherUser == null) return false;
505 return (UserHandle.myUserId() == otherUser.getIdentifier())
506 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100507 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530508
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100509 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700510 * Return whether or not the user should have a SIM Cards option in Settings.
511 * TODO: Change back to returning true if count is greater than one after testing.
512 * TODO: See bug 16533525.
513 */
514 public static boolean showSimCardTile(Context context) {
515 final TelephonyManager tm =
516 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
517
PauloftheWestdbd03822014-12-04 11:56:35 -0800518 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700519 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200520
521 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800522 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
523 * @param userManager Instance of UserManager
524 * @param checkUser The user to check the existence of.
525 * @return UserInfo of the user or null for non-existent user.
526 */
527 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
528 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
529 final int checkUserId = checkUser.getIdentifier();
530 for (UserInfo user : users) {
531 if (user.id == checkUserId) {
532 return user;
533 }
534 }
535 return null;
536 }
537
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000538 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
539 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
540 com.android.internal.R.styleable.Preference,
541 com.android.internal.R.attr.preferenceCategoryStyle, 0);
542 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
543 0);
544 a.recycle();
545 return inflater.inflate(resId, parent, false);
546 }
547
Christopher Tatea08a2252015-07-01 16:52:43 -0700548 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
549 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
550 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
551
552 ArraySet<String> result = new ArraySet<>();
Fan Zhang4e540db2017-11-08 13:06:38 -0800553 if (iviList != null && iviList.size() > 0) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700554 for (IntentFilterVerificationInfo ivi : iviList) {
555 for (String host : ivi.getDomains()) {
556 result.add(host);
557 }
558 }
559 }
560 if (filters != null && filters.size() > 0) {
561 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700562 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
563 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
564 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700565 result.addAll(filter.getHostsList());
566 }
567 }
568 }
569 return result;
570 }
571
Sudheer Shankabc956302015-04-09 12:19:53 +0100572 /**
573 * Returns the application info of the currently installed MDM package.
574 */
575 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
576 DevicePolicyManager dpm =
577 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
578 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
579 if (mdmPackage == null) {
580 return null;
581 }
582 String mdmPackageName = mdmPackage.getPackageName();
583 try {
584 IPackageManager ipm = AppGlobals.getPackageManager();
585 ApplicationInfo mdmApplicationInfo =
586 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
587 return mdmApplicationInfo;
588 } catch (RemoteException e) {
589 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
590 + ", userId " + profileId, e);
591 return null;
592 }
593 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400594
595 public static boolean isBandwidthControlEnabled() {
596 final INetworkManagementService netManager = INetworkManagementService.Stub
597 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
598 try {
599 return netManager.isBandwidthControlEnabled();
600 } catch (RemoteException e) {
601 return false;
602 }
603 }
Julia Reynoldsce25af42015-07-08 16:56:31 -0400604
605 /**
606 * Returns an accessible SpannableString.
607 * @param displayText the text to display
608 * @param accessibileText the text text-to-speech engines should read
609 */
610 public static SpannableString createAccessibleSequence(CharSequence displayText,
611 String accessibileText) {
612 SpannableString str = new SpannableString(displayText);
613 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
614 displayText.length(),
615 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
616 return str;
617 }
Andres Morales7bdffd82015-08-04 16:55:00 -0700618
Clara Bayarrife432e82015-10-12 12:07:02 +0100619 /**
Jeff Sharkey219ec912017-12-19 14:57:39 -0700620 * Returns the user id present in the bundle with
621 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
Clara Bayarrife432e82015-10-12 12:07:02 +0100622 *
Jeff Sharkey219ec912017-12-19 14:57:39 -0700623 * @throws SecurityException if the given userId does not belong to the
624 * current user group.
Clara Bayarrife432e82015-10-12 12:07:02 +0100625 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000626 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700627 return getUserIdFromBundle(context, bundle, false);
628 }
629
630 /**
631 * Returns the user id present in the bundle with
632 * {@link Intent#EXTRA_USER_ID} if it belongs to the current user.
633 *
634 * @param isInternal indicating if the caller is "internal" to the system,
635 * meaning we're willing to trust extras like
636 * {@link ChooseLockSettingsHelper#EXTRA_ALLOW_ANY_USER}.
637 * @throws SecurityException if the given userId does not belong to the
638 * current user group.
639 */
640 public static int getUserIdFromBundle(Context context, Bundle bundle, boolean isInternal) {
Clara Bayarrife432e82015-10-12 12:07:02 +0100641 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +0000642 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +0100643 }
Jeff Sharkey219ec912017-12-19 14:57:39 -0700644 final boolean allowAnyUser = isInternal
645 && bundle.getBoolean(ChooseLockSettingsHelper.EXTRA_ALLOW_ANY_USER, false);
Clara Bayarri6934a042015-10-14 11:07:35 +0100646 int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700647 if (userId == LockPatternUtils.USER_FRP) {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700648 return allowAnyUser ? userId : enforceSystemUser(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700649 } else {
Jeff Sharkey219ec912017-12-19 14:57:39 -0700650 return allowAnyUser ? userId : enforceSameOwner(context, userId);
Adrian Roos5a9a3cd2017-03-30 18:02:25 -0700651 }
652 }
653
654 /**
655 * Returns the given user id if the current user is the system user.
656 *
657 * @throws SecurityException if the current user is not the system user.
658 */
659 public static int enforceSystemUser(Context context, int userId) {
660 if (UserHandle.myUserId() == UserHandle.USER_SYSTEM) {
661 return userId;
662 }
663 throw new SecurityException("Given user id " + userId + " must only be used from "
664 + "USER_SYSTEM, but current user is " + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100665 }
666
667 /**
668 * Returns the given user id if it belongs to the current user.
669 *
670 * @throws SecurityException if the given userId does not belong to the current user group.
671 */
Benjamin Franz194300d2016-01-13 12:16:25 +0000672 public static int enforceSameOwner(Context context, int userId) {
Ricky Wai72500162016-06-07 16:54:25 +0100673 final UserManager um = getUserManager(context);
674 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
675 if (ArrayUtils.contains(profileIds, userId)) {
676 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +0100677 }
Ricky Wai72500162016-06-07 16:54:25 +0100678 throw new SecurityException("Given user id " + userId + " does not belong to user "
679 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +0100680 }
681
Benjamin Franz194300d2016-01-13 12:16:25 +0000682 /**
683 * Returns the effective credential owner of the calling user.
684 */
685 public static int getCredentialOwnerUserId(Context context) {
686 return getCredentialOwnerUserId(context, UserHandle.myUserId());
687 }
688
689 /**
690 * Returns the user id of the credential owner of the given user id.
691 */
692 public static int getCredentialOwnerUserId(Context context, int userId) {
693 UserManager um = getUserManager(context);
694 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -0700695 }
Jason Monkdb4ed192015-12-11 16:48:31 -0500696
Jason Monkb37e2882016-01-11 14:27:20 -0500697 private static final StringBuilder sBuilder = new StringBuilder(50);
698 private static final java.util.Formatter sFormatter = new java.util.Formatter(
699 sBuilder, Locale.getDefault());
700
701 public static String formatDateRange(Context context, long start, long end) {
702 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
703
704 synchronized (sBuilder) {
705 sBuilder.setLength(0);
706 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
707 .toString();
708 }
709 }
Jason Monk91e2f892016-02-23 15:31:09 -0500710
Udam Saini679f7ad2016-03-25 10:47:00 -0700711 public static boolean isDeviceProvisioned(Context context) {
712 return Settings.Global.getInt(context.getContentResolver(),
713 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
714 }
Ricky Wai616342b2016-04-13 10:40:22 +0100715
Bernard Chau88d523b2016-04-14 15:08:28 +0100716 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +0100717 int userId) {
718 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
719 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
720 context.startActivity(intent);
721 return true;
722 }
723 return false;
724 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700725
Rubin Xu3231afe2016-08-24 10:15:07 +0100726 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
727 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800728 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +0100729 ActivityManager.FLAG_AND_LOCKED)) {
730 return false;
731 }
732 } catch (RemoteException e) {
733 return false;
734 }
735 if (!(new LockPatternUtils(context)).isSecure(userId)) {
736 return false;
737 }
Robin Leecccf3242017-02-10 15:32:49 +0000738 return confirmWorkProfileCredentials(context, userId);
739 }
740
Robin Leecccf3242017-02-10 15:32:49 +0000741 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +0100742 final KeyguardManager km = (KeyguardManager) context.getSystemService(
743 Context.KEYGUARD_SERVICE);
744 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
745 if (unlockIntent != null) {
746 context.startActivity(unlockIntent);
747 return true;
748 } else {
749 return false;
750 }
Rubin Xu3231afe2016-08-24 10:15:07 +0100751 }
752
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700753 public static CharSequence getApplicationLabel(Context context, String packageName) {
754 try {
755 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
756 packageName,
757 PackageManager.MATCH_DISABLED_COMPONENTS
Amith Yamasani21556cd2016-11-01 15:49:21 -0700758 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -0700759 return appInfo.loadLabel(context.getPackageManager());
760 } catch (PackageManager.NameNotFoundException e) {
761 Log.w(TAG, "Unable to find info for package: " + packageName);
762 }
763 return null;
764 }
Jason Monk75199542016-05-06 15:09:32 -0400765
Jeff Sharkey4a8136b2016-07-27 12:53:34 -0600766 public static boolean isPackageDirectBootAware(Context context, String packageName) {
767 try {
768 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
769 packageName, 0);
770 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
771 } catch (NameNotFoundException ignored) {
772 }
773 return false;
774 }
Andre Lago3e398c82016-07-25 14:12:28 +0100775
776 /**
777 * Returns a context created from the given context for the given user, or null if it fails
778 */
779 public static Context createPackageContextAsUser(Context context, int userId) {
780 try {
781 return context.createPackageContextAsUser(
782 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
783 } catch (PackageManager.NameNotFoundException e) {
784 Log.e(TAG, "Failed to create user context", e);
785 }
786 return null;
787 }
Jeff Sharkeyab508072016-10-11 14:25:22 -0600788
789 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
790 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
Fan Zhangcf97f0b2018-01-05 11:18:44 -0800791 return (FingerprintManager) context.getSystemService(Context.FINGERPRINT_SERVICE);
Jeff Sharkeyab508072016-10-11 14:25:22 -0600792 } else {
793 return null;
794 }
795 }
Daniel Nishi31027da2017-01-19 14:03:57 -0800796
Kevin Chyn82792cc2017-07-20 00:15:44 -0700797 public static boolean hasFingerprintHardware(Context context) {
798 FingerprintManager fingerprintManager = getFingerprintManagerOrNull(context);
799 return fingerprintManager != null && fingerprintManager.isHardwareDetected();
800 }
801
Kevin Chyn4882e872018-06-25 17:58:31 -0700802 public static FaceManager getFaceManagerOrNull(Context context) {
803 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FACE)) {
804 return (FaceManager) context.getSystemService(Context.FACE_SERVICE);
805 } else {
806 return null;
807 }
808 }
809
810 public static boolean hasFaceHardware(Context context) {
811 FaceManager faceManager = getFaceManagerOrNull(context);
812 return faceManager != null && faceManager.isHardwareDetected();
813 }
814
Daniel Nishi31027da2017-01-19 14:03:57 -0800815 /**
816 * Launches an intent which may optionally have a user id defined.
817 * @param fragment Fragment to use to launch the activity.
818 * @param intent Intent to launch.
819 */
820 public static void launchIntent(Fragment fragment, Intent intent) {
821 try {
822 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
823
824 if (userId == -1) {
825 fragment.startActivity(intent);
826 } else {
827 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
828 }
829 } catch (ActivityNotFoundException e) {
830 Log.w(TAG, "No activity found for " + intent);
831 }
832 }
833
Christine Franksc6890ab2017-06-23 14:28:21 -0700834 public static boolean isDemoUser(Context context) {
835 return UserManager.isDeviceInDemoMode(context) && getUserManager(context).isDemoUser();
836 }
837
Justin Klaassen30257272017-08-08 21:58:05 -0700838 public static ComponentName getDeviceOwnerComponent(Context context) {
839 final DevicePolicyManager dpm = (DevicePolicyManager) context.getSystemService(
840 Context.DEVICE_POLICY_SERVICE);
841 return dpm.getDeviceOwnerComponentOnAnyUser();
Christine Franks14782222017-01-23 16:44:02 -0800842 }
Daniel Nishidfed8a22017-01-19 16:32:41 -0800843
844 /**
845 * Returns if a given user is a profile of another user.
Christine Franksa0dd9872017-07-11 17:32:57 -0700846 * @param user The user whose profiles wibe checked.
Daniel Nishidfed8a22017-01-19 16:32:41 -0800847 * @param profile The (potential) profile.
848 * @return if the profile is actually a profile
849 */
850 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
851 return user.id == profile.id ||
852 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
853 && user.profileGroupId == profile.profileGroupId);
854 }
Daniel Nishi9f60f422017-02-15 15:25:48 -0800855
856 /**
857 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
858 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
859 */
860 @Nullable
861 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
862 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
863 VolumeInfo.ID_PRIVATE_INTERNAL);
864 VolumeInfo volume = sm.findVolumeById(volumeId);
865 return isVolumeValid(volume) ? volume : null;
866 }
867
jackqdyuleiddba9662017-03-08 19:35:02 -0800868 /**
jackqdyulei00015fb2017-08-22 11:25:30 -0700869 * Return {@code true} if the supplied package is device owner or profile owner of at
870 * least one user.
871 * @param userManager used to get profile owner app for each user
872 * @param devicePolicyManager used to check whether it is device owner app
873 * @param packageName package to check about
874 */
875 public static boolean isProfileOrDeviceOwner(UserManager userManager,
Fan Zhangaab36de2018-03-30 16:58:28 -0700876 DevicePolicyManager devicePolicyManager, String packageName) {
jackqdyulei00015fb2017-08-22 11:25:30 -0700877 List<UserInfo> userInfos = userManager.getUsers();
878 if (devicePolicyManager.isDeviceOwnerAppOnAnyUser(packageName)) {
879 return true;
880 }
881 for (int i = 0, size = userInfos.size(); i < size; i++) {
882 ComponentName cn = devicePolicyManager.getProfileOwnerAsUser(userInfos.get(i).id);
883 if (cn != null && cn.getPackageName().equals(packageName)) {
884 return true;
885 }
886 }
887 return false;
888 }
889
890 /**
jackqdyuleiddba9662017-03-08 19:35:02 -0800891 * Return the resource id to represent the install status for an app
892 */
893 @StringRes
894 public static int getInstallationStatus(ApplicationInfo info) {
895 if ((info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
896 return R.string.not_installed;
897 }
898 return info.enabled ? R.string.installed : R.string.disabled;
899 }
900
Daniel Nishi9f60f422017-02-15 15:25:48 -0800901 private static boolean isVolumeValid(VolumeInfo volume) {
902 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
903 && volume.isMountedReadable();
904 }
jackqdyuleif4c1cef2017-03-31 12:57:10 -0700905
PMS2263a05602017-06-14 07:10:15 +0000906 public static void setEditTextCursorPosition(EditText editText) {
907 editText.setSelection(editText.getText().length());
908 }
Felipe Lemebd884502017-09-15 18:16:21 -0700909
910 /**
911 * Sets the preference icon with a drawable that is scaled down to to avoid crashing Settings if
912 * it's too big.
913 */
914 public static void setSafeIcon(Preference pref, Drawable icon) {
915 Drawable safeIcon = icon;
Phil Weaver5a3e02d2018-03-08 17:38:46 -0800916 if ((icon != null) && !(icon instanceof VectorDrawable)) {
Felipe Lemebd884502017-09-15 18:16:21 -0700917 safeIcon = getSafeDrawable(icon, 500, 500);
918 }
919 pref.setIcon(safeIcon);
920 }
921
922 /**
923 * Gets a drawable with a limited size to avoid crashing Settings if it's too big.
924 *
925 * @param original original drawable, typically an app icon.
926 * @param maxWidth maximum width, in pixels.
927 * @param maxHeight maximum height, in pixels.
928 */
929 public static Drawable getSafeDrawable(Drawable original, int maxWidth, int maxHeight) {
930 final int actualWidth = original.getMinimumWidth();
931 final int actualHeight = original.getMinimumHeight();
932
933 if (actualWidth <= maxWidth && actualHeight <= maxHeight) {
934 return original;
935 }
936
937 float scaleWidth = ((float) maxWidth) / actualWidth;
938 float scaleHeight = ((float) maxHeight) / actualHeight;
939 float scale = Math.min(scaleWidth, scaleHeight);
940 final int width = (int) (actualWidth * scale);
941 final int height = (int) (actualHeight * scale);
942
943 final Bitmap bitmap;
944 if (original instanceof BitmapDrawable) {
945 bitmap = Bitmap.createScaledBitmap(((BitmapDrawable) original).getBitmap(), width,
946 height, false);
947 } else {
Jason Chiuc78c54a2019-02-13 16:07:57 +0800948 bitmap = createBitmap(original, width, height);
Felipe Lemebd884502017-09-15 18:16:21 -0700949 }
950 return new BitmapDrawable(null, bitmap);
951 }
jackqdyuleifde637f2018-01-02 14:51:01 -0800952
953 /**
Jason Chiuc78c54a2019-02-13 16:07:57 +0800954 * Create an Icon pointing to a drawable.
Jason Chiu1217bbe2019-01-24 16:32:31 +0800955 */
Jason Chiuc78c54a2019-02-13 16:07:57 +0800956 public static IconCompat createIconWithDrawable(Drawable drawable) {
957 Bitmap bitmap;
Jason Chiu1217bbe2019-01-24 16:32:31 +0800958 if (drawable instanceof BitmapDrawable) {
Jason Chiuc78c54a2019-02-13 16:07:57 +0800959 bitmap = ((BitmapDrawable)drawable).getBitmap();
960 } else {
961 final int width = drawable.getIntrinsicWidth();
962 final int height = drawable.getIntrinsicHeight();
963 bitmap = createBitmap(drawable,
964 width > 0 ? width : 1,
965 height > 0 ? height : 1);
Jason Chiu1217bbe2019-01-24 16:32:31 +0800966 }
Jason Chiuc78c54a2019-02-13 16:07:57 +0800967 return IconCompat.createWithBitmap(bitmap);
968 }
Jason Chiu1217bbe2019-01-24 16:32:31 +0800969
Jason Chiuc78c54a2019-02-13 16:07:57 +0800970 private static Bitmap createBitmap(Drawable drawable, int width, int height) {
971 final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Jason Chiu1217bbe2019-01-24 16:32:31 +0800972 final Canvas canvas = new Canvas(bitmap);
973 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
974 drawable.draw(canvas);
975 return bitmap;
976 }
977
978 /**
jackqdyuleifde637f2018-01-02 14:51:01 -0800979 * Get the {@link Drawable} that represents the app icon
980 */
981 public static Drawable getBadgedIcon(IconDrawableFactory iconDrawableFactory,
982 PackageManager packageManager, String packageName, int userId) {
983 try {
Tony Mak4e292812018-03-19 15:37:21 +0000984 final ApplicationInfo appInfo = packageManager.getApplicationInfoAsUser(
985 packageName, PackageManager.GET_META_DATA, userId);
jackqdyuleifde637f2018-01-02 14:51:01 -0800986 return iconDrawableFactory.getBadgedIcon(appInfo, userId);
987 } catch (PackageManager.NameNotFoundException e) {
988 return packageManager.getDefaultActivityIcon();
989 }
990 }
Raff Tsai2928cd42018-11-05 16:10:19 +0800991
992 /** Returns true if the current package is installed & enabled. */
993 public static boolean isPackageEnabled(Context context, String packageName) {
994 try {
995 return context.getPackageManager().getApplicationInfo(packageName, 0).enabled;
996 } catch (Exception e) {
997 Log.e(TAG, "Error while retrieving application info for package " + packageName, e);
998 }
999 return false;
1000 }
markchien1dd1d792019-01-11 16:18:20 +08001001
1002 /** Get {@link Resources} by subscription id if subscription id is valid. */
1003 public static Resources getResourcesForSubId(Context context, int subId) {
1004 if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
1005 return SubscriptionManager.getResourcesForSubId(context, subId);
1006 } else {
1007 return context.getResources();
1008 }
1009 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001010}