blob: 16037c55e4d7985e988f5d4623050379be842917 [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
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010019import static android.content.Intent.EXTRA_USER;
20
21import android.annotation.Nullable;
Amith Yamasaniae697552011-09-27 11:33:17 -070022import android.app.ActivityManager;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010023import android.app.ActivityManagerNative;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070024import android.app.AlertDialog;
25import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070026import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010027import android.app.IActivityManager;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070028import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080029import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070030import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080031import android.content.Intent;
32import android.content.pm.ApplicationInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020033import android.content.pm.PackageInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080034import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070035import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070036import android.content.pm.ResolveInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020037import android.content.pm.Signature;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070038import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020039import android.content.res.Resources;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000040import android.content.res.TypedArray;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020041import android.content.res.Resources.NotFoundException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070042import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070043import android.graphics.Bitmap;
44import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020045import android.graphics.drawable.Drawable;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080046import android.net.ConnectivityManager;
47import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070048import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070049import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020050import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010051import android.os.IBinder;
52import android.os.RemoteException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070053import android.os.UserHandle;
54import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080055import android.os.storage.StorageManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080056import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070057import android.preference.PreferenceFrameLayout;
58import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070059import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070060import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070061import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070062import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070063import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070064import android.service.persistentdata.PersistentDataBlockManager;
Wink Savilleca756612014-11-08 10:47:12 -080065import android.telephony.SubscriptionInfo;
PauloftheWest0a0daca2014-11-06 15:02:58 -080066import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070067import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020068import android.text.TextUtils;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010069import android.util.Log;
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +000070import android.util.SparseArray;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000071import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070072import android.view.View;
73import android.view.ViewGroup;
74import android.widget.ListView;
75import android.widget.TabWidget;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010076
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010077import com.android.internal.util.UserIcons;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010078import com.android.settings.UserSpinnerAdapter.UserDetails;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070079import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010080import com.android.settings.drawable.CircleFramedDrawable;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070081
Amith Yamasaniae47ef42012-09-16 17:53:35 -070082import java.io.IOException;
83import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080084import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070085import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010086import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080087import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070088import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090089import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080090
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070091public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010092 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010093
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080094 /**
95 * Set the preference's title to the matching activity's label.
96 */
97 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
98
99 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +0900100 * The opacity level of a disabled icon.
101 */
102 public static final float DISABLED_ALPHA = 0.4f;
103
104 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700105 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
106 * 1 is most bad (red), the last value is least bad (green).
107 */
108 public static final int[] BADNESS_COLORS = new int[] {
109 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
110 0xfffabf2c, 0xff679e37, 0xff0a7f42
111 };
112
113 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200114 * Name of the meta-data item that should be set in the AndroidManifest.xml
115 * to specify the icon that should be displayed for the preference.
116 */
117 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
118
119 /**
120 * Name of the meta-data item that should be set in the AndroidManifest.xml
121 * to specify the title that should be displayed for the preference.
122 */
123 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
124
125 /**
126 * Name of the meta-data item that should be set in the AndroidManifest.xml
127 * to specify the summary text that should be displayed for the preference.
128 */
129 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
130
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100131 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
132
Elliott Hughes7253df32014-09-02 17:10:14 -0700133 private static final int SECONDS_PER_MINUTE = 60;
134 private static final int SECONDS_PER_HOUR = 60 * 60;
135 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
136
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +0000137 private static SparseArray<Bitmap> sDarkDefaultUserBitmapCache = new SparseArray<Bitmap>();
138
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200139 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800140 * Finds a matching activity for a preference's intent. If a matching
141 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800142 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800143 * @param context The context.
144 * @param parentPreferenceGroup The preference group that contains the
145 * preference whose intent is being resolved.
146 * @param preferenceKey The key of the preference whose intent is being
147 * resolved.
148 * @param flags 0 or one or more of
149 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
150 * .
151 * @return Whether an activity was found. If false, the preference was
152 * removed.
153 */
154 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
155 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800156
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800157 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
158 if (preference == null) {
159 return false;
160 }
Ying Wanga7188322010-01-04 18:45:10 -0800161
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800162 Intent intent = preference.getIntent();
163 if (intent != null) {
164 // Find the activity that is in the system image
165 PackageManager pm = context.getPackageManager();
166 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
167 int listSize = list.size();
168 for (int i = 0; i < listSize; i++) {
169 ResolveInfo resolveInfo = list.get(i);
170 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
171 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800172
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800173 // Replace the intent with this specific activity
174 preference.setIntent(new Intent().setClassName(
175 resolveInfo.activityInfo.packageName,
176 resolveInfo.activityInfo.name));
177
178 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
179 // Set the preference title to the activity's label
180 preference.setTitle(resolveInfo.loadLabel(pm));
181 }
Ying Wanga7188322010-01-04 18:45:10 -0800182
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800183 return true;
184 }
185 }
186 }
187
188 // Did not find a matching activity, so remove the preference
189 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800190
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900191 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800192 }
Ying Wanga7188322010-01-04 18:45:10 -0800193
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700194 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700195 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700196
197 Intent intent = tile.intent;
198 if (intent != null) {
199 // Find the activity that is in the system image
200 PackageManager pm = context.getPackageManager();
201 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
202 int listSize = list.size();
203 for (int i = 0; i < listSize; i++) {
204 ResolveInfo resolveInfo = list.get(i);
205 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
206 != 0) {
207 Drawable icon = null;
208 String title = null;
209 String summary = null;
210
211 // Get the activity's meta-data
212 try {
213 Resources res = pm.getResourcesForApplication(
214 resolveInfo.activityInfo.packageName);
215 Bundle metaData = resolveInfo.activityInfo.metaData;
216
217 if (res != null && metaData != null) {
Alan Viverette0ba89bd2014-10-10 10:58:58 -0700218 icon = res.getDrawable(
219 metaData.getInt(META_DATA_PREFERENCE_ICON), null);
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700220 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
221 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
222 }
223 } catch (NameNotFoundException e) {
224 // Ignore
225 } catch (NotFoundException e) {
226 // Ignore
227 }
228
229 // Set the preference title to the activity's label if no
230 // meta-data is found
231 if (TextUtils.isEmpty(title)) {
232 title = resolveInfo.loadLabel(pm).toString();
233 }
234
235 // Set icon, title and summary for the preference
236 // TODO:
237 //tile.icon = icon;
238 tile.title = title;
239 tile.summary = summary;
240 // Replace the intent with this specific activity
241 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
242 resolveInfo.activityInfo.name);
243
244 return true;
245 }
246 }
247 }
248
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700249 return false;
250 }
251
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200252 /**
Ying Wanga7188322010-01-04 18:45:10 -0800253 * Returns true if Monkey is running.
254 */
255 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700256 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800257 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700258
259 /**
260 * Returns whether the device is voice-capable (meaning, it is also a phone).
261 */
262 public static boolean isVoiceCapable(Context context) {
263 TelephonyManager telephony =
264 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
265 return telephony != null && telephony.isVoiceCapable();
266 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800267
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700268 public static boolean isWifiOnly(Context context) {
269 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
270 Context.CONNECTIVITY_SERVICE);
271 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800272 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800273
274 /**
275 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
276 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900277 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800278 */
279 public static String getWifiIpAddresses(Context context) {
280 ConnectivityManager cm = (ConnectivityManager)
281 context.getSystemService(Context.CONNECTIVITY_SERVICE);
282 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700283 return formatIpAddresses(prop);
284 }
285
286 /**
287 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
288 * addresses.
289 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900290 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700291 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900292 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700293 LinkProperties prop = cm.getActiveLinkProperties();
294 return formatIpAddresses(prop);
295 }
296
297 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800298 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900299 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800300 // If there are no entries, return null
301 if (!iter.hasNext()) return null;
302 // Concatenate all available addresses, comma separated
303 String addresses = "";
304 while (iter.hasNext()) {
305 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900306 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800307 }
308 return addresses;
309 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900310
311 public static Locale createLocaleFromString(String localeStr) {
312 // TODO: is there a better way to actually construct a locale that will match?
313 // The main problem is, on top of Java specs, locale.toString() and
314 // new Locale(locale.toString()).toString() do not return equal() strings in
315 // many cases, because the constructor takes the only string as the language
316 // code. So : new Locale("en", "US").toString() => "en_US"
317 // And : new Locale("en_US").toString() => "en_us"
318 if (null == localeStr)
319 return Locale.getDefault();
320 String[] brokenDownLocale = localeStr.split("_", 3);
321 // split may not return a 0-length array.
322 if (1 == brokenDownLocale.length) {
323 return new Locale(brokenDownLocale[0]);
324 } else if (2 == brokenDownLocale.length) {
325 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
326 } else {
327 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
328 }
329 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700330
Elliott Hughes7253df32014-09-02 17:10:14 -0700331 /** Formats the ratio of amount/total as a percentage. */
332 public static String formatPercentage(long amount, long total) {
333 return formatPercentage(((double) amount) / total);
334 }
335
336 /** Formats an integer from 0..100 as a percentage. */
337 public static String formatPercentage(int percentage) {
338 return formatPercentage(((double) percentage) / 100.0);
339 }
340
341 /** Formats a double from 0.0..1.0 as a percentage. */
342 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700343 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700344 }
345
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900346 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
347 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
348 }
349
Amith Yamasania4379d62011-07-22 10:34:58 -0700350 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700351 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700352 }
353
354 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900355 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
356 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700357 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700358 }
359
360 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
361 final Intent intent = batteryChangedIntent;
362
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900363 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
364 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
365 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700366 String statusString;
367 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700368 int resId;
369 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
370 resId = R.string.battery_info_status_charging_ac;
371 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
372 resId = R.string.battery_info_status_charging_usb;
373 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
374 resId = R.string.battery_info_status_charging_wireless;
375 } else {
376 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700377 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700378 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700379 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
380 statusString = res.getString(R.string.battery_info_status_discharging);
381 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
382 statusString = res.getString(R.string.battery_info_status_not_charging);
383 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
384 statusString = res.getString(R.string.battery_info_status_full);
385 } else {
386 statusString = res.getString(R.string.battery_info_status_unknown);
387 }
388
389 return statusString;
390 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700391
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800392 public static void forcePrepareCustomPreferencesList(
393 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
394 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
395 list.setClipToPadding(false);
396 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
397 }
398
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700399 /**
400 * Prepare a custom preferences layout, moving padding to {@link ListView}
401 * when outside scrollbars are requested. Usually used to display
402 * {@link ListView} and {@link TabWidget} with correct padding.
403 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700404 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800405 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700406 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700407 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700408 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700409 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700410 final int paddingBottom = res.getDimensionPixelSize(
411 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700412
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700413 if (parent instanceof PreferenceFrameLayout) {
414 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
415
416 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
417 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
418 } else {
419 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
420 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700421 }
422 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700423
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700424 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700425 final Resources res = view.getResources();
426 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700427
428 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
429 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700430 final int paddingBottom = res.getDimensionPixelSize(
431 com.android.internal.R.dimen.preference_fragment_padding_bottom);
432
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700433 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700434 }
435
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700436 /**
437 * Return string resource that best describes combination of tethering
438 * options available on this device.
439 */
440 public static int getTetheringLabel(ConnectivityManager cm) {
441 String[] usbRegexs = cm.getTetherableUsbRegexs();
442 String[] wifiRegexs = cm.getTetherableWifiRegexs();
443 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
444
445 boolean usbAvailable = usbRegexs.length != 0;
446 boolean wifiAvailable = wifiRegexs.length != 0;
447 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
448
449 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
450 return R.string.tether_settings_title_all;
451 } else if (wifiAvailable && usbAvailable) {
452 return R.string.tether_settings_title_all;
453 } else if (wifiAvailable && bluetoothAvailable) {
454 return R.string.tether_settings_title_all;
455 } else if (wifiAvailable) {
456 return R.string.tether_settings_title_wifi;
457 } else if (usbAvailable && bluetoothAvailable) {
458 return R.string.tether_settings_title_usb_bluetooth;
459 } else if (usbAvailable) {
460 return R.string.tether_settings_title_usb;
461 } else {
462 return R.string.tether_settings_title_bluetooth;
463 }
464 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700465
466 /* Used by UserSettings as well. Call this on a non-ui thread. */
467 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
468 Uri contactUri = Profile.CONTENT_URI;
469
470 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
471 context.getContentResolver(),
472 contactUri, true);
473 // If there's no profile photo, assign a default avatar
474 if (avatarDataStream == null) {
475 return false;
476 }
477 int userId = user != null ? user.id : UserHandle.myUserId();
478 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700479 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
480 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700481 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700482 avatarDataStream.close();
483 } catch (IOException ioe) { }
484 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700485 }
486
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700487 public static String getMeProfileName(Context context, boolean full) {
488 if (full) {
489 return getProfileDisplayName(context);
490 } else {
491 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700492 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700493 }
494
495 private static String getShorterNameIfPossible(Context context) {
496 final String given = getLocalProfileGivenName(context);
497 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
498 }
499
500 private static String getLocalProfileGivenName(Context context) {
501 final ContentResolver cr = context.getContentResolver();
502
503 // Find the raw contact ID for the local ME profile raw contact.
504 final long localRowProfileId;
505 final Cursor localRawProfile = cr.query(
506 Profile.CONTENT_RAW_CONTACTS_URI,
507 new String[] {RawContacts._ID},
508 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
509 RawContacts.ACCOUNT_NAME + " IS NULL",
510 null, null);
511 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700512
513 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700514 if (!localRawProfile.moveToFirst()) {
515 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700516 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700517 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700518 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700519 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700520 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700521
522 // Find the structured name for the raw contact.
523 final Cursor structuredName = cr.query(
524 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
525 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
526 CommonDataKinds.StructuredName.FAMILY_NAME},
527 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
528 null, null);
529 if (structuredName == null) return null;
530
531 try {
532 if (!structuredName.moveToFirst()) {
533 return null;
534 }
535 String partialName = structuredName.getString(0);
536 if (TextUtils.isEmpty(partialName)) {
537 partialName = structuredName.getString(1);
538 }
539 return partialName;
540 } finally {
541 structuredName.close();
542 }
543 }
544
545 private static final String getProfileDisplayName(Context context) {
546 final ContentResolver cr = context.getContentResolver();
547 final Cursor profile = cr.query(Profile.CONTENT_URI,
548 new String[] {Profile.DISPLAY_NAME}, null, null, null);
549 if (profile == null) return null;
550
551 try {
552 if (!profile.moveToFirst()) {
553 return null;
554 }
555 return profile.getString(0);
556 } finally {
557 profile.close();
558 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700559 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700560
561 /** Not global warming, it's global change warning. */
562 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
563 final Runnable positiveAction) {
564 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
565 builder.setTitle(titleResId);
566 builder.setMessage(R.string.global_change_warning);
567 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
568 @Override
569 public void onClick(DialogInterface dialog, int which) {
570 positiveAction.run();
571 }
572 });
573 builder.setNegativeButton(android.R.string.cancel, null);
574
575 return builder.create();
576 }
577
578 public static boolean hasMultipleUsers(Context context) {
579 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
580 .getUsers().size() > 1;
581 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700582
583 /**
584 * Start a new instance of the activity, showing only the given fragment.
585 * When launched in this mode, the given preference fragment will be instantiated and fill the
586 * entire activity.
587 *
588 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000589 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700590 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700591 * @param resultTo Option fragment that should receive the result of the activity launch.
592 * @param resultRequestCode If resultTo is non-null, this is the request code in which
593 * to report the result.
594 * @param titleResId resource id for the String to display for the title of this set
595 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700596 * @param title String to display for the title of this set of preferences.
597 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000598 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100599 Fragment resultTo, int resultRequestCode, int titleResId,
600 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700601 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100602 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
603 }
604
605 /**
606 * Start a new instance of the activity, showing only the given fragment.
607 * When launched in this mode, the given preference fragment will be instantiated and fill the
608 * entire activity.
609 *
610 * @param context The context.
611 * @param fragmentName The name of the fragment to display.
612 * @param args Optional arguments to supply to the fragment.
613 * @param resultTo Option fragment that should receive the result of the activity launch.
614 * @param resultRequestCode If resultTo is non-null, this is the request code in which
615 * to report the result.
616 * @param titleResPackageName Optional package name for the resource id of the title.
617 * @param titleResId resource id for the String to display for the title of this set
618 * of preferences.
619 * @param title String to display for the title of this set of preferences.
620 */
621 public static void startWithFragment(Context context, String fragmentName, Bundle args,
622 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
623 CharSequence title) {
624 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
625 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700626 }
627
628 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100629 Fragment resultTo, int resultRequestCode, int titleResId,
630 CharSequence title, boolean isShortcut) {
631 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
632 null /* titleResPackageName */, titleResId, title, isShortcut);
633 if (resultTo == null) {
634 context.startActivity(intent);
635 } else {
636 resultTo.startActivityForResult(intent, resultRequestCode);
637 }
638 }
639
640 public static void startWithFragment(Context context, String fragmentName, Bundle args,
641 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
642 CharSequence title, boolean isShortcut) {
643 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
644 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700645 if (resultTo == null) {
646 context.startActivity(intent);
647 } else {
648 resultTo.startActivityForResult(intent, resultRequestCode);
649 }
650 }
651
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100652 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100653 int titleResId, CharSequence title, boolean isShortcut,
654 UserHandle userHandle) {
655 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
656 null /* titleResPackageName */, titleResId, title, isShortcut);
657 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
658 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
659 context.startActivityAsUser(intent, userHandle);
660 }
661
662 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
663 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
664 UserHandle userHandle) {
665 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
666 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100667 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
668 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100669 context.startActivityAsUser(intent, userHandle);
670 }
671
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700672 /**
673 * Build an Intent to launch a new activity showing the selected fragment.
674 * The implementation constructs an Intent that re-launches the current activity with the
675 * appropriate arguments to display the fragment.
676 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700677 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700678 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000679 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700680 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100681 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700682 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700683 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700684 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700685 * @return Returns an Intent that can be launched to display the given
686 * fragment.
687 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000688 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100689 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
690 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700691 Intent intent = new Intent(Intent.ACTION_MAIN);
692 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000693 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700694 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100695 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
696 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700697 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700698 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700699 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700700 return intent;
701 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100702
703 /**
704 * Returns the managed profile of the current user or null if none found.
705 */
706 public static UserHandle getManagedProfile(UserManager userManager) {
707 List<UserHandle> userProfiles = userManager.getUserProfiles();
708 final int count = userProfiles.size();
709 for (int i = 0; i < count; i++) {
710 final UserHandle profile = userProfiles.get(i);
711 if (profile.getIdentifier() == userManager.getUserHandle()) {
712 continue;
713 }
714 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
715 if (userInfo.isManagedProfile()) {
716 return profile;
717 }
718 }
719 return null;
720 }
721
722 /**
723 * Returns true if the current profile is a managed one.
724 */
725 public static boolean isManagedProfile(UserManager userManager) {
726 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
727 return currentUser.isManagedProfile();
728 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100729
730 /**
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100731 * Creates a {@link UserSpinnerAdapter} if there is more than one profile on the device.
732 *
733 * <p> The adapter can be used to populate a spinner that switches between the Settings
734 * app on the different profiles.
735 *
736 * @return a {@link UserSpinnerAdapter} or null if there is only one profile.
737 */
738 public static UserSpinnerAdapter createUserSpinnerAdapter(UserManager userManager,
739 Context context) {
740 List<UserHandle> userProfiles = userManager.getUserProfiles();
741 if (userProfiles.size() < 2) {
742 return null;
743 }
744
745 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
746 // The first option should be the current profile
747 userProfiles.remove(myUserHandle);
748 userProfiles.add(0, myUserHandle);
749
750 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
751 final int count = userProfiles.size();
752 for (int i = 0; i < count; i++) {
753 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
754 }
755 return new UserSpinnerAdapter(context, userDetails);
756 }
757
758 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100759 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100760 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100761 * The target user can be either the current user, the user that launched this activity or
762 * the user contained as an extra in the arguments or intent extras.
763 *
764 * Note: This is secure in the sense that it only returns a target user different to the current
765 * one if the app launching this activity is the Settings app itself, running in the same user
766 * 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 +0100767 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100768 public static UserHandle getSecureTargetUser(IBinder activityToken,
769 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
770 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
771 IActivityManager am = ActivityManagerNative.getDefault();
772 try {
773 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
774 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
775
776 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
777 am.getLaunchedFromUid(activityToken)));
778 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
779 // Check it's secure
780 if (isProfileOf(um, launchedFromUser)) {
781 return launchedFromUser;
782 }
783 }
784 UserHandle extrasUser = intentExtras != null
785 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
786 if (extrasUser != null && !extrasUser.equals(currentUser)) {
787 // Check it's secure
788 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
789 return extrasUser;
790 }
791 }
792 UserHandle argumentsUser = arguments != null
793 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
794 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
795 // Check it's secure
796 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
797 return argumentsUser;
798 }
799 }
800 } catch (RemoteException e) {
801 // Should not happen
802 Log.v(TAG, "Could not talk to activity manager.", e);
803 }
804 return currentUser;
805 }
806
807 /**
808 * Returns the target user for a Settings activity.
809 *
810 * The target user can be either the current user, the user that launched this activity or
811 * the user contained as an extra in the arguments or intent extras.
812 *
813 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
814 * possible.
815 *
816 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
817 */
818 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
819 @Nullable Bundle intentExtras) {
820 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
821 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100822 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100823 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
824 am.getLaunchedFromUid(activityToken)));
825 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
826 return launchedFromUser;
827 }
828 UserHandle extrasUser = intentExtras != null
829 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
830 if (extrasUser != null && !extrasUser.equals(currentUser)) {
831 return extrasUser;
832 }
833 UserHandle argumentsUser = arguments != null
834 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
835 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
836 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100837 }
838 } catch (RemoteException e) {
839 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100840 Log.v(TAG, "Could not talk to activity manager.", e);
841 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100842 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100843 return currentUser;
844 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100845
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100846 /**
847 * Returns true if the user provided is in the same profiles group as the current user.
848 */
849 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
850 if (um == null || otherUser == null) return false;
851 return (UserHandle.myUserId() == otherUser.getIdentifier())
852 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100853 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530854
Andres Moralesce249fe2014-07-07 16:58:16 -0700855
856 /**
857 * Returns whether or not this device is able to be OEM unlocked.
858 */
859 static boolean isOemUnlockEnabled(Context context) {
860 PersistentDataBlockManager manager =(PersistentDataBlockManager)
861 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
862 return manager.getOemUnlockEnabled();
863 }
864
865 /**
866 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
867 * devices allow users to flash other OSes to them.
868 */
869 static void setOemUnlockEnabled(Context context, boolean enabled) {
870 PersistentDataBlockManager manager =(PersistentDataBlockManager)
871 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
872 manager.setOemUnlockEnabled(enabled);
873 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100874
875 /**
876 * Returns a circular icon for a user.
877 */
878 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000879 if (user.isManagedProfile()) {
880 // We use predefined values for managed profiles
881 Bitmap b = BitmapFactory.decodeResource(context.getResources(),
882 com.android.internal.R.drawable.ic_corp_icon);
883 return CircleFramedDrawable.getInstance(context, b);
884 }
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100885 if (user.iconPath != null) {
886 Bitmap icon = um.getUserIcon(user.id);
887 if (icon != null) {
888 return CircleFramedDrawable.getInstance(context, icon);
889 }
890 }
Zoltan Szatmary-Banae6ea362014-12-18 12:10:16 +0000891 return CircleFramedDrawable.getInstance(context, UserIcons.convertToBitmap(
892 UserIcons.getDefaultUserIcon(user.id, /* light= */ false)));
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100893 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700894
895 /**
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000896 * Returns a label for the user, in the form of "User: user name" or "Work profile".
897 */
898 public static String getUserLabel(Context context, UserInfo info) {
899 if (info.isManagedProfile()) {
900 // We use predefined values for managed profiles
901 return context.getString(R.string.managed_user_title);
902 }
903 String name = info != null ? info.name : null;
904 if (name == null && info != null) {
905 name = Integer.toString(info.id);
906 } else if (info == null) {
907 name = context.getString(R.string.unknown);
908 }
909 return context.getResources().getString(R.string.running_process_item_user_label, name);
910 }
911
912 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700913 * Return whether or not the user should have a SIM Cards option in Settings.
914 * TODO: Change back to returning true if count is greater than one after testing.
915 * TODO: See bug 16533525.
916 */
917 public static boolean showSimCardTile(Context context) {
918 final TelephonyManager tm =
919 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
920
PauloftheWestdbd03822014-12-04 11:56:35 -0800921 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700922 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200923
924 /**
925 * Determine whether a package is a "system package", in which case certain things (like
926 * disabling notifications or disabling the package altogether) should be disallowed.
927 */
928 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
929 if (sSystemSignature == null) {
930 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
931 }
932 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
933 }
934
935 private static Signature[] sSystemSignature;
936
937 private static Signature getFirstSignature(PackageInfo pkg) {
938 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
939 return pkg.signatures[0];
940 }
941 return null;
942 }
943
944 private static Signature getSystemSignature(PackageManager pm) {
945 try {
946 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
947 return getFirstSignature(sys);
948 } catch (NameNotFoundException e) {
949 }
950 return null;
951 }
952
Elliott Hughes7253df32014-09-02 17:10:14 -0700953 /**
954 * Returns elapsed time for the given millis, in the following format:
955 * 2d 5h 40m 29s
956 * @param context the application context
957 * @param millis the elapsed time in milli seconds
958 * @param withSeconds include seconds?
959 * @return the formatted elapsed time
960 */
961 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
962 StringBuilder sb = new StringBuilder();
963 int seconds = (int) Math.floor(millis / 1000);
964 if (!withSeconds) {
965 // Round up.
966 seconds += 30;
967 }
968
969 int days = 0, hours = 0, minutes = 0;
970 if (seconds >= SECONDS_PER_DAY) {
971 days = seconds / SECONDS_PER_DAY;
972 seconds -= days * SECONDS_PER_DAY;
973 }
974 if (seconds >= SECONDS_PER_HOUR) {
975 hours = seconds / SECONDS_PER_HOUR;
976 seconds -= hours * SECONDS_PER_HOUR;
977 }
978 if (seconds >= SECONDS_PER_MINUTE) {
979 minutes = seconds / SECONDS_PER_MINUTE;
980 seconds -= minutes * SECONDS_PER_MINUTE;
981 }
982 if (withSeconds) {
983 if (days > 0) {
984 sb.append(context.getString(R.string.battery_history_days,
985 days, hours, minutes, seconds));
986 } else if (hours > 0) {
987 sb.append(context.getString(R.string.battery_history_hours,
988 hours, minutes, seconds));
989 } else if (minutes > 0) {
990 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
991 } else {
992 sb.append(context.getString(R.string.battery_history_seconds, seconds));
993 }
994 } else {
995 if (days > 0) {
996 sb.append(context.getString(R.string.battery_history_days_no_seconds,
997 days, hours, minutes));
998 } else if (hours > 0) {
999 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
1000 hours, minutes));
1001 } else {
1002 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
1003 }
1004 }
1005 return sb.toString();
1006 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001007
1008 /**
1009 * finds a record with subId.
1010 * Since the number of SIMs are few, an array is fine.
1011 */
Wink Saville0183fb52014-11-22 10:11:39 -08001012 public static SubscriptionInfo findRecordBySubId(Context context, final int subId) {
Wink Savilleca756612014-11-08 10:47:12 -08001013 final List<SubscriptionInfo> subInfoList =
Wink Saville0183fb52014-11-22 10:11:39 -08001014 SubscriptionManager.from(context).getActiveSubscriptionInfoList();
1015 if (subInfoList != null) {
1016 final int subInfoLength = subInfoList.size();
PauloftheWest0a0daca2014-11-06 15:02:58 -08001017
Wink Saville0183fb52014-11-22 10:11:39 -08001018 for (int i = 0; i < subInfoLength; ++i) {
1019 final SubscriptionInfo sir = subInfoList.get(i);
1020 if (sir != null && sir.getSubscriptionId() == subId) {
1021 return sir;
1022 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001023 }
1024 }
1025
1026 return null;
1027 }
1028
1029 /**
1030 * finds a record with slotId.
1031 * Since the number of SIMs are few, an array is fine.
1032 */
Wink Saville0183fb52014-11-22 10:11:39 -08001033 public static SubscriptionInfo findRecordBySlotId(Context context, final int slotId) {
Wink Savilleca756612014-11-08 10:47:12 -08001034 final List<SubscriptionInfo> subInfoList =
Wink Saville0183fb52014-11-22 10:11:39 -08001035 SubscriptionManager.from(context).getActiveSubscriptionInfoList();
1036 if (subInfoList != null) {
1037 final int subInfoLength = subInfoList.size();
PauloftheWest0a0daca2014-11-06 15:02:58 -08001038
Wink Saville0183fb52014-11-22 10:11:39 -08001039 for (int i = 0; i < subInfoLength; ++i) {
1040 final SubscriptionInfo sir = subInfoList.get(i);
1041 if (sir.getSimSlotIndex() == slotId) {
1042 //Right now we take the first subscription on a SIM.
1043 return sir;
1044 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001045 }
1046 }
1047
1048 return null;
1049 }
1050
Amith Yamasani45f86232014-11-19 17:12:46 -08001051 /**
1052 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
1053 * @param userManager Instance of UserManager
1054 * @param checkUser The user to check the existence of.
1055 * @return UserInfo of the user or null for non-existent user.
1056 */
1057 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
1058 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
1059 final int checkUserId = checkUser.getIdentifier();
1060 for (UserInfo user : users) {
1061 if (user.id == checkUserId) {
1062 return user;
1063 }
1064 }
1065 return null;
1066 }
1067
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +00001068 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
1069 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
1070 com.android.internal.R.styleable.Preference,
1071 com.android.internal.R.attr.preferenceCategoryStyle, 0);
1072 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
1073 0);
1074 a.recycle();
1075 return inflater.inflate(resId, parent, false);
1076 }
1077
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -08001078 /**
1079 * Return if we are running low on storage space or not.
1080 *
1081 * @param context The context
1082 * @return true if we are running low on storage space
1083 */
1084 public static boolean isLowStorage(Context context) {
1085 final StorageManager sm = StorageManager.from(context);
1086 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
1087 }
1088
Zoltan Szatmary-Bane5814ff2014-12-19 16:27:45 +00001089
1090 /**
1091 * Returns a default user icon (as a {@link Bitmap}) for the given user.
1092 *
1093 * Note that for guest users, you should pass in {@code UserHandle.USER_NULL}.
1094 * @param userId the user id or {@code UserHandle.USER_NULL} for a non-user specific icon
1095 */
1096 public static Bitmap getDefaultUserIconAsBitmap(int userId) {
1097 Bitmap bitmap = null;
1098 // Try finding the corresponding bitmap in the dark bitmap cache
1099 bitmap = sDarkDefaultUserBitmapCache.get(userId);
1100 if (bitmap == null) {
1101 bitmap = UserIcons.convertToBitmap(UserIcons.getDefaultUserIcon(userId, false));
1102 // Save it to cache
1103 sDarkDefaultUserBitmapCache.put(userId, bitmap);
1104 }
1105 return bitmap;
1106 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -08001107}