blob: e687bebcde892a25d395978496a1b51020547542 [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;
Wink Savilleca756612014-11-08 10:47:12 -080063import android.telephony.SubscriptionInfo;
PauloftheWest0a0daca2014-11-06 15:02:58 -080064import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070065import android.telephony.TelephonyManager;
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.UserIcons;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010074import com.android.settings.UserSpinnerAdapter.UserDetails;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070075import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010076import com.android.settings.drawable.CircleFramedDrawable;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070077
Amith Yamasaniae47ef42012-09-16 17:53:35 -070078import java.io.IOException;
79import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080080import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070081import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010082import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080083import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070084import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090085import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080086
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070087public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010088 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010089
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080090 /**
91 * Set the preference's title to the matching activity's label.
92 */
93 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
94
95 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090096 * The opacity level of a disabled icon.
97 */
98 public static final float DISABLED_ALPHA = 0.4f;
99
100 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700101 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
102 * 1 is most bad (red), the last value is least bad (green).
103 */
104 public static final int[] BADNESS_COLORS = new int[] {
105 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
106 0xfffabf2c, 0xff679e37, 0xff0a7f42
107 };
108
109 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200110 * Name of the meta-data item that should be set in the AndroidManifest.xml
111 * to specify the icon that should be displayed for the preference.
112 */
113 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
114
115 /**
116 * Name of the meta-data item that should be set in the AndroidManifest.xml
117 * to specify the title that should be displayed for the preference.
118 */
119 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
120
121 /**
122 * Name of the meta-data item that should be set in the AndroidManifest.xml
123 * to specify the summary text that should be displayed for the preference.
124 */
125 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
126
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100127 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
128
Elliott Hughes7253df32014-09-02 17:10:14 -0700129 private static final int SECONDS_PER_MINUTE = 60;
130 private static final int SECONDS_PER_HOUR = 60 * 60;
131 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
132
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200133 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800134 * Finds a matching activity for a preference's intent. If a matching
135 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800136 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800137 * @param context The context.
138 * @param parentPreferenceGroup The preference group that contains the
139 * preference whose intent is being resolved.
140 * @param preferenceKey The key of the preference whose intent is being
141 * resolved.
142 * @param flags 0 or one or more of
143 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
144 * .
145 * @return Whether an activity was found. If false, the preference was
146 * removed.
147 */
148 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
149 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800150
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800151 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
152 if (preference == null) {
153 return false;
154 }
Ying Wanga7188322010-01-04 18:45:10 -0800155
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800156 Intent intent = preference.getIntent();
157 if (intent != null) {
158 // Find the activity that is in the system image
159 PackageManager pm = context.getPackageManager();
160 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
161 int listSize = list.size();
162 for (int i = 0; i < listSize; i++) {
163 ResolveInfo resolveInfo = list.get(i);
164 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
165 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800166
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800167 // Replace the intent with this specific activity
168 preference.setIntent(new Intent().setClassName(
169 resolveInfo.activityInfo.packageName,
170 resolveInfo.activityInfo.name));
171
172 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
173 // Set the preference title to the activity's label
174 preference.setTitle(resolveInfo.loadLabel(pm));
175 }
Ying Wanga7188322010-01-04 18:45:10 -0800176
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800177 return true;
178 }
179 }
180 }
181
182 // Did not find a matching activity, so remove the preference
183 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800184
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900185 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800186 }
Ying Wanga7188322010-01-04 18:45:10 -0800187
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700188 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700189 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700190
191 Intent intent = tile.intent;
192 if (intent != null) {
193 // Find the activity that is in the system image
194 PackageManager pm = context.getPackageManager();
195 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
196 int listSize = list.size();
197 for (int i = 0; i < listSize; i++) {
198 ResolveInfo resolveInfo = list.get(i);
199 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
200 != 0) {
201 Drawable icon = null;
202 String title = null;
203 String summary = null;
204
205 // Get the activity's meta-data
206 try {
207 Resources res = pm.getResourcesForApplication(
208 resolveInfo.activityInfo.packageName);
209 Bundle metaData = resolveInfo.activityInfo.metaData;
210
211 if (res != null && metaData != null) {
Alan Viverette0ba89bd2014-10-10 10:58:58 -0700212 icon = res.getDrawable(
213 metaData.getInt(META_DATA_PREFERENCE_ICON), null);
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700214 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
215 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
216 }
217 } catch (NameNotFoundException e) {
218 // Ignore
219 } catch (NotFoundException e) {
220 // Ignore
221 }
222
223 // Set the preference title to the activity's label if no
224 // meta-data is found
225 if (TextUtils.isEmpty(title)) {
226 title = resolveInfo.loadLabel(pm).toString();
227 }
228
229 // Set icon, title and summary for the preference
230 // TODO:
231 //tile.icon = icon;
232 tile.title = title;
233 tile.summary = summary;
234 // Replace the intent with this specific activity
235 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
236 resolveInfo.activityInfo.name);
237
238 return true;
239 }
240 }
241 }
242
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700243 return false;
244 }
245
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200246 /**
Ying Wanga7188322010-01-04 18:45:10 -0800247 * Returns true if Monkey is running.
248 */
249 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700250 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800251 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700252
253 /**
254 * Returns whether the device is voice-capable (meaning, it is also a phone).
255 */
256 public static boolean isVoiceCapable(Context context) {
257 TelephonyManager telephony =
258 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
259 return telephony != null && telephony.isVoiceCapable();
260 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800261
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700262 public static boolean isWifiOnly(Context context) {
263 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
264 Context.CONNECTIVITY_SERVICE);
265 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800266 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800267
268 /**
269 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
270 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900271 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800272 */
273 public static String getWifiIpAddresses(Context context) {
274 ConnectivityManager cm = (ConnectivityManager)
275 context.getSystemService(Context.CONNECTIVITY_SERVICE);
276 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700277 return formatIpAddresses(prop);
278 }
279
280 /**
281 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
282 * addresses.
283 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900284 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700285 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900286 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700287 LinkProperties prop = cm.getActiveLinkProperties();
288 return formatIpAddresses(prop);
289 }
290
291 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800292 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900293 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800294 // If there are no entries, return null
295 if (!iter.hasNext()) return null;
296 // Concatenate all available addresses, comma separated
297 String addresses = "";
298 while (iter.hasNext()) {
299 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900300 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800301 }
302 return addresses;
303 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900304
305 public static Locale createLocaleFromString(String localeStr) {
306 // TODO: is there a better way to actually construct a locale that will match?
307 // The main problem is, on top of Java specs, locale.toString() and
308 // new Locale(locale.toString()).toString() do not return equal() strings in
309 // many cases, because the constructor takes the only string as the language
310 // code. So : new Locale("en", "US").toString() => "en_US"
311 // And : new Locale("en_US").toString() => "en_us"
312 if (null == localeStr)
313 return Locale.getDefault();
314 String[] brokenDownLocale = localeStr.split("_", 3);
315 // split may not return a 0-length array.
316 if (1 == brokenDownLocale.length) {
317 return new Locale(brokenDownLocale[0]);
318 } else if (2 == brokenDownLocale.length) {
319 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
320 } else {
321 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
322 }
323 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700324
Elliott Hughes7253df32014-09-02 17:10:14 -0700325 /** Formats the ratio of amount/total as a percentage. */
326 public static String formatPercentage(long amount, long total) {
327 return formatPercentage(((double) amount) / total);
328 }
329
330 /** Formats an integer from 0..100 as a percentage. */
331 public static String formatPercentage(int percentage) {
332 return formatPercentage(((double) percentage) / 100.0);
333 }
334
335 /** Formats a double from 0.0..1.0 as a percentage. */
336 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700337 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700338 }
339
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900340 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
341 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
342 }
343
Amith Yamasania4379d62011-07-22 10:34:58 -0700344 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700345 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700346 }
347
348 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900349 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
350 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700351 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700352 }
353
354 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
355 final Intent intent = batteryChangedIntent;
356
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900357 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
358 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
359 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700360 String statusString;
361 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700362 int resId;
363 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
364 resId = R.string.battery_info_status_charging_ac;
365 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
366 resId = R.string.battery_info_status_charging_usb;
367 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
368 resId = R.string.battery_info_status_charging_wireless;
369 } else {
370 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700371 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700372 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700373 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
374 statusString = res.getString(R.string.battery_info_status_discharging);
375 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
376 statusString = res.getString(R.string.battery_info_status_not_charging);
377 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
378 statusString = res.getString(R.string.battery_info_status_full);
379 } else {
380 statusString = res.getString(R.string.battery_info_status_unknown);
381 }
382
383 return statusString;
384 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700385
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800386 public static void forcePrepareCustomPreferencesList(
387 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
388 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
389 list.setClipToPadding(false);
390 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
391 }
392
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700393 /**
394 * Prepare a custom preferences layout, moving padding to {@link ListView}
395 * when outside scrollbars are requested. Usually used to display
396 * {@link ListView} and {@link TabWidget} with correct padding.
397 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700398 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800399 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700400 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700401 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700402 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700403 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700404 final int paddingBottom = res.getDimensionPixelSize(
405 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700406
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700407 if (parent instanceof PreferenceFrameLayout) {
408 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
409
410 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
411 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
412 } else {
413 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
414 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700415 }
416 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700417
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700418 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700419 final Resources res = view.getResources();
420 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700421
422 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
423 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700424 final int paddingBottom = res.getDimensionPixelSize(
425 com.android.internal.R.dimen.preference_fragment_padding_bottom);
426
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700427 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700428 }
429
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700430 /**
431 * Return string resource that best describes combination of tethering
432 * options available on this device.
433 */
434 public static int getTetheringLabel(ConnectivityManager cm) {
435 String[] usbRegexs = cm.getTetherableUsbRegexs();
436 String[] wifiRegexs = cm.getTetherableWifiRegexs();
437 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
438
439 boolean usbAvailable = usbRegexs.length != 0;
440 boolean wifiAvailable = wifiRegexs.length != 0;
441 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
442
443 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
444 return R.string.tether_settings_title_all;
445 } else if (wifiAvailable && usbAvailable) {
446 return R.string.tether_settings_title_all;
447 } else if (wifiAvailable && bluetoothAvailable) {
448 return R.string.tether_settings_title_all;
449 } else if (wifiAvailable) {
450 return R.string.tether_settings_title_wifi;
451 } else if (usbAvailable && bluetoothAvailable) {
452 return R.string.tether_settings_title_usb_bluetooth;
453 } else if (usbAvailable) {
454 return R.string.tether_settings_title_usb;
455 } else {
456 return R.string.tether_settings_title_bluetooth;
457 }
458 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700459
460 /* Used by UserSettings as well. Call this on a non-ui thread. */
461 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
462 Uri contactUri = Profile.CONTENT_URI;
463
464 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
465 context.getContentResolver(),
466 contactUri, true);
467 // If there's no profile photo, assign a default avatar
468 if (avatarDataStream == null) {
469 return false;
470 }
471 int userId = user != null ? user.id : UserHandle.myUserId();
472 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700473 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
474 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700475 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700476 avatarDataStream.close();
477 } catch (IOException ioe) { }
478 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700479 }
480
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700481 public static String getMeProfileName(Context context, boolean full) {
482 if (full) {
483 return getProfileDisplayName(context);
484 } else {
485 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700486 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700487 }
488
489 private static String getShorterNameIfPossible(Context context) {
490 final String given = getLocalProfileGivenName(context);
491 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
492 }
493
494 private static String getLocalProfileGivenName(Context context) {
495 final ContentResolver cr = context.getContentResolver();
496
497 // Find the raw contact ID for the local ME profile raw contact.
498 final long localRowProfileId;
499 final Cursor localRawProfile = cr.query(
500 Profile.CONTENT_RAW_CONTACTS_URI,
501 new String[] {RawContacts._ID},
502 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
503 RawContacts.ACCOUNT_NAME + " IS NULL",
504 null, null);
505 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700506
507 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700508 if (!localRawProfile.moveToFirst()) {
509 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700510 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700511 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700512 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700513 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700514 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700515
516 // Find the structured name for the raw contact.
517 final Cursor structuredName = cr.query(
518 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
519 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
520 CommonDataKinds.StructuredName.FAMILY_NAME},
521 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
522 null, null);
523 if (structuredName == null) return null;
524
525 try {
526 if (!structuredName.moveToFirst()) {
527 return null;
528 }
529 String partialName = structuredName.getString(0);
530 if (TextUtils.isEmpty(partialName)) {
531 partialName = structuredName.getString(1);
532 }
533 return partialName;
534 } finally {
535 structuredName.close();
536 }
537 }
538
539 private static final String getProfileDisplayName(Context context) {
540 final ContentResolver cr = context.getContentResolver();
541 final Cursor profile = cr.query(Profile.CONTENT_URI,
542 new String[] {Profile.DISPLAY_NAME}, null, null, null);
543 if (profile == null) return null;
544
545 try {
546 if (!profile.moveToFirst()) {
547 return null;
548 }
549 return profile.getString(0);
550 } finally {
551 profile.close();
552 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700553 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700554
555 /** Not global warming, it's global change warning. */
556 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
557 final Runnable positiveAction) {
558 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
559 builder.setTitle(titleResId);
560 builder.setMessage(R.string.global_change_warning);
561 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
562 @Override
563 public void onClick(DialogInterface dialog, int which) {
564 positiveAction.run();
565 }
566 });
567 builder.setNegativeButton(android.R.string.cancel, null);
568
569 return builder.create();
570 }
571
572 public static boolean hasMultipleUsers(Context context) {
573 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
574 .getUsers().size() > 1;
575 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700576
577 /**
578 * Start a new instance of the activity, showing only the given fragment.
579 * When launched in this mode, the given preference fragment will be instantiated and fill the
580 * entire activity.
581 *
582 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000583 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700584 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700585 * @param resultTo Option fragment that should receive the result of the activity launch.
586 * @param resultRequestCode If resultTo is non-null, this is the request code in which
587 * to report the result.
588 * @param titleResId resource id for the String to display for the title of this set
589 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700590 * @param title String to display for the title of this set of preferences.
591 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000592 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700593 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700594 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
595 titleResId, title, false /* not a shortcut */);
596 }
597
598 public static void startWithFragment(Context context, String fragmentName, Bundle args,
599 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title,
600 boolean isShortcut) {
601 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
602 title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700603 if (resultTo == null) {
604 context.startActivity(intent);
605 } else {
606 resultTo.startActivityForResult(intent, resultRequestCode);
607 }
608 }
609
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100610 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
611 int titleResId, CharSequence title, boolean isShortcut, UserHandle userHandle) {
612 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
613 title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100614 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
615 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100616 context.startActivityAsUser(intent, userHandle);
617 }
618
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700619 /**
620 * Build an Intent to launch a new activity showing the selected fragment.
621 * The implementation constructs an Intent that re-launches the current activity with the
622 * appropriate arguments to display the fragment.
623 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700624 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700625 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000626 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700627 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700628 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700629 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700630 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700631 * @return Returns an Intent that can be launched to display the given
632 * fragment.
633 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000634 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700635 Bundle args, int titleResId, CharSequence title, boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700636 Intent intent = new Intent(Intent.ACTION_MAIN);
637 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000638 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700639 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700640 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700641 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700642 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700643 return intent;
644 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100645
646 /**
647 * Returns the managed profile of the current user or null if none found.
648 */
649 public static UserHandle getManagedProfile(UserManager userManager) {
650 List<UserHandle> userProfiles = userManager.getUserProfiles();
651 final int count = userProfiles.size();
652 for (int i = 0; i < count; i++) {
653 final UserHandle profile = userProfiles.get(i);
654 if (profile.getIdentifier() == userManager.getUserHandle()) {
655 continue;
656 }
657 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
658 if (userInfo.isManagedProfile()) {
659 return profile;
660 }
661 }
662 return null;
663 }
664
665 /**
666 * Returns true if the current profile is a managed one.
667 */
668 public static boolean isManagedProfile(UserManager userManager) {
669 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
670 return currentUser.isManagedProfile();
671 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100672
673 /**
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100674 * Creates a {@link UserSpinnerAdapter} if there is more than one profile on the device.
675 *
676 * <p> The adapter can be used to populate a spinner that switches between the Settings
677 * app on the different profiles.
678 *
679 * @return a {@link UserSpinnerAdapter} or null if there is only one profile.
680 */
681 public static UserSpinnerAdapter createUserSpinnerAdapter(UserManager userManager,
682 Context context) {
683 List<UserHandle> userProfiles = userManager.getUserProfiles();
684 if (userProfiles.size() < 2) {
685 return null;
686 }
687
688 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
689 // The first option should be the current profile
690 userProfiles.remove(myUserHandle);
691 userProfiles.add(0, myUserHandle);
692
693 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
694 final int count = userProfiles.size();
695 for (int i = 0; i < count; i++) {
696 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
697 }
698 return new UserSpinnerAdapter(context, userDetails);
699 }
700
701 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100702 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100703 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100704 * The target user can be either the current user, the user that launched this activity or
705 * the user contained as an extra in the arguments or intent extras.
706 *
707 * Note: This is secure in the sense that it only returns a target user different to the current
708 * one if the app launching this activity is the Settings app itself, running in the same user
709 * 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 +0100710 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100711 public static UserHandle getSecureTargetUser(IBinder activityToken,
712 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
713 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
714 IActivityManager am = ActivityManagerNative.getDefault();
715 try {
716 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
717 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
718
719 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
720 am.getLaunchedFromUid(activityToken)));
721 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
722 // Check it's secure
723 if (isProfileOf(um, launchedFromUser)) {
724 return launchedFromUser;
725 }
726 }
727 UserHandle extrasUser = intentExtras != null
728 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
729 if (extrasUser != null && !extrasUser.equals(currentUser)) {
730 // Check it's secure
731 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
732 return extrasUser;
733 }
734 }
735 UserHandle argumentsUser = arguments != null
736 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
737 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
738 // Check it's secure
739 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
740 return argumentsUser;
741 }
742 }
743 } catch (RemoteException e) {
744 // Should not happen
745 Log.v(TAG, "Could not talk to activity manager.", e);
746 }
747 return currentUser;
748 }
749
750 /**
751 * Returns the target user for a Settings activity.
752 *
753 * The target user can be either the current user, the user that launched this activity or
754 * the user contained as an extra in the arguments or intent extras.
755 *
756 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
757 * possible.
758 *
759 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
760 */
761 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
762 @Nullable Bundle intentExtras) {
763 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
764 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100765 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100766 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
767 am.getLaunchedFromUid(activityToken)));
768 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
769 return launchedFromUser;
770 }
771 UserHandle extrasUser = intentExtras != null
772 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
773 if (extrasUser != null && !extrasUser.equals(currentUser)) {
774 return extrasUser;
775 }
776 UserHandle argumentsUser = arguments != null
777 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
778 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
779 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100780 }
781 } catch (RemoteException e) {
782 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100783 Log.v(TAG, "Could not talk to activity manager.", e);
784 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100785 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100786 return currentUser;
787 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100788
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100789 /**
790 * Returns true if the user provided is in the same profiles group as the current user.
791 */
792 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
793 if (um == null || otherUser == null) return false;
794 return (UserHandle.myUserId() == otherUser.getIdentifier())
795 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100796 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530797
798 /**
799 * Creates a dialog to confirm with the user if it's ok to remove the user
800 * and delete all the data.
801 *
802 * @param context a Context object
803 * @param removingUserId The userId of the user to remove
804 * @param onConfirmListener Callback object for positive action
805 * @return the created Dialog
806 */
807 public static Dialog createRemoveConfirmationDialog(Context context, int removingUserId,
808 DialogInterface.OnClickListener onConfirmListener) {
809 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
810 UserInfo userInfo = um.getUserInfo(removingUserId);
Alexandra Gherghina4c962672014-08-22 11:17:29 +0100811 int titleResId;
812 int messageResId;
813 if (UserHandle.myUserId() == removingUserId) {
814 titleResId = R.string.user_confirm_remove_self_title;
815 messageResId = R.string.user_confirm_remove_self_message;
816 } else if (userInfo.isRestricted()) {
817 titleResId = R.string.user_profile_confirm_remove_title;
818 messageResId = R.string.user_profile_confirm_remove_message;
819 } else if (userInfo.isManagedProfile()) {
820 titleResId = R.string.work_profile_confirm_remove_title;
821 messageResId = R.string.work_profile_confirm_remove_message;
822 } else {
823 titleResId = R.string.user_confirm_remove_title;
824 messageResId = R.string.user_confirm_remove_message;
825 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530826 Dialog dlg = new AlertDialog.Builder(context)
Alexandra Gherghina4c962672014-08-22 11:17:29 +0100827 .setTitle(titleResId)
828 .setMessage(messageResId)
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530829 .setPositiveButton(R.string.user_delete_button,
830 onConfirmListener)
831 .setNegativeButton(android.R.string.cancel, null)
832 .create();
833 return dlg;
834 }
Andres Moralesce249fe2014-07-07 16:58:16 -0700835
836 /**
837 * Returns whether or not this device is able to be OEM unlocked.
838 */
839 static boolean isOemUnlockEnabled(Context context) {
840 PersistentDataBlockManager manager =(PersistentDataBlockManager)
841 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
842 return manager.getOemUnlockEnabled();
843 }
844
845 /**
846 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
847 * devices allow users to flash other OSes to them.
848 */
849 static void setOemUnlockEnabled(Context context, boolean enabled) {
850 PersistentDataBlockManager manager =(PersistentDataBlockManager)
851 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
852 manager.setOemUnlockEnabled(enabled);
853 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100854
855 /**
856 * Returns a circular icon for a user.
857 */
858 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000859 if (user.isManagedProfile()) {
860 // We use predefined values for managed profiles
861 Bitmap b = BitmapFactory.decodeResource(context.getResources(),
862 com.android.internal.R.drawable.ic_corp_icon);
863 return CircleFramedDrawable.getInstance(context, b);
864 }
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100865 if (user.iconPath != null) {
866 Bitmap icon = um.getUserIcon(user.id);
867 if (icon != null) {
868 return CircleFramedDrawable.getInstance(context, icon);
869 }
870 }
871 return UserIcons.getDefaultUserIcon(user.id, /* light= */ false);
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100872 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700873
874 /**
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000875 * Returns a label for the user, in the form of "User: user name" or "Work profile".
876 */
877 public static String getUserLabel(Context context, UserInfo info) {
878 if (info.isManagedProfile()) {
879 // We use predefined values for managed profiles
880 return context.getString(R.string.managed_user_title);
881 }
882 String name = info != null ? info.name : null;
883 if (name == null && info != null) {
884 name = Integer.toString(info.id);
885 } else if (info == null) {
886 name = context.getString(R.string.unknown);
887 }
888 return context.getResources().getString(R.string.running_process_item_user_label, name);
889 }
890
891 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700892 * Return whether or not the user should have a SIM Cards option in Settings.
893 * TODO: Change back to returning true if count is greater than one after testing.
894 * TODO: See bug 16533525.
895 */
896 public static boolean showSimCardTile(Context context) {
897 final TelephonyManager tm =
898 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
899
Wink Savilledbd052e2014-10-02 15:54:21 -0700900 return tm.getSimCount() > 0;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700901 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200902
903 /**
904 * Determine whether a package is a "system package", in which case certain things (like
905 * disabling notifications or disabling the package altogether) should be disallowed.
906 */
907 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
908 if (sSystemSignature == null) {
909 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
910 }
911 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
912 }
913
914 private static Signature[] sSystemSignature;
915
916 private static Signature getFirstSignature(PackageInfo pkg) {
917 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
918 return pkg.signatures[0];
919 }
920 return null;
921 }
922
923 private static Signature getSystemSignature(PackageManager pm) {
924 try {
925 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
926 return getFirstSignature(sys);
927 } catch (NameNotFoundException e) {
928 }
929 return null;
930 }
931
Elliott Hughes7253df32014-09-02 17:10:14 -0700932 /**
933 * Returns elapsed time for the given millis, in the following format:
934 * 2d 5h 40m 29s
935 * @param context the application context
936 * @param millis the elapsed time in milli seconds
937 * @param withSeconds include seconds?
938 * @return the formatted elapsed time
939 */
940 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
941 StringBuilder sb = new StringBuilder();
942 int seconds = (int) Math.floor(millis / 1000);
943 if (!withSeconds) {
944 // Round up.
945 seconds += 30;
946 }
947
948 int days = 0, hours = 0, minutes = 0;
949 if (seconds >= SECONDS_PER_DAY) {
950 days = seconds / SECONDS_PER_DAY;
951 seconds -= days * SECONDS_PER_DAY;
952 }
953 if (seconds >= SECONDS_PER_HOUR) {
954 hours = seconds / SECONDS_PER_HOUR;
955 seconds -= hours * SECONDS_PER_HOUR;
956 }
957 if (seconds >= SECONDS_PER_MINUTE) {
958 minutes = seconds / SECONDS_PER_MINUTE;
959 seconds -= minutes * SECONDS_PER_MINUTE;
960 }
961 if (withSeconds) {
962 if (days > 0) {
963 sb.append(context.getString(R.string.battery_history_days,
964 days, hours, minutes, seconds));
965 } else if (hours > 0) {
966 sb.append(context.getString(R.string.battery_history_hours,
967 hours, minutes, seconds));
968 } else if (minutes > 0) {
969 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
970 } else {
971 sb.append(context.getString(R.string.battery_history_seconds, seconds));
972 }
973 } else {
974 if (days > 0) {
975 sb.append(context.getString(R.string.battery_history_days_no_seconds,
976 days, hours, minutes));
977 } else if (hours > 0) {
978 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
979 hours, minutes));
980 } else {
981 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
982 }
983 }
984 return sb.toString();
985 }
PauloftheWest0a0daca2014-11-06 15:02:58 -0800986
987 /**
988 * finds a record with subId.
989 * Since the number of SIMs are few, an array is fine.
990 */
Wink Savilleca756612014-11-08 10:47:12 -0800991 public static SubscriptionInfo findRecordBySubId(final int subId) {
992 final List<SubscriptionInfo> subInfoList =
993 SubscriptionManager.getActiveSubscriptionInfoList();
PauloftheWest0a0daca2014-11-06 15:02:58 -0800994 final int subInfoLength = subInfoList.size();
995
996 for (int i = 0; i < subInfoLength; ++i) {
Wink Savilleca756612014-11-08 10:47:12 -0800997 final SubscriptionInfo sir = subInfoList.get(i);
PauloftheWest0a0daca2014-11-06 15:02:58 -0800998 if (sir != null && sir.getSubscriptionId() == subId) {
999 return sir;
1000 }
1001 }
1002
1003 return null;
1004 }
1005
1006 /**
1007 * finds a record with slotId.
1008 * Since the number of SIMs are few, an array is fine.
1009 */
Wink Savilleca756612014-11-08 10:47:12 -08001010 public static SubscriptionInfo findRecordBySlotId(final int slotId) {
1011 final List<SubscriptionInfo> subInfoList =
1012 SubscriptionManager.getActiveSubscriptionInfoList();
PauloftheWest0a0daca2014-11-06 15:02:58 -08001013 final int subInfoLength = subInfoList.size();
1014
1015 for (int i = 0; i < subInfoLength; ++i) {
Wink Savilleca756612014-11-08 10:47:12 -08001016 final SubscriptionInfo sir = subInfoList.get(i);
PauloftheWest0a0daca2014-11-06 15:02:58 -08001017 if (sir.getSimSlotIndex() == slotId) {
1018 //Right now we take the first subscription on a SIM.
1019 return sir;
1020 }
1021 }
1022
1023 return null;
1024 }
1025
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -08001026}