blob: 6c9391dc1a862383ca8b2130b0b09ebcf47ee3b3 [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;
40import android.content.res.Resources.NotFoundException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070041import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070042import android.graphics.Bitmap;
43import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020044import android.graphics.drawable.Drawable;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080045import android.net.ConnectivityManager;
46import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070047import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070048import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020049import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010050import android.os.IBinder;
51import android.os.RemoteException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070052import android.os.UserHandle;
53import android.os.UserManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080054import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070055import android.preference.PreferenceFrameLayout;
56import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070057import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070058import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070059import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070060import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070061import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070062import android.service.persistentdata.PersistentDataBlockManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070063import android.telephony.TelephonyManager;
Elliott Hughes7253df32014-09-02 17:10:14 -070064import android.text.BidiFormatter;
65import android.text.TextDirectionHeuristics;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020066import android.text.TextUtils;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010067import android.util.Log;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070068import android.view.View;
69import android.view.ViewGroup;
70import android.widget.ListView;
71import android.widget.TabWidget;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010072
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010073import com.android.internal.util.ImageUtils;
74import com.android.internal.util.UserIcons;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010075import com.android.settings.UserSpinnerAdapter.UserDetails;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070076import com.android.settings.dashboard.DashboardCategory;
77import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010078import com.android.settings.drawable.CircleFramedDrawable;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070079
Amith Yamasaniae47ef42012-09-16 17:53:35 -070080import java.io.IOException;
81import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080082import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070083import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010084import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080085import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070086import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090087import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080088
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070089public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010090 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010091
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080092 /**
93 * Set the preference's title to the matching activity's label.
94 */
95 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
96
97 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090098 * The opacity level of a disabled icon.
99 */
100 public static final float DISABLED_ALPHA = 0.4f;
101
102 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700103 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
104 * 1 is most bad (red), the last value is least bad (green).
105 */
106 public static final int[] BADNESS_COLORS = new int[] {
107 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
108 0xfffabf2c, 0xff679e37, 0xff0a7f42
109 };
110
111 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200112 * Name of the meta-data item that should be set in the AndroidManifest.xml
113 * to specify the icon that should be displayed for the preference.
114 */
115 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
116
117 /**
118 * Name of the meta-data item that should be set in the AndroidManifest.xml
119 * to specify the title that should be displayed for the preference.
120 */
121 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
122
123 /**
124 * Name of the meta-data item that should be set in the AndroidManifest.xml
125 * to specify the summary text that should be displayed for the preference.
126 */
127 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
128
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100129 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
130
Elliott Hughes7253df32014-09-02 17:10:14 -0700131 private static final int SECONDS_PER_MINUTE = 60;
132 private static final int SECONDS_PER_HOUR = 60 * 60;
133 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
134
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200135 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800136 * Finds a matching activity for a preference's intent. If a matching
137 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800138 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800139 * @param context The context.
140 * @param parentPreferenceGroup The preference group that contains the
141 * preference whose intent is being resolved.
142 * @param preferenceKey The key of the preference whose intent is being
143 * resolved.
144 * @param flags 0 or one or more of
145 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
146 * .
147 * @return Whether an activity was found. If false, the preference was
148 * removed.
149 */
150 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
151 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800152
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800153 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
154 if (preference == null) {
155 return false;
156 }
Ying Wanga7188322010-01-04 18:45:10 -0800157
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800158 Intent intent = preference.getIntent();
159 if (intent != null) {
160 // Find the activity that is in the system image
161 PackageManager pm = context.getPackageManager();
162 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
163 int listSize = list.size();
164 for (int i = 0; i < listSize; i++) {
165 ResolveInfo resolveInfo = list.get(i);
166 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
167 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800168
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800169 // Replace the intent with this specific activity
170 preference.setIntent(new Intent().setClassName(
171 resolveInfo.activityInfo.packageName,
172 resolveInfo.activityInfo.name));
173
174 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
175 // Set the preference title to the activity's label
176 preference.setTitle(resolveInfo.loadLabel(pm));
177 }
Ying Wanga7188322010-01-04 18:45:10 -0800178
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800179 return true;
180 }
181 }
182 }
183
184 // Did not find a matching activity, so remove the preference
185 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800186
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900187 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800188 }
Ying Wanga7188322010-01-04 18:45:10 -0800189
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700190 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700191 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700192
193 Intent intent = tile.intent;
194 if (intent != null) {
195 // Find the activity that is in the system image
196 PackageManager pm = context.getPackageManager();
197 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
198 int listSize = list.size();
199 for (int i = 0; i < listSize; i++) {
200 ResolveInfo resolveInfo = list.get(i);
201 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
202 != 0) {
203 Drawable icon = null;
204 String title = null;
205 String summary = null;
206
207 // Get the activity's meta-data
208 try {
209 Resources res = pm.getResourcesForApplication(
210 resolveInfo.activityInfo.packageName);
211 Bundle metaData = resolveInfo.activityInfo.metaData;
212
213 if (res != null && metaData != null) {
214 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
215 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
216 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
217 }
218 } catch (NameNotFoundException e) {
219 // Ignore
220 } catch (NotFoundException e) {
221 // Ignore
222 }
223
224 // Set the preference title to the activity's label if no
225 // meta-data is found
226 if (TextUtils.isEmpty(title)) {
227 title = resolveInfo.loadLabel(pm).toString();
228 }
229
230 // Set icon, title and summary for the preference
231 // TODO:
232 //tile.icon = icon;
233 tile.title = title;
234 tile.summary = summary;
235 // Replace the intent with this specific activity
236 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
237 resolveInfo.activityInfo.name);
238
239 return true;
240 }
241 }
242 }
243
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700244 return false;
245 }
246
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200247 /**
Ying Wanga7188322010-01-04 18:45:10 -0800248 * Returns true if Monkey is running.
249 */
250 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700251 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800252 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700253
254 /**
255 * Returns whether the device is voice-capable (meaning, it is also a phone).
256 */
257 public static boolean isVoiceCapable(Context context) {
258 TelephonyManager telephony =
259 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
260 return telephony != null && telephony.isVoiceCapable();
261 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800262
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700263 public static boolean isWifiOnly(Context context) {
264 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
265 Context.CONNECTIVITY_SERVICE);
266 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800267 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800268
269 /**
270 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
271 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900272 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800273 */
274 public static String getWifiIpAddresses(Context context) {
275 ConnectivityManager cm = (ConnectivityManager)
276 context.getSystemService(Context.CONNECTIVITY_SERVICE);
277 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700278 return formatIpAddresses(prop);
279 }
280
281 /**
282 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
283 * addresses.
284 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900285 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700286 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900287 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700288 LinkProperties prop = cm.getActiveLinkProperties();
289 return formatIpAddresses(prop);
290 }
291
292 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800293 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900294 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800295 // If there are no entries, return null
296 if (!iter.hasNext()) return null;
297 // Concatenate all available addresses, comma separated
298 String addresses = "";
299 while (iter.hasNext()) {
300 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900301 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800302 }
303 return addresses;
304 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900305
306 public static Locale createLocaleFromString(String localeStr) {
307 // TODO: is there a better way to actually construct a locale that will match?
308 // The main problem is, on top of Java specs, locale.toString() and
309 // new Locale(locale.toString()).toString() do not return equal() strings in
310 // many cases, because the constructor takes the only string as the language
311 // code. So : new Locale("en", "US").toString() => "en_US"
312 // And : new Locale("en_US").toString() => "en_us"
313 if (null == localeStr)
314 return Locale.getDefault();
315 String[] brokenDownLocale = localeStr.split("_", 3);
316 // split may not return a 0-length array.
317 if (1 == brokenDownLocale.length) {
318 return new Locale(brokenDownLocale[0]);
319 } else if (2 == brokenDownLocale.length) {
320 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
321 } else {
322 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
323 }
324 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700325
Elliott Hughes7253df32014-09-02 17:10:14 -0700326 /** Formats the ratio of amount/total as a percentage. */
327 public static String formatPercentage(long amount, long total) {
328 return formatPercentage(((double) amount) / total);
329 }
330
331 /** Formats an integer from 0..100 as a percentage. */
332 public static String formatPercentage(int percentage) {
333 return formatPercentage(((double) percentage) / 100.0);
334 }
335
336 /** Formats a double from 0.0..1.0 as a percentage. */
337 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700338 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700339 }
340
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900341 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
342 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
343 }
344
Amith Yamasania4379d62011-07-22 10:34:58 -0700345 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700346 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700347 }
348
349 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900350 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
351 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700352 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700353 }
354
355 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
356 final Intent intent = batteryChangedIntent;
357
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900358 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
359 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
360 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700361 String statusString;
362 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700363 int resId;
364 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
365 resId = R.string.battery_info_status_charging_ac;
366 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
367 resId = R.string.battery_info_status_charging_usb;
368 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
369 resId = R.string.battery_info_status_charging_wireless;
370 } else {
371 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700372 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700373 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700374 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
375 statusString = res.getString(R.string.battery_info_status_discharging);
376 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
377 statusString = res.getString(R.string.battery_info_status_not_charging);
378 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
379 statusString = res.getString(R.string.battery_info_status_full);
380 } else {
381 statusString = res.getString(R.string.battery_info_status_unknown);
382 }
383
384 return statusString;
385 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700386
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800387 public static void forcePrepareCustomPreferencesList(
388 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
389 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
390 list.setClipToPadding(false);
391 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
392 }
393
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700394 /**
395 * Prepare a custom preferences layout, moving padding to {@link ListView}
396 * when outside scrollbars are requested. Usually used to display
397 * {@link ListView} and {@link TabWidget} with correct padding.
398 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700399 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800400 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700401 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700402 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700403 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700404 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700405 final int paddingBottom = res.getDimensionPixelSize(
406 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700407
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700408 if (parent instanceof PreferenceFrameLayout) {
409 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
410
411 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
412 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
413 } else {
414 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
415 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700416 }
417 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700418
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700419 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700420 final Resources res = view.getResources();
421 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700422
423 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
424 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700425 final int paddingBottom = res.getDimensionPixelSize(
426 com.android.internal.R.dimen.preference_fragment_padding_bottom);
427
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700428 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700429 }
430
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700431 /**
432 * Return string resource that best describes combination of tethering
433 * options available on this device.
434 */
435 public static int getTetheringLabel(ConnectivityManager cm) {
436 String[] usbRegexs = cm.getTetherableUsbRegexs();
437 String[] wifiRegexs = cm.getTetherableWifiRegexs();
438 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
439
440 boolean usbAvailable = usbRegexs.length != 0;
441 boolean wifiAvailable = wifiRegexs.length != 0;
442 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
443
444 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
445 return R.string.tether_settings_title_all;
446 } else if (wifiAvailable && usbAvailable) {
447 return R.string.tether_settings_title_all;
448 } else if (wifiAvailable && bluetoothAvailable) {
449 return R.string.tether_settings_title_all;
450 } else if (wifiAvailable) {
451 return R.string.tether_settings_title_wifi;
452 } else if (usbAvailable && bluetoothAvailable) {
453 return R.string.tether_settings_title_usb_bluetooth;
454 } else if (usbAvailable) {
455 return R.string.tether_settings_title_usb;
456 } else {
457 return R.string.tether_settings_title_bluetooth;
458 }
459 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700460
461 /* Used by UserSettings as well. Call this on a non-ui thread. */
462 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
463 Uri contactUri = Profile.CONTENT_URI;
464
465 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
466 context.getContentResolver(),
467 contactUri, true);
468 // If there's no profile photo, assign a default avatar
469 if (avatarDataStream == null) {
470 return false;
471 }
472 int userId = user != null ? user.id : UserHandle.myUserId();
473 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700474 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
475 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700476 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700477 avatarDataStream.close();
478 } catch (IOException ioe) { }
479 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700480 }
481
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700482 public static String getMeProfileName(Context context, boolean full) {
483 if (full) {
484 return getProfileDisplayName(context);
485 } else {
486 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700487 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700488 }
489
490 private static String getShorterNameIfPossible(Context context) {
491 final String given = getLocalProfileGivenName(context);
492 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
493 }
494
495 private static String getLocalProfileGivenName(Context context) {
496 final ContentResolver cr = context.getContentResolver();
497
498 // Find the raw contact ID for the local ME profile raw contact.
499 final long localRowProfileId;
500 final Cursor localRawProfile = cr.query(
501 Profile.CONTENT_RAW_CONTACTS_URI,
502 new String[] {RawContacts._ID},
503 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
504 RawContacts.ACCOUNT_NAME + " IS NULL",
505 null, null);
506 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700507
508 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700509 if (!localRawProfile.moveToFirst()) {
510 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700511 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700512 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700513 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700514 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700515 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700516
517 // Find the structured name for the raw contact.
518 final Cursor structuredName = cr.query(
519 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
520 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
521 CommonDataKinds.StructuredName.FAMILY_NAME},
522 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
523 null, null);
524 if (structuredName == null) return null;
525
526 try {
527 if (!structuredName.moveToFirst()) {
528 return null;
529 }
530 String partialName = structuredName.getString(0);
531 if (TextUtils.isEmpty(partialName)) {
532 partialName = structuredName.getString(1);
533 }
534 return partialName;
535 } finally {
536 structuredName.close();
537 }
538 }
539
540 private static final String getProfileDisplayName(Context context) {
541 final ContentResolver cr = context.getContentResolver();
542 final Cursor profile = cr.query(Profile.CONTENT_URI,
543 new String[] {Profile.DISPLAY_NAME}, null, null, null);
544 if (profile == null) return null;
545
546 try {
547 if (!profile.moveToFirst()) {
548 return null;
549 }
550 return profile.getString(0);
551 } finally {
552 profile.close();
553 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700554 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700555
556 /** Not global warming, it's global change warning. */
557 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
558 final Runnable positiveAction) {
559 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
560 builder.setTitle(titleResId);
561 builder.setMessage(R.string.global_change_warning);
562 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
563 @Override
564 public void onClick(DialogInterface dialog, int which) {
565 positiveAction.run();
566 }
567 });
568 builder.setNegativeButton(android.R.string.cancel, null);
569
570 return builder.create();
571 }
572
573 public static boolean hasMultipleUsers(Context context) {
574 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
575 .getUsers().size() > 1;
576 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700577
578 /**
579 * Start a new instance of the activity, showing only the given fragment.
580 * When launched in this mode, the given preference fragment will be instantiated and fill the
581 * entire activity.
582 *
583 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000584 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700585 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700586 * @param resultTo Option fragment that should receive the result of the activity launch.
587 * @param resultRequestCode If resultTo is non-null, this is the request code in which
588 * to report the result.
589 * @param titleResId resource id for the String to display for the title of this set
590 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700591 * @param title String to display for the title of this set of preferences.
592 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000593 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700594 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700595 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
596 titleResId, title, false /* not a shortcut */);
597 }
598
599 public static void startWithFragment(Context context, String fragmentName, Bundle args,
600 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title,
601 boolean isShortcut) {
602 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
603 title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700604 if (resultTo == null) {
605 context.startActivity(intent);
606 } else {
607 resultTo.startActivityForResult(intent, resultRequestCode);
608 }
609 }
610
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100611 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
612 int titleResId, CharSequence title, boolean isShortcut, UserHandle userHandle) {
613 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
614 title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100615 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
616 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100617 context.startActivityAsUser(intent, userHandle);
618 }
619
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700620 /**
621 * Build an Intent to launch a new activity showing the selected fragment.
622 * The implementation constructs an Intent that re-launches the current activity with the
623 * appropriate arguments to display the fragment.
624 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700625 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700626 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000627 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700628 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700629 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700630 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700631 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700632 * @return Returns an Intent that can be launched to display the given
633 * fragment.
634 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000635 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700636 Bundle args, int titleResId, CharSequence title, boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700637 Intent intent = new Intent(Intent.ACTION_MAIN);
638 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000639 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700640 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700641 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700642 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700643 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700644 return intent;
645 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100646
647 /**
648 * Returns the managed profile of the current user or null if none found.
649 */
650 public static UserHandle getManagedProfile(UserManager userManager) {
651 List<UserHandle> userProfiles = userManager.getUserProfiles();
652 final int count = userProfiles.size();
653 for (int i = 0; i < count; i++) {
654 final UserHandle profile = userProfiles.get(i);
655 if (profile.getIdentifier() == userManager.getUserHandle()) {
656 continue;
657 }
658 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
659 if (userInfo.isManagedProfile()) {
660 return profile;
661 }
662 }
663 return null;
664 }
665
666 /**
667 * Returns true if the current profile is a managed one.
668 */
669 public static boolean isManagedProfile(UserManager userManager) {
670 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
671 return currentUser.isManagedProfile();
672 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100673
674 /**
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100675 * Creates a {@link UserSpinnerAdapter} if there is more than one profile on the device.
676 *
677 * <p> The adapter can be used to populate a spinner that switches between the Settings
678 * app on the different profiles.
679 *
680 * @return a {@link UserSpinnerAdapter} or null if there is only one profile.
681 */
682 public static UserSpinnerAdapter createUserSpinnerAdapter(UserManager userManager,
683 Context context) {
684 List<UserHandle> userProfiles = userManager.getUserProfiles();
685 if (userProfiles.size() < 2) {
686 return null;
687 }
688
689 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
690 // The first option should be the current profile
691 userProfiles.remove(myUserHandle);
692 userProfiles.add(0, myUserHandle);
693
694 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
695 final int count = userProfiles.size();
696 for (int i = 0; i < count; i++) {
697 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
698 }
699 return new UserSpinnerAdapter(context, userDetails);
700 }
701
702 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100703 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100704 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100705 * The target user can be either the current user, the user that launched this activity or
706 * the user contained as an extra in the arguments or intent extras.
707 *
708 * Note: This is secure in the sense that it only returns a target user different to the current
709 * one if the app launching this activity is the Settings app itself, running in the same user
710 * 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 +0100711 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100712 public static UserHandle getSecureTargetUser(IBinder activityToken,
713 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
714 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
715 IActivityManager am = ActivityManagerNative.getDefault();
716 try {
717 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
718 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
719
720 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
721 am.getLaunchedFromUid(activityToken)));
722 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
723 // Check it's secure
724 if (isProfileOf(um, launchedFromUser)) {
725 return launchedFromUser;
726 }
727 }
728 UserHandle extrasUser = intentExtras != null
729 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
730 if (extrasUser != null && !extrasUser.equals(currentUser)) {
731 // Check it's secure
732 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
733 return extrasUser;
734 }
735 }
736 UserHandle argumentsUser = arguments != null
737 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
738 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
739 // Check it's secure
740 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
741 return argumentsUser;
742 }
743 }
744 } catch (RemoteException e) {
745 // Should not happen
746 Log.v(TAG, "Could not talk to activity manager.", e);
747 }
748 return currentUser;
749 }
750
751 /**
752 * Returns the target user for a Settings activity.
753 *
754 * The target user can be either the current user, the user that launched this activity or
755 * the user contained as an extra in the arguments or intent extras.
756 *
757 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
758 * possible.
759 *
760 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
761 */
762 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
763 @Nullable Bundle intentExtras) {
764 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
765 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100766 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100767 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
768 am.getLaunchedFromUid(activityToken)));
769 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
770 return launchedFromUser;
771 }
772 UserHandle extrasUser = intentExtras != null
773 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
774 if (extrasUser != null && !extrasUser.equals(currentUser)) {
775 return extrasUser;
776 }
777 UserHandle argumentsUser = arguments != null
778 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
779 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
780 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100781 }
782 } catch (RemoteException e) {
783 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100784 Log.v(TAG, "Could not talk to activity manager.", e);
785 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100786 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100787 return currentUser;
788 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100789
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100790 /**
791 * Returns true if the user provided is in the same profiles group as the current user.
792 */
793 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
794 if (um == null || otherUser == null) return false;
795 return (UserHandle.myUserId() == otherUser.getIdentifier())
796 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100797 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530798
799 /**
800 * Creates a dialog to confirm with the user if it's ok to remove the user
801 * and delete all the data.
802 *
803 * @param context a Context object
804 * @param removingUserId The userId of the user to remove
805 * @param onConfirmListener Callback object for positive action
806 * @return the created Dialog
807 */
808 public static Dialog createRemoveConfirmationDialog(Context context, int removingUserId,
809 DialogInterface.OnClickListener onConfirmListener) {
810 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
811 UserInfo userInfo = um.getUserInfo(removingUserId);
Alexandra Gherghina4c962672014-08-22 11:17:29 +0100812 int titleResId;
813 int messageResId;
814 if (UserHandle.myUserId() == removingUserId) {
815 titleResId = R.string.user_confirm_remove_self_title;
816 messageResId = R.string.user_confirm_remove_self_message;
817 } else if (userInfo.isRestricted()) {
818 titleResId = R.string.user_profile_confirm_remove_title;
819 messageResId = R.string.user_profile_confirm_remove_message;
820 } else if (userInfo.isManagedProfile()) {
821 titleResId = R.string.work_profile_confirm_remove_title;
822 messageResId = R.string.work_profile_confirm_remove_message;
823 } else {
824 titleResId = R.string.user_confirm_remove_title;
825 messageResId = R.string.user_confirm_remove_message;
826 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530827 Dialog dlg = new AlertDialog.Builder(context)
Alexandra Gherghina4c962672014-08-22 11:17:29 +0100828 .setTitle(titleResId)
829 .setMessage(messageResId)
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530830 .setPositiveButton(R.string.user_delete_button,
831 onConfirmListener)
832 .setNegativeButton(android.R.string.cancel, null)
833 .create();
834 return dlg;
835 }
Andres Moralesce249fe2014-07-07 16:58:16 -0700836
837 /**
838 * Returns whether or not this device is able to be OEM unlocked.
839 */
840 static boolean isOemUnlockEnabled(Context context) {
841 PersistentDataBlockManager manager =(PersistentDataBlockManager)
842 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
843 return manager.getOemUnlockEnabled();
844 }
845
846 /**
847 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
848 * devices allow users to flash other OSes to them.
849 */
850 static void setOemUnlockEnabled(Context context, boolean enabled) {
851 PersistentDataBlockManager manager =(PersistentDataBlockManager)
852 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
853 manager.setOemUnlockEnabled(enabled);
854 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100855
856 /**
857 * Returns a circular icon for a user.
858 */
859 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100860 if (user.iconPath != null) {
861 Bitmap icon = um.getUserIcon(user.id);
862 if (icon != null) {
863 return CircleFramedDrawable.getInstance(context, icon);
864 }
865 }
866 return UserIcons.getDefaultUserIcon(user.id, /* light= */ false);
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100867 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700868
869 /**
870 * Return whether or not the user should have a SIM Cards option in Settings.
871 * TODO: Change back to returning true if count is greater than one after testing.
872 * TODO: See bug 16533525.
873 */
874 public static boolean showSimCardTile(Context context) {
875 final TelephonyManager tm =
876 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
877
PauloftheWest9998f472014-09-08 11:08:41 -0700878 // TODO: Uncomment to re-enable SimSettings.
Wink Savilledbd052e2014-10-02 15:54:21 -0700879 return tm.getSimCount() > 0;
880 //return false;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700881 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200882
883 /**
884 * Determine whether a package is a "system package", in which case certain things (like
885 * disabling notifications or disabling the package altogether) should be disallowed.
886 */
887 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
888 if (sSystemSignature == null) {
889 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
890 }
891 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
892 }
893
894 private static Signature[] sSystemSignature;
895
896 private static Signature getFirstSignature(PackageInfo pkg) {
897 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
898 return pkg.signatures[0];
899 }
900 return null;
901 }
902
903 private static Signature getSystemSignature(PackageManager pm) {
904 try {
905 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
906 return getFirstSignature(sys);
907 } catch (NameNotFoundException e) {
908 }
909 return null;
910 }
911
Elliott Hughes7253df32014-09-02 17:10:14 -0700912 /**
913 * Returns elapsed time for the given millis, in the following format:
914 * 2d 5h 40m 29s
915 * @param context the application context
916 * @param millis the elapsed time in milli seconds
917 * @param withSeconds include seconds?
918 * @return the formatted elapsed time
919 */
920 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
921 StringBuilder sb = new StringBuilder();
922 int seconds = (int) Math.floor(millis / 1000);
923 if (!withSeconds) {
924 // Round up.
925 seconds += 30;
926 }
927
928 int days = 0, hours = 0, minutes = 0;
929 if (seconds >= SECONDS_PER_DAY) {
930 days = seconds / SECONDS_PER_DAY;
931 seconds -= days * SECONDS_PER_DAY;
932 }
933 if (seconds >= SECONDS_PER_HOUR) {
934 hours = seconds / SECONDS_PER_HOUR;
935 seconds -= hours * SECONDS_PER_HOUR;
936 }
937 if (seconds >= SECONDS_PER_MINUTE) {
938 minutes = seconds / SECONDS_PER_MINUTE;
939 seconds -= minutes * SECONDS_PER_MINUTE;
940 }
941 if (withSeconds) {
942 if (days > 0) {
943 sb.append(context.getString(R.string.battery_history_days,
944 days, hours, minutes, seconds));
945 } else if (hours > 0) {
946 sb.append(context.getString(R.string.battery_history_hours,
947 hours, minutes, seconds));
948 } else if (minutes > 0) {
949 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
950 } else {
951 sb.append(context.getString(R.string.battery_history_seconds, seconds));
952 }
953 } else {
954 if (days > 0) {
955 sb.append(context.getString(R.string.battery_history_days_no_seconds,
956 days, hours, minutes));
957 } else if (hours > 0) {
958 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
959 hours, minutes));
960 } else {
961 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
962 }
963 }
964 return sb.toString();
965 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800966}