blob: 350ab9ce869962434aaf6a27cd8759d8a7af4c0f [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;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070026import android.app.AlertDialog;
Sudheer Shankabc956302015-04-09 12:19:53 +010027import android.app.AppGlobals;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070028import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070029import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010030import android.app.IActivityManager;
Rubin Xu3231afe2016-08-24 10:15:07 +010031import android.app.KeyguardManager;
Sudheer Shankabc956302015-04-09 12:19:53 +010032import android.app.admin.DevicePolicyManager;
Daniel Nishi31027da2017-01-19 14:03:57 -080033import android.content.ActivityNotFoundException;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080034import android.content.ComponentName;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070035import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080036import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070037import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080038import android.content.Intent;
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -080039import android.content.IntentFilter;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080040import android.content.pm.ApplicationInfo;
Sudheer Shankabc956302015-04-09 12:19:53 +010041import android.content.pm.IPackageManager;
Christopher Tatea08a2252015-07-01 16:52:43 -070042import android.content.pm.IntentFilterVerificationInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080043import android.content.pm.PackageManager;
Jason Monk75199542016-05-06 15:09:32 -040044import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070045import android.content.pm.ResolveInfo;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070046import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020047import android.content.res.Resources;
Jason Monkb5aa73f2015-03-31 12:59:33 -040048import android.content.res.TypedArray;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070049import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070050import android.graphics.Bitmap;
51import android.graphics.BitmapFactory;
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;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070056import android.net.Uri;
Jaewoong Jungc260e6d2016-10-13 14:21:52 -070057import android.net.wifi.WifiManager;
Amith Yamasania4379d62011-07-22 10:34:58 -070058import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020059import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010060import android.os.IBinder;
Jason Monkb45e27b2015-05-20 13:35:43 -040061import android.os.INetworkManagementService;
Jason Monkbe941212016-05-27 12:58:53 -040062import android.os.Looper;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010063import android.os.RemoteException;
Jason Monkb45e27b2015-05-20 13:35:43 -040064import android.os.ServiceManager;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070065import android.os.UserHandle;
66import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080067import android.os.storage.StorageManager;
Daniel Nishi9f60f422017-02-15 15:25:48 -080068import android.os.storage.VolumeInfo;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070069import android.preference.PreferenceFrameLayout;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070070import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070071import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070072import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070073import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070074import android.provider.ContactsContract.RawContacts;
Udam Saini679f7ad2016-03-25 10:47:00 -070075import android.provider.Settings;
Andres Moralesce249fe2014-07-07 16:58:16 -070076import android.service.persistentdata.PersistentDataBlockManager;
Jason Monk39b46742015-09-10 15:52:51 -040077import android.support.v7.preference.Preference;
78import android.support.v7.preference.PreferenceGroup;
Jason Monk91e2f892016-02-23 15:31:09 -050079import android.support.v7.preference.PreferenceManager;
80import android.support.v7.preference.PreferenceScreen;
Amith Yamasani60133dd2010-09-11 14:17:31 -070081import android.telephony.TelephonyManager;
Julia Reynoldsce25af42015-07-08 16:56:31 -040082import android.text.Spannable;
83import android.text.SpannableString;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020084import android.text.TextUtils;
Jason Monkb37e2882016-01-11 14:27:20 -050085import android.text.format.DateUtils;
Julia Reynoldsce25af42015-07-08 16:56:31 -040086import android.text.style.TtsSpan;
Christopher Tatea08a2252015-07-01 16:52:43 -070087import android.util.ArraySet;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010088import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000089import android.util.SparseArray;
Jason Monkdb4ed192015-12-11 16:48:31 -050090import android.util.TypedValue;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000091import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070092import android.view.View;
93import android.view.ViewGroup;
Jason Monkb5aa73f2015-03-31 12:59:33 -040094import android.view.animation.Animation;
95import android.view.animation.Animation.AnimationListener;
96import android.view.animation.AnimationUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070097import android.widget.ListView;
98import android.widget.TabWidget;
Fan Zhangcc335d92016-09-29 14:37:14 -070099
Ricky Wai616342b2016-04-13 10:40:22 +0100100import com.android.internal.app.UnlaunchableAppActivity;
Ricky Wai72500162016-06-07 16:54:25 +0100101import com.android.internal.util.ArrayUtils;
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100102import com.android.internal.util.UserIcons;
Rubin Xu3231afe2016-08-24 10:15:07 +0100103import com.android.internal.widget.LockPatternUtils;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700104
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700105import java.io.IOException;
106import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800107import java.net.InetAddress;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100108import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800109import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -0700110import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +0900111import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800112
Jason Monk27985e12016-01-08 14:13:05 -0500113public final class Utils extends com.android.settingslib.Utils {
114
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100115 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100116
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800117 /**
118 * Set the preference's title to the matching activity's label.
119 */
120 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
121
122 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900123 * The opacity level of a disabled icon.
124 */
125 public static final float DISABLED_ALPHA = 0.4f;
126
127 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700128 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
129 * 1 is most bad (red), the last value is least bad (green).
130 */
131 public static final int[] BADNESS_COLORS = new int[] {
132 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
133 0xfffabf2c, 0xff679e37, 0xff0a7f42
134 };
135
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100136 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
137
Elliott Hughes7253df32014-09-02 17:10:14 -0700138 private static final int SECONDS_PER_MINUTE = 60;
139 private static final int SECONDS_PER_HOUR = 60 * 60;
140 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
141
Jason Monkbeb171d2015-05-21 15:24:37 -0400142 public static final String OS_PKG = "os";
143
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000144 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
145
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200146 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800147 * Finds a matching activity for a preference's intent. If a matching
148 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800149 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800150 * @param context The context.
151 * @param parentPreferenceGroup The preference group that contains the
152 * preference whose intent is being resolved.
153 * @param preferenceKey The key of the preference whose intent is being
154 * resolved.
155 * @param flags 0 or one or more of
156 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
157 * .
158 * @return Whether an activity was found. If false, the preference was
159 * removed.
160 */
161 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
162 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800163
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800164 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
165 if (preference == null) {
166 return false;
167 }
Ying Wanga7188322010-01-04 18:45:10 -0800168
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800169 Intent intent = preference.getIntent();
170 if (intent != null) {
171 // Find the activity that is in the system image
172 PackageManager pm = context.getPackageManager();
173 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
174 int listSize = list.size();
175 for (int i = 0; i < listSize; i++) {
176 ResolveInfo resolveInfo = list.get(i);
177 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
178 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800179
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800180 // Replace the intent with this specific activity
181 preference.setIntent(new Intent().setClassName(
182 resolveInfo.activityInfo.packageName,
183 resolveInfo.activityInfo.name));
184
185 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
186 // Set the preference title to the activity's label
187 preference.setTitle(resolveInfo.loadLabel(pm));
188 }
Ying Wanga7188322010-01-04 18:45:10 -0800189
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800190 return true;
191 }
192 }
193 }
194
195 // Did not find a matching activity, so remove the preference
196 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800197
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900198 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800199 }
Ying Wanga7188322010-01-04 18:45:10 -0800200
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200201 /**
Benjamin Franz194300d2016-01-13 12:16:25 +0000202 * Returns the UserManager for a given context
203 *
204 * @throws IllegalStateException if no UserManager could be retrieved.
205 */
206 public static UserManager getUserManager(Context context) {
207 UserManager um = UserManager.get(context);
208 if (um == null) {
209 throw new IllegalStateException("Unable to load UserManager");
210 }
211 return um;
212 }
213
214 /**
Ying Wanga7188322010-01-04 18:45:10 -0800215 * Returns true if Monkey is running.
216 */
217 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700218 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800219 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700220
221 /**
222 * Returns whether the device is voice-capable (meaning, it is also a phone).
223 */
224 public static boolean isVoiceCapable(Context context) {
225 TelephonyManager telephony =
226 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
227 return telephony != null && telephony.isVoiceCapable();
228 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800229
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700230 public static boolean isWifiOnly(Context context) {
231 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
232 Context.CONNECTIVITY_SERVICE);
233 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800234 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800235
236 /**
237 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
238 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900239 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800240 */
241 public static String getWifiIpAddresses(Context context) {
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700242 WifiManager wifiManager = context.getSystemService(WifiManager.class);
243 Network currentNetwork = wifiManager.getCurrentNetwork();
244 if (currentNetwork != null) {
245 ConnectivityManager cm = (ConnectivityManager)
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800246 context.getSystemService(Context.CONNECTIVITY_SERVICE);
Jaewoong Jungc260e6d2016-10-13 14:21:52 -0700247 LinkProperties prop = cm.getLinkProperties(currentNetwork);
248 return formatIpAddresses(prop);
249 }
250 return null;
Amith Yamasani6822b742011-10-17 16:41:00 -0700251 }
252
253 /**
254 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
255 * addresses.
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900256 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700257 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900258 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700259 LinkProperties prop = cm.getActiveLinkProperties();
260 return formatIpAddresses(prop);
261 }
262
263 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800264 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900265 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800266 // If there are no entries, return null
267 if (!iter.hasNext()) return null;
268 // Concatenate all available addresses, comma separated
269 String addresses = "";
270 while (iter.hasNext()) {
271 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900272 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800273 }
274 return addresses;
275 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900276
277 public static Locale createLocaleFromString(String localeStr) {
278 // TODO: is there a better way to actually construct a locale that will match?
279 // The main problem is, on top of Java specs, locale.toString() and
280 // new Locale(locale.toString()).toString() do not return equal() strings in
281 // many cases, because the constructor takes the only string as the language
282 // code. So : new Locale("en", "US").toString() => "en_US"
283 // And : new Locale("en_US").toString() => "en_us"
284 if (null == localeStr)
285 return Locale.getDefault();
286 String[] brokenDownLocale = localeStr.split("_", 3);
287 // split may not return a 0-length array.
288 if (1 == brokenDownLocale.length) {
289 return new Locale(brokenDownLocale[0]);
290 } else if (2 == brokenDownLocale.length) {
291 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
292 } else {
293 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
294 }
295 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700296
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900297 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
298 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
299 }
300
Amith Yamasania4379d62011-07-22 10:34:58 -0700301 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700302 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700303 }
304
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800305 public static void forcePrepareCustomPreferencesList(
306 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
307 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
308 list.setClipToPadding(false);
309 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
310 }
311
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700312 /**
313 * Prepare a custom preferences layout, moving padding to {@link ListView}
314 * when outside scrollbars are requested. Usually used to display
315 * {@link ListView} and {@link TabWidget} with correct padding.
316 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700317 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800318 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700319 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700320 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700321 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700322 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700323 final int paddingBottom = res.getDimensionPixelSize(
324 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700325
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700326 if (parent instanceof PreferenceFrameLayout) {
327 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
328
329 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
330 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
331 } else {
332 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
333 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700334 }
335 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700336
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700337 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700338 final Resources res = view.getResources();
339 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700340
341 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
342 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700343 final int paddingBottom = res.getDimensionPixelSize(
344 com.android.internal.R.dimen.preference_fragment_padding_bottom);
345
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700346 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700347 }
348
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700349 /* Used by UserSettings as well. Call this on a non-ui thread. */
Sudheer Shanka71caf692016-04-14 16:50:14 -0700350 public static void copyMeProfilePhoto(Context context, UserInfo user) {
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700351 Uri contactUri = Profile.CONTENT_URI;
352
Sudheer Shanka71caf692016-04-14 16:50:14 -0700353 int userId = user != null ? user.id : UserHandle.myUserId();
354
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700355 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
356 context.getContentResolver(),
357 contactUri, true);
358 // If there's no profile photo, assign a default avatar
359 if (avatarDataStream == null) {
Sudheer Shanka71caf692016-04-14 16:50:14 -0700360 assignDefaultPhoto(context, userId);
Sudheer Shanka39975a62016-04-15 17:20:54 -0700361 return;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700362 }
Sudheer Shanka39975a62016-04-15 17:20:54 -0700363
364 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
365 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
366 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700367 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700368 avatarDataStream.close();
369 } catch (IOException ioe) { }
Sudheer Shanka71caf692016-04-14 16:50:14 -0700370 }
371
jackqdyulei8164c642016-12-27 10:15:27 -0800372 /**
373 * Assign the default photo to user with {@paramref userId}
374 * @param context used to get the {@link UserManager}
375 * @param userId used to get the icon bitmap
376 * @return true if assign photo successfully, false if failed
377 */
378 public static boolean assignDefaultPhoto(Context context, int userId) {
379 if (context == null) {
380 return false;
381 }
Sudheer Shanka71caf692016-04-14 16:50:14 -0700382 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
383 Bitmap bitmap = getDefaultUserIconAsBitmap(userId);
384 um.setUserIcon(userId, bitmap);
jackqdyulei8164c642016-12-27 10:15:27 -0800385
386 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700387 }
388
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700389 public static String getMeProfileName(Context context, boolean full) {
390 if (full) {
391 return getProfileDisplayName(context);
392 } else {
393 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700394 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700395 }
396
397 private static String getShorterNameIfPossible(Context context) {
398 final String given = getLocalProfileGivenName(context);
399 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
400 }
401
402 private static String getLocalProfileGivenName(Context context) {
403 final ContentResolver cr = context.getContentResolver();
404
405 // Find the raw contact ID for the local ME profile raw contact.
406 final long localRowProfileId;
407 final Cursor localRawProfile = cr.query(
408 Profile.CONTENT_RAW_CONTACTS_URI,
409 new String[] {RawContacts._ID},
410 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
411 RawContacts.ACCOUNT_NAME + " IS NULL",
412 null, null);
413 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700414
415 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700416 if (!localRawProfile.moveToFirst()) {
417 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700418 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700419 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700420 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700421 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700422 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700423
424 // Find the structured name for the raw contact.
425 final Cursor structuredName = cr.query(
426 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
427 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
428 CommonDataKinds.StructuredName.FAMILY_NAME},
429 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
430 null, null);
431 if (structuredName == null) return null;
432
433 try {
434 if (!structuredName.moveToFirst()) {
435 return null;
436 }
437 String partialName = structuredName.getString(0);
438 if (TextUtils.isEmpty(partialName)) {
439 partialName = structuredName.getString(1);
440 }
441 return partialName;
442 } finally {
443 structuredName.close();
444 }
445 }
446
447 private static final String getProfileDisplayName(Context context) {
448 final ContentResolver cr = context.getContentResolver();
449 final Cursor profile = cr.query(Profile.CONTENT_URI,
450 new String[] {Profile.DISPLAY_NAME}, null, null, null);
451 if (profile == null) return null;
452
453 try {
454 if (!profile.moveToFirst()) {
455 return null;
456 }
457 return profile.getString(0);
458 } finally {
459 profile.close();
460 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700461 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700462
463 /** Not global warming, it's global change warning. */
464 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
465 final Runnable positiveAction) {
466 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
467 builder.setTitle(titleResId);
468 builder.setMessage(R.string.global_change_warning);
469 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
470 @Override
471 public void onClick(DialogInterface dialog, int which) {
472 positiveAction.run();
473 }
474 });
475 builder.setNegativeButton(android.R.string.cancel, null);
476
477 return builder.create();
478 }
479
480 public static boolean hasMultipleUsers(Context context) {
481 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
482 .getUsers().size() > 1;
483 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700484
485 /**
486 * Start a new instance of the activity, showing only the given fragment.
487 * When launched in this mode, the given preference fragment will be instantiated and fill the
488 * entire activity.
489 *
490 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000491 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700492 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700493 * @param resultTo Option fragment that should receive the result of the activity launch.
494 * @param resultRequestCode If resultTo is non-null, this is the request code in which
495 * to report the result.
496 * @param titleResId resource id for the String to display for the title of this set
497 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700498 * @param title String to display for the title of this set of preferences.
Fan Zhangc6ca3142017-02-14 15:02:35 -0800499 * @param metricsCategory The current metricsCategory for logging source when fragment starts
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700500 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000501 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100502 Fragment resultTo, int resultRequestCode, int titleResId,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800503 CharSequence title, int metricsCategory) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700504 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800505 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */,
506 metricsCategory);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100507 }
508
509 /**
510 * Start a new instance of the activity, showing only the given fragment.
511 * When launched in this mode, the given preference fragment will be instantiated and fill the
512 * entire activity.
513 *
514 * @param context The context.
515 * @param fragmentName The name of the fragment to display.
516 * @param args Optional arguments to supply to the fragment.
517 * @param resultTo Option fragment that should receive the result of the activity launch.
518 * @param resultRequestCode If resultTo is non-null, this is the request code in which
519 * to report the result.
520 * @param titleResPackageName Optional package name for the resource id of the title.
521 * @param titleResId resource id for the String to display for the title of this set
522 * of preferences.
523 * @param title String to display for the title of this set of preferences.
Fan Zhangc6ca3142017-02-14 15:02:35 -0800524 * @param metricsCategory The current metricsCategory for logging source when fragment starts
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100525 */
526 public static void startWithFragment(Context context, String fragmentName, Bundle args,
527 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800528 CharSequence title, int metricsCategory) {
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100529 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800530 titleResPackageName, titleResId, title, false /* not a shortcut */,
531 metricsCategory);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700532 }
533
534 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100535 Fragment resultTo, int resultRequestCode, int titleResId,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800536 CharSequence title, boolean isShortcut, int metricsCategory) {
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100537 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800538 null /* titleResPackageName */, titleResId, title, isShortcut, metricsCategory);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100539 if (resultTo == null) {
540 context.startActivity(intent);
541 } else {
Doris Ling36e953f2016-08-12 15:25:00 -0700542 resultTo.getActivity().startActivityForResult(intent, resultRequestCode);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100543 }
544 }
545
546 public static void startWithFragment(Context context, String fragmentName, Bundle args,
547 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800548 CharSequence title, boolean isShortcut, int metricsCategory) {
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100549 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800550 titleResId, title, isShortcut, metricsCategory);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700551 if (resultTo == null) {
552 context.startActivity(intent);
553 } else {
554 resultTo.startActivityForResult(intent, resultRequestCode);
555 }
556 }
557
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100558 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800559 int titleResId, CharSequence title, boolean isShortcut, int metricsCategory,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100560 UserHandle userHandle) {
Victor Chang16da2aa2016-03-11 19:44:56 +0000561 // workaround to avoid crash in b/17523189
562 if (userHandle.getIdentifier() == UserHandle.myUserId()) {
Fan Zhangc6ca3142017-02-14 15:02:35 -0800563 startWithFragment(context, fragmentName, args, null, 0, titleResId, title, isShortcut,
564 metricsCategory);
Victor Chang16da2aa2016-03-11 19:44:56 +0000565 } else {
566 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800567 null /* titleResPackageName */, titleResId, title, isShortcut, metricsCategory);
Victor Chang16da2aa2016-03-11 19:44:56 +0000568 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
569 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
570 context.startActivityAsUser(intent, userHandle);
571 }
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100572 }
573
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700574 /**
575 * Build an Intent to launch a new activity showing the selected fragment.
576 * The implementation constructs an Intent that re-launches the current activity with the
577 * appropriate arguments to display the fragment.
578 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700579 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700580 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000581 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700582 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100583 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700584 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700585 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700586 * @param isShortcut tell if this is a Launcher Shortcut or not
Fan Zhangc6ca3142017-02-14 15:02:35 -0800587 * @param sourceMetricsCategory The context (source) from which an action is performed
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700588 * @return Returns an Intent that can be launched to display the given
589 * fragment.
590 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000591 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100592 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
Fan Zhangc6ca3142017-02-14 15:02:35 -0800593 boolean isShortcut, int sourceMetricsCategory) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700594 Intent intent = new Intent(Intent.ACTION_MAIN);
595 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000596 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700597 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100598 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
599 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700600 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700601 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700602 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fan Zhangc6ca3142017-02-14 15:02:35 -0800603 intent.putExtra(SettingsActivity.EXTRA_SOURCE_METRICS_CATEGORY, sourceMetricsCategory);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700604 return intent;
605 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100606
607 /**
608 * Returns the managed profile of the current user or null if none found.
609 */
610 public static UserHandle getManagedProfile(UserManager userManager) {
611 List<UserHandle> userProfiles = userManager.getUserProfiles();
612 final int count = userProfiles.size();
613 for (int i = 0; i < count; i++) {
614 final UserHandle profile = userProfiles.get(i);
615 if (profile.getIdentifier() == userManager.getUserHandle()) {
616 continue;
617 }
618 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
619 if (userInfo.isManagedProfile()) {
620 return profile;
621 }
622 }
623 return null;
624 }
625
626 /**
Clara Bayarri462cce12016-02-18 12:09:21 +0000627 * Retrieves the id for the given user's managed profile.
628 *
629 * @return the managed profile id or UserHandle.USER_NULL if there is none.
630 */
631 public static int getManagedProfileId(UserManager um, int parentUserId) {
Fyodor Kupolov4a4af5a2016-04-07 16:46:18 -0700632 int[] profileIds = um.getProfileIdsWithDisabled(parentUserId);
633 for (int profileId : profileIds) {
634 if (profileId != parentUserId) {
635 return profileId;
Clara Bayarri462cce12016-02-18 12:09:21 +0000636 }
637 }
638 return UserHandle.USER_NULL;
639 }
640
641 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100642 * Returns the target user for a Settings activity.
Tony Mak8f41b9b2016-11-23 11:36:18 +0000643 * <p>
644 * User would be retrieved in this order:
645 * <ul>
646 * <li> If this activity is launched from other user, return that user id.
647 * <li> If this is launched from the Settings app in same user, return the user contained as an
648 * extra in the arguments or intent extras.
649 * <li> Otherwise, return UserHandle.myUserId().
650 * </ul>
651 * <p>
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100652 * Note: This is secure in the sense that it only returns a target user different to the current
653 * one if the app launching this activity is the Settings app itself, running in the same user
654 * 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 +0100655 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100656 public static UserHandle getSecureTargetUser(IBinder activityToken,
Tony Mak8f41b9b2016-11-23 11:36:18 +0000657 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100658 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800659 IActivityManager am = ActivityManager.getService();
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100660 try {
661 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
662 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
663
664 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
665 am.getLaunchedFromUid(activityToken)));
666 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
667 // Check it's secure
668 if (isProfileOf(um, launchedFromUser)) {
669 return launchedFromUser;
670 }
671 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000672 UserHandle extrasUser = getUserHandleFromBundle(intentExtras);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100673 if (extrasUser != null && !extrasUser.equals(currentUser)) {
674 // Check it's secure
675 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
676 return extrasUser;
677 }
678 }
Tony Mak8f41b9b2016-11-23 11:36:18 +0000679 UserHandle argumentsUser = getUserHandleFromBundle(arguments);
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100680 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
681 // Check it's secure
682 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
683 return argumentsUser;
684 }
685 }
686 } catch (RemoteException e) {
687 // Should not happen
688 Log.v(TAG, "Could not talk to activity manager.", e);
689 }
690 return currentUser;
Tony Mak8f41b9b2016-11-23 11:36:18 +0000691 }
692
693 /**
694 * Lookup both {@link Intent#EXTRA_USER} and {@link Intent#EXTRA_USER_ID} in the bundle
695 * and return the {@link UserHandle} object. Return {@code null} if nothing is found.
696 */
697 private static @Nullable UserHandle getUserHandleFromBundle(Bundle bundle) {
698 if (bundle == null) {
699 return null;
700 }
701 final UserHandle user = bundle.getParcelable(EXTRA_USER);
702 if (user != null) {
703 return user;
704 }
705 final int userId = bundle.getInt(EXTRA_USER_ID, -1);
706 if (userId != -1) {
707 return UserHandle.of(userId);
708 }
709 return null;
710 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100711
712 /**
713 * Returns the target user for a Settings activity.
714 *
715 * The target user can be either the current user, the user that launched this activity or
716 * the user contained as an extra in the arguments or intent extras.
717 *
718 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
719 * possible.
720 *
721 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
722 */
723 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
724 @Nullable Bundle intentExtras) {
725 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
Sudheer Shankaacb1a612016-11-10 15:30:14 -0800726 IActivityManager am = ActivityManager.getService();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100727 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100728 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
729 am.getLaunchedFromUid(activityToken)));
730 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
731 return launchedFromUser;
732 }
733 UserHandle extrasUser = intentExtras != null
734 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
735 if (extrasUser != null && !extrasUser.equals(currentUser)) {
736 return extrasUser;
737 }
738 UserHandle argumentsUser = arguments != null
739 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
740 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
741 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100742 }
743 } catch (RemoteException e) {
744 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100745 Log.v(TAG, "Could not talk to activity manager.", e);
746 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100747 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100748 return currentUser;
749 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100750
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100751 /**
752 * Returns true if the user provided is in the same profiles group as the current user.
753 */
754 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
755 if (um == null || otherUser == null) return false;
756 return (UserHandle.myUserId() == otherUser.getIdentifier())
757 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100758 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530759
Andres Moralesce249fe2014-07-07 16:58:16 -0700760
761 /**
762 * Returns whether or not this device is able to be OEM unlocked.
763 */
764 static boolean isOemUnlockEnabled(Context context) {
765 PersistentDataBlockManager manager =(PersistentDataBlockManager)
766 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
767 return manager.getOemUnlockEnabled();
768 }
769
770 /**
771 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
772 * devices allow users to flash other OSes to them.
773 */
774 static void setOemUnlockEnabled(Context context, boolean enabled) {
Steven Ng3fe14032016-04-27 15:28:40 +0100775 try {
776 PersistentDataBlockManager manager = (PersistentDataBlockManager)
777 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
778 manager.setOemUnlockEnabled(enabled);
779 } catch (SecurityException e) {
780 Log.e(TAG, "Fail to set oem unlock.", e);
781 }
Andres Moralesce249fe2014-07-07 16:58:16 -0700782 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100783
784 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700785 * Return whether or not the user should have a SIM Cards option in Settings.
786 * TODO: Change back to returning true if count is greater than one after testing.
787 * TODO: See bug 16533525.
788 */
789 public static boolean showSimCardTile(Context context) {
790 final TelephonyManager tm =
791 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
792
PauloftheWestdbd03822014-12-04 11:56:35 -0800793 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700794 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200795
796 /**
Elliott Hughes7253df32014-09-02 17:10:14 -0700797 * Returns elapsed time for the given millis, in the following format:
798 * 2d 5h 40m 29s
799 * @param context the application context
800 * @param millis the elapsed time in milli seconds
801 * @param withSeconds include seconds?
802 * @return the formatted elapsed time
803 */
804 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
805 StringBuilder sb = new StringBuilder();
806 int seconds = (int) Math.floor(millis / 1000);
807 if (!withSeconds) {
808 // Round up.
809 seconds += 30;
810 }
811
812 int days = 0, hours = 0, minutes = 0;
813 if (seconds >= SECONDS_PER_DAY) {
814 days = seconds / SECONDS_PER_DAY;
815 seconds -= days * SECONDS_PER_DAY;
816 }
817 if (seconds >= SECONDS_PER_HOUR) {
818 hours = seconds / SECONDS_PER_HOUR;
819 seconds -= hours * SECONDS_PER_HOUR;
820 }
821 if (seconds >= SECONDS_PER_MINUTE) {
822 minutes = seconds / SECONDS_PER_MINUTE;
823 seconds -= minutes * SECONDS_PER_MINUTE;
824 }
825 if (withSeconds) {
826 if (days > 0) {
827 sb.append(context.getString(R.string.battery_history_days,
828 days, hours, minutes, seconds));
829 } else if (hours > 0) {
830 sb.append(context.getString(R.string.battery_history_hours,
831 hours, minutes, seconds));
832 } else if (minutes > 0) {
833 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
834 } else {
835 sb.append(context.getString(R.string.battery_history_seconds, seconds));
836 }
837 } else {
838 if (days > 0) {
839 sb.append(context.getString(R.string.battery_history_days_no_seconds,
840 days, hours, minutes));
841 } else if (hours > 0) {
842 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
843 hours, minutes));
844 } else {
845 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
846 }
847 }
848 return sb.toString();
849 }
PauloftheWest0a0daca2014-11-06 15:02:58 -0800850
851 /**
Amith Yamasani45f86232014-11-19 17:12:46 -0800852 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
853 * @param userManager Instance of UserManager
854 * @param checkUser The user to check the existence of.
855 * @return UserInfo of the user or null for non-existent user.
856 */
857 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
858 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
859 final int checkUserId = checkUser.getIdentifier();
860 for (UserInfo user : users) {
861 if (user.id == checkUserId) {
862 return user;
863 }
864 }
865 return null;
866 }
867
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +0000868 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
869 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
870 com.android.internal.R.styleable.Preference,
871 com.android.internal.R.attr.preferenceCategoryStyle, 0);
872 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
873 0);
874 a.recycle();
875 return inflater.inflate(resId, parent, false);
876 }
877
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -0800878 /**
879 * Return if we are running low on storage space or not.
880 *
881 * @param context The context
882 * @return true if we are running low on storage space
883 */
884 public static boolean isLowStorage(Context context) {
885 final StorageManager sm = StorageManager.from(context);
886 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
887 }
888
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000889 /**
890 * Returns a default user icon (as a {@link Bitmap}) for the given user.
891 *
892 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
893 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
894 */
895 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
896 Bitmap bitmap = null;
897 // Try finding the corresponding bitmap in the dark bitmap cache
898 bitmap = sDarkDefaultUserBitmapCache.get(userId);
899 if (bitmap == null) {
900 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
901 // Save it to cache
902 sDarkDefaultUserBitmapCache.put(userId, bitmap);
903 }
904 return bitmap;
905 }
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800906
Fabrice Di Meglio8b2ea392015-01-23 19:03:22 -0800907 public static boolean hasPreferredActivities(PackageManager pm, String packageName) {
908 // Get list of preferred activities
909 List<ComponentName> prefActList = new ArrayList<>();
910 // Intent list cannot be null. so pass empty list
911 List<IntentFilter> intentList = new ArrayList<>();
912 pm.getPreferredActivities(intentList, prefActList, packageName);
913 Log.d(TAG, "Have " + prefActList.size() + " number of activities in preferred list");
914 return prefActList.size() > 0;
915 }
916
Christopher Tatea08a2252015-07-01 16:52:43 -0700917 public static ArraySet<String> getHandledDomains(PackageManager pm, String packageName) {
918 List<IntentFilterVerificationInfo> iviList = pm.getIntentFilterVerifications(packageName);
919 List<IntentFilter> filters = pm.getAllIntentFilters(packageName);
920
921 ArraySet<String> result = new ArraySet<>();
922 if (iviList.size() > 0) {
923 for (IntentFilterVerificationInfo ivi : iviList) {
924 for (String host : ivi.getDomains()) {
925 result.add(host);
926 }
927 }
928 }
929 if (filters != null && filters.size() > 0) {
930 for (IntentFilter filter : filters) {
Christopher Tateddaa1422015-07-16 16:00:49 -0700931 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE)
932 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
933 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
Christopher Tatea08a2252015-07-01 16:52:43 -0700934 result.addAll(filter.getHostsList());
935 }
936 }
937 }
938 return result;
939 }
940
Jason Monkb5aa73f2015-03-31 12:59:33 -0400941 public static void handleLoadingContainer(View loading, View doneLoading, boolean done,
942 boolean animate) {
943 setViewShown(loading, !done, animate);
944 setViewShown(doneLoading, done, animate);
945 }
946
947 private static void setViewShown(final View view, boolean shown, boolean animate) {
948 if (animate) {
949 Animation animation = AnimationUtils.loadAnimation(view.getContext(),
950 shown ? android.R.anim.fade_in : android.R.anim.fade_out);
951 if (shown) {
952 view.setVisibility(View.VISIBLE);
953 } else {
954 animation.setAnimationListener(new AnimationListener() {
955 @Override
956 public void onAnimationStart(Animation animation) {
957 }
958
959 @Override
960 public void onAnimationRepeat(Animation animation) {
961 }
962
963 @Override
964 public void onAnimationEnd(Animation animation) {
965 view.setVisibility(View.INVISIBLE);
966 }
967 });
968 }
969 view.startAnimation(animation);
970 } else {
971 view.clearAnimation();
972 view.setVisibility(shown ? View.VISIBLE : View.INVISIBLE);
973 }
974 }
Sudheer Shankabc956302015-04-09 12:19:53 +0100975
976 /**
977 * Returns the application info of the currently installed MDM package.
978 */
979 public static ApplicationInfo getAdminApplicationInfo(Context context, int profileId) {
980 DevicePolicyManager dpm =
981 (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
982 ComponentName mdmPackage = dpm.getProfileOwnerAsUser(profileId);
983 if (mdmPackage == null) {
984 return null;
985 }
986 String mdmPackageName = mdmPackage.getPackageName();
987 try {
988 IPackageManager ipm = AppGlobals.getPackageManager();
989 ApplicationInfo mdmApplicationInfo =
990 ipm.getApplicationInfo(mdmPackageName, 0, profileId);
991 return mdmApplicationInfo;
992 } catch (RemoteException e) {
993 Log.e(TAG, "Error while retrieving application info for package " + mdmPackageName
994 + ", userId " + profileId, e);
995 return null;
996 }
997 }
Jason Monkb45e27b2015-05-20 13:35:43 -0400998
999 public static boolean isBandwidthControlEnabled() {
1000 final INetworkManagementService netManager = INetworkManagementService.Stub
1001 .asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
1002 try {
1003 return netManager.isBandwidthControlEnabled();
1004 } catch (RemoteException e) {
1005 return false;
1006 }
1007 }
Julia Reynoldsce25af42015-07-08 16:56:31 -04001008
1009 /**
1010 * Returns an accessible SpannableString.
1011 * @param displayText the text to display
1012 * @param accessibileText the text text-to-speech engines should read
1013 */
1014 public static SpannableString createAccessibleSequence(CharSequence displayText,
1015 String accessibileText) {
1016 SpannableString str = new SpannableString(displayText);
1017 str.setSpan(new TtsSpan.TextBuilder(accessibileText).build(), 0,
1018 displayText.length(),
1019 Spannable.SPAN_INCLUSIVE_INCLUSIVE);
1020 return str;
1021 }
Andres Morales7bdffd82015-08-04 16:55:00 -07001022
Clara Bayarrife432e82015-10-12 12:07:02 +01001023 /**
Benjamin Franz194300d2016-01-13 12:16:25 +00001024 * Returns the user id present in the bundle with {@link Intent#EXTRA_USER_ID} if it
Clara Bayarrife432e82015-10-12 12:07:02 +01001025 * belongs to the current user.
1026 *
1027 * @throws SecurityException if the given userId does not belong to the current user group.
1028 */
Benjamin Franz194300d2016-01-13 12:16:25 +00001029 public static int getUserIdFromBundle(Context context, Bundle bundle) {
Clara Bayarrife432e82015-10-12 12:07:02 +01001030 if (bundle == null) {
Benjamin Franz194300d2016-01-13 12:16:25 +00001031 return getCredentialOwnerUserId(context);
Clara Bayarrife432e82015-10-12 12:07:02 +01001032 }
Clara Bayarri6934a042015-10-14 11:07:35 +01001033 int userId = bundle.getInt(Intent.EXTRA_USER_ID, UserHandle.myUserId());
Benjamin Franz194300d2016-01-13 12:16:25 +00001034 return enforceSameOwner(context, userId);
Clara Bayarrife432e82015-10-12 12:07:02 +01001035 }
1036
1037 /**
1038 * Returns the given user id if it belongs to the current user.
1039 *
1040 * @throws SecurityException if the given userId does not belong to the current user group.
1041 */
Benjamin Franz194300d2016-01-13 12:16:25 +00001042 public static int enforceSameOwner(Context context, int userId) {
Ricky Wai72500162016-06-07 16:54:25 +01001043 final UserManager um = getUserManager(context);
1044 final int[] profileIds = um.getProfileIdsWithDisabled(UserHandle.myUserId());
1045 if (ArrayUtils.contains(profileIds, userId)) {
1046 return userId;
Clara Bayarrife432e82015-10-12 12:07:02 +01001047 }
Ricky Wai72500162016-06-07 16:54:25 +01001048 throw new SecurityException("Given user id " + userId + " does not belong to user "
1049 + UserHandle.myUserId());
Clara Bayarrife432e82015-10-12 12:07:02 +01001050 }
1051
Benjamin Franz194300d2016-01-13 12:16:25 +00001052 /**
1053 * Returns the effective credential owner of the calling user.
1054 */
1055 public static int getCredentialOwnerUserId(Context context) {
1056 return getCredentialOwnerUserId(context, UserHandle.myUserId());
1057 }
1058
1059 /**
1060 * Returns the user id of the credential owner of the given user id.
1061 */
1062 public static int getCredentialOwnerUserId(Context context, int userId) {
1063 UserManager um = getUserManager(context);
1064 return um.getCredentialOwnerProfile(userId);
Andres Morales7bdffd82015-08-04 16:55:00 -07001065 }
Jason Monkdb4ed192015-12-11 16:48:31 -05001066
1067 public static int resolveResource(Context context, int attr) {
1068 TypedValue value = new TypedValue();
1069 context.getTheme().resolveAttribute(attr, value, true);
1070 return value.resourceId;
1071 }
Jason Monkb37e2882016-01-11 14:27:20 -05001072
1073 private static final StringBuilder sBuilder = new StringBuilder(50);
1074 private static final java.util.Formatter sFormatter = new java.util.Formatter(
1075 sBuilder, Locale.getDefault());
1076
1077 public static String formatDateRange(Context context, long start, long end) {
1078 final int flags = FORMAT_SHOW_DATE | FORMAT_ABBREV_MONTH;
1079
1080 synchronized (sBuilder) {
1081 sBuilder.setLength(0);
1082 return DateUtils.formatDateRange(context, sFormatter, start, end, flags, null)
1083 .toString();
1084 }
1085 }
Jason Monk91e2f892016-02-23 15:31:09 -05001086
1087 public static List<String> getNonIndexable(int xml, Context context) {
Jason Monkbe941212016-05-27 12:58:53 -04001088 if (Looper.myLooper() == null) {
1089 // Hack to make sure Preferences can initialize. Prefs expect a looper, but
1090 // don't actually use it for the basic stuff here.
1091 Looper.prepare();
1092 }
Jason Monk9ee80cd2016-03-03 11:21:42 -05001093 final List<String> ret = new ArrayList<>();
Jason Monkbe941212016-05-27 12:58:53 -04001094 PreferenceManager manager = new PreferenceManager(context);
1095 PreferenceScreen screen = manager.inflateFromResource(context, xml, null);
1096 checkPrefs(screen, ret);
Jason Monk91e2f892016-02-23 15:31:09 -05001097
1098 return ret;
1099 }
1100
1101 private static void checkPrefs(PreferenceGroup group, List<String> ret) {
1102 if (group == null) return;
1103 for (int i = 0; i < group.getPreferenceCount(); i++) {
1104 Preference pref = group.getPreference(i);
1105 if (pref instanceof SelfAvailablePreference
1106 && !((SelfAvailablePreference) pref).isAvailable(group.getContext())) {
1107 ret.add(pref.getKey());
1108 if (pref instanceof PreferenceGroup) {
1109 addAll((PreferenceGroup) pref, ret);
1110 }
1111 } else if (pref instanceof PreferenceGroup) {
1112 checkPrefs((PreferenceGroup) pref, ret);
1113 }
1114 }
1115 }
1116
1117 private static void addAll(PreferenceGroup group, List<String> ret) {
1118 if (group == null) return;
1119 for (int i = 0; i < group.getPreferenceCount(); i++) {
1120 Preference pref = group.getPreference(i);
1121 ret.add(pref.getKey());
1122 if (pref instanceof PreferenceGroup) {
1123 addAll((PreferenceGroup) pref, ret);
1124 }
1125 }
1126 }
Udam Saini679f7ad2016-03-25 10:47:00 -07001127
1128 public static boolean isDeviceProvisioned(Context context) {
1129 return Settings.Global.getInt(context.getContentResolver(),
1130 Settings.Global.DEVICE_PROVISIONED, 0) != 0;
1131 }
Ricky Wai616342b2016-04-13 10:40:22 +01001132
Bernard Chau88d523b2016-04-14 15:08:28 +01001133 public static boolean startQuietModeDialogIfNecessary(Context context, UserManager um,
Ricky Wai616342b2016-04-13 10:40:22 +01001134 int userId) {
1135 if (um.isQuietModeEnabled(UserHandle.of(userId))) {
1136 final Intent intent = UnlaunchableAppActivity.createInQuietModeDialogIntent(userId);
1137 context.startActivity(intent);
1138 return true;
1139 }
1140 return false;
1141 }
Sudheer Shankac3eb16e2016-04-21 12:51:43 -07001142
Rubin Xu3231afe2016-08-24 10:15:07 +01001143 public static boolean unlockWorkProfileIfNecessary(Context context, int userId) {
1144 try {
Sudheer Shankaacb1a612016-11-10 15:30:14 -08001145 if (!ActivityManager.getService().isUserRunning(userId,
Rubin Xu3231afe2016-08-24 10:15:07 +01001146 ActivityManager.FLAG_AND_LOCKED)) {
1147 return false;
1148 }
1149 } catch (RemoteException e) {
1150 return false;
1151 }
1152 if (!(new LockPatternUtils(context)).isSecure(userId)) {
1153 return false;
1154 }
Robin Leecccf3242017-02-10 15:32:49 +00001155 return confirmWorkProfileCredentials(context, userId);
1156 }
1157
1158 public static boolean confirmWorkProfileCredentialsIfNecessary(Context context, int userId) {
1159 KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
1160 if (!km.isDeviceLocked(userId)) {
1161 return false;
1162 }
1163 return confirmWorkProfileCredentials(context, userId);
1164 }
1165
1166 private static boolean confirmWorkProfileCredentials(Context context, int userId) {
Rubin Xu3231afe2016-08-24 10:15:07 +01001167 final KeyguardManager km = (KeyguardManager) context.getSystemService(
1168 Context.KEYGUARD_SERVICE);
1169 final Intent unlockIntent = km.createConfirmDeviceCredentialIntent(null, null, userId);
1170 if (unlockIntent != null) {
1171 context.startActivity(unlockIntent);
1172 return true;
1173 } else {
1174 return false;
1175 }
Rubin Xu3231afe2016-08-24 10:15:07 +01001176 }
1177
Sudheer Shankac3eb16e2016-04-21 12:51:43 -07001178 public static CharSequence getApplicationLabel(Context context, String packageName) {
1179 try {
1180 final ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
1181 packageName,
1182 PackageManager.MATCH_DISABLED_COMPONENTS
Amith Yamasani21556cd2016-11-01 15:49:21 -07001183 | PackageManager.MATCH_ANY_USER);
Sudheer Shankac3eb16e2016-04-21 12:51:43 -07001184 return appInfo.loadLabel(context.getPackageManager());
1185 } catch (PackageManager.NameNotFoundException e) {
1186 Log.w(TAG, "Unable to find info for package: " + packageName);
1187 }
1188 return null;
1189 }
Jason Monk75199542016-05-06 15:09:32 -04001190
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001191 public static boolean isPackageDirectBootAware(Context context, String packageName) {
1192 try {
1193 final ApplicationInfo ai = context.getPackageManager().getApplicationInfo(
1194 packageName, 0);
1195 return ai.isDirectBootAware() || ai.isPartiallyDirectBootAware();
1196 } catch (NameNotFoundException ignored) {
1197 }
1198 return false;
1199 }
Andre Lago3e398c82016-07-25 14:12:28 +01001200
1201 /**
1202 * Returns a context created from the given context for the given user, or null if it fails
1203 */
1204 public static Context createPackageContextAsUser(Context context, int userId) {
1205 try {
1206 return context.createPackageContextAsUser(
1207 context.getPackageName(), 0 /* flags */, UserHandle.of(userId));
1208 } catch (PackageManager.NameNotFoundException e) {
1209 Log.e(TAG, "Failed to create user context", e);
1210 }
1211 return null;
1212 }
Jeff Sharkeyab508072016-10-11 14:25:22 -06001213
1214 public static FingerprintManager getFingerprintManagerOrNull(Context context) {
1215 if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {
1216 return context.getSystemService(FingerprintManager.class);
1217 } else {
1218 return null;
1219 }
1220 }
Daniel Nishi31027da2017-01-19 14:03:57 -08001221
1222 /**
1223 * Launches an intent which may optionally have a user id defined.
1224 * @param fragment Fragment to use to launch the activity.
1225 * @param intent Intent to launch.
1226 */
1227 public static void launchIntent(Fragment fragment, Intent intent) {
1228 try {
1229 final int userId = intent.getIntExtra(Intent.EXTRA_USER_ID, -1);
1230
1231 if (userId == -1) {
1232 fragment.startActivity(intent);
1233 } else {
1234 fragment.getActivity().startActivityAsUser(intent, new UserHandle(userId));
1235 }
1236 } catch (ActivityNotFoundException e) {
1237 Log.w(TAG, "No activity found for " + intent);
1238 }
1239 }
1240
Christine Franks14782222017-01-23 16:44:02 -08001241 public static boolean isCarrierDemoUser(Context context) {
1242 final String carrierDemoModeSetting =
1243 context.getString(com.android.internal.R.string.config_carrierDemoModeSetting);
1244 return UserManager.isDeviceInDemoMode(context)
1245 && getUserManager(context).isDemoUser()
1246 && !TextUtils.isEmpty(carrierDemoModeSetting)
1247 && (Settings.Secure.getInt(context.getContentResolver(),
1248 carrierDemoModeSetting, 0) == 1);
1249 }
Daniel Nishidfed8a22017-01-19 16:32:41 -08001250
1251 /**
1252 * Returns if a given user is a profile of another user.
1253 * @param user The user whose profiles will be checked.
1254 * @param profile The (potential) profile.
1255 * @return if the profile is actually a profile
1256 */
1257 public static boolean isProfileOf(UserInfo user, UserInfo profile) {
1258 return user.id == profile.id ||
1259 (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID
1260 && user.profileGroupId == profile.profileGroupId);
1261 }
Daniel Nishi9f60f422017-02-15 15:25:48 -08001262
1263 /**
1264 * Tries to initalize a volume with the given bundle. If it is a valid, private, and readable
1265 * {@link VolumeInfo}, it is returned. If it is not valid, null is returned.
1266 */
1267 @Nullable
1268 public static VolumeInfo maybeInitializeVolume(StorageManager sm, Bundle bundle) {
1269 final String volumeId = bundle.getString(VolumeInfo.EXTRA_VOLUME_ID,
1270 VolumeInfo.ID_PRIVATE_INTERNAL);
1271 VolumeInfo volume = sm.findVolumeById(volumeId);
1272 return isVolumeValid(volume) ? volume : null;
1273 }
1274
1275 private static boolean isVolumeValid(VolumeInfo volume) {
1276 return (volume != null) && (volume.getType() == VolumeInfo.TYPE_PRIVATE)
1277 && volume.isMountedReadable();
1278 }
Jeff Sharkey4a8136b2016-07-27 12:53:34 -06001279}