blob: 5a2618eda80a00a1fb5c1235970735fdf05a9ed5 [file] [log] [blame]
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -08001/**
2 * Copyright (C) 2007 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy
6 * of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16
17package com.android.settings;
18
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010019import static android.content.Intent.EXTRA_USER;
20
21import android.annotation.Nullable;
Amith Yamasaniae697552011-09-27 11:33:17 -070022import android.app.ActivityManager;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010023import android.app.ActivityManagerNative;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070024import android.app.AlertDialog;
25import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070026import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010027import android.app.IActivityManager;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070028import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080029import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070030import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080031import android.content.Intent;
32import android.content.pm.ApplicationInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020033import android.content.pm.PackageInfo;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080034import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070035import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070036import android.content.pm.ResolveInfo;
Dan Sandlerb58b5122014-09-02 18:31:49 +020037import android.content.pm.Signature;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070038import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020039import android.content.res.Resources;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000040import android.content.res.TypedArray;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020041import android.content.res.Resources.NotFoundException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070042import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070043import android.graphics.Bitmap;
44import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020045import android.graphics.drawable.Drawable;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080046import android.net.ConnectivityManager;
47import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070048import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070049import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020050import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010051import android.os.IBinder;
52import android.os.RemoteException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070053import android.os.UserHandle;
54import android.os.UserManager;
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -080055import android.os.storage.StorageManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080056import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070057import android.preference.PreferenceFrameLayout;
58import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070059import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070060import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070061import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070062import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070063import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070064import android.service.persistentdata.PersistentDataBlockManager;
Wink Savilleca756612014-11-08 10:47:12 -080065import android.telephony.SubscriptionInfo;
PauloftheWest0a0daca2014-11-06 15:02:58 -080066import android.telephony.SubscriptionManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070067import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020068import android.text.TextUtils;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010069import android.util.Log;
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +000070import android.view.LayoutInflater;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070071import android.view.View;
72import android.view.ViewGroup;
73import android.widget.ListView;
74import android.widget.TabWidget;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010075
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +010076import com.android.internal.util.UserIcons;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010077import com.android.settings.UserSpinnerAdapter.UserDetails;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070078import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010079import com.android.settings.drawable.CircleFramedDrawable;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070080
Amith Yamasaniae47ef42012-09-16 17:53:35 -070081import java.io.IOException;
82import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080083import java.net.InetAddress;
Elliott Hughes7253df32014-09-02 17:10:14 -070084import java.text.NumberFormat;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010085import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080086import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070087import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090088import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080089
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070090public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010091 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010092
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080093 /**
94 * Set the preference's title to the matching activity's label.
95 */
96 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
97
98 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090099 * The opacity level of a disabled icon.
100 */
101 public static final float DISABLED_ALPHA = 0.4f;
102
103 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -0700104 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
105 * 1 is most bad (red), the last value is least bad (green).
106 */
107 public static final int[] BADNESS_COLORS = new int[] {
108 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
109 0xfffabf2c, 0xff679e37, 0xff0a7f42
110 };
111
112 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200113 * Name of the meta-data item that should be set in the AndroidManifest.xml
114 * to specify the icon that should be displayed for the preference.
115 */
116 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
117
118 /**
119 * Name of the meta-data item that should be set in the AndroidManifest.xml
120 * to specify the title that should be displayed for the preference.
121 */
122 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
123
124 /**
125 * Name of the meta-data item that should be set in the AndroidManifest.xml
126 * to specify the summary text that should be displayed for the preference.
127 */
128 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
129
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100130 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
131
Elliott Hughes7253df32014-09-02 17:10:14 -0700132 private static final int SECONDS_PER_MINUTE = 60;
133 private static final int SECONDS_PER_HOUR = 60 * 60;
134 private static final int SECONDS_PER_DAY = 24 * 60 * 60;
135
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200136 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800137 * Finds a matching activity for a preference's intent. If a matching
138 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800139 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800140 * @param context The context.
141 * @param parentPreferenceGroup The preference group that contains the
142 * preference whose intent is being resolved.
143 * @param preferenceKey The key of the preference whose intent is being
144 * resolved.
145 * @param flags 0 or one or more of
146 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
147 * .
148 * @return Whether an activity was found. If false, the preference was
149 * removed.
150 */
151 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
152 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800153
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800154 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
155 if (preference == null) {
156 return false;
157 }
Ying Wanga7188322010-01-04 18:45:10 -0800158
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800159 Intent intent = preference.getIntent();
160 if (intent != null) {
161 // Find the activity that is in the system image
162 PackageManager pm = context.getPackageManager();
163 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
164 int listSize = list.size();
165 for (int i = 0; i < listSize; i++) {
166 ResolveInfo resolveInfo = list.get(i);
167 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
168 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800169
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800170 // Replace the intent with this specific activity
171 preference.setIntent(new Intent().setClassName(
172 resolveInfo.activityInfo.packageName,
173 resolveInfo.activityInfo.name));
174
175 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
176 // Set the preference title to the activity's label
177 preference.setTitle(resolveInfo.loadLabel(pm));
178 }
Ying Wanga7188322010-01-04 18:45:10 -0800179
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800180 return true;
181 }
182 }
183 }
184
185 // Did not find a matching activity, so remove the preference
186 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800187
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900188 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800189 }
Ying Wanga7188322010-01-04 18:45:10 -0800190
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700191 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700192 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700193
194 Intent intent = tile.intent;
195 if (intent != null) {
196 // Find the activity that is in the system image
197 PackageManager pm = context.getPackageManager();
198 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
199 int listSize = list.size();
200 for (int i = 0; i < listSize; i++) {
201 ResolveInfo resolveInfo = list.get(i);
202 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
203 != 0) {
204 Drawable icon = null;
205 String title = null;
206 String summary = null;
207
208 // Get the activity's meta-data
209 try {
210 Resources res = pm.getResourcesForApplication(
211 resolveInfo.activityInfo.packageName);
212 Bundle metaData = resolveInfo.activityInfo.metaData;
213
214 if (res != null && metaData != null) {
Alan Viverette0ba89bd2014-10-10 10:58:58 -0700215 icon = res.getDrawable(
216 metaData.getInt(META_DATA_PREFERENCE_ICON), null);
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700217 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
218 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
219 }
220 } catch (NameNotFoundException e) {
221 // Ignore
222 } catch (NotFoundException e) {
223 // Ignore
224 }
225
226 // Set the preference title to the activity's label if no
227 // meta-data is found
228 if (TextUtils.isEmpty(title)) {
229 title = resolveInfo.loadLabel(pm).toString();
230 }
231
232 // Set icon, title and summary for the preference
233 // TODO:
234 //tile.icon = icon;
235 tile.title = title;
236 tile.summary = summary;
237 // Replace the intent with this specific activity
238 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
239 resolveInfo.activityInfo.name);
240
241 return true;
242 }
243 }
244 }
245
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700246 return false;
247 }
248
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200249 /**
Ying Wanga7188322010-01-04 18:45:10 -0800250 * Returns true if Monkey is running.
251 */
252 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700253 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800254 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700255
256 /**
257 * Returns whether the device is voice-capable (meaning, it is also a phone).
258 */
259 public static boolean isVoiceCapable(Context context) {
260 TelephonyManager telephony =
261 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
262 return telephony != null && telephony.isVoiceCapable();
263 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800264
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700265 public static boolean isWifiOnly(Context context) {
266 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
267 Context.CONNECTIVITY_SERVICE);
268 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800269 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800270
271 /**
272 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
273 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900274 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800275 */
276 public static String getWifiIpAddresses(Context context) {
277 ConnectivityManager cm = (ConnectivityManager)
278 context.getSystemService(Context.CONNECTIVITY_SERVICE);
279 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700280 return formatIpAddresses(prop);
281 }
282
283 /**
284 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
285 * addresses.
286 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900287 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700288 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900289 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700290 LinkProperties prop = cm.getActiveLinkProperties();
291 return formatIpAddresses(prop);
292 }
293
294 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800295 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900296 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800297 // If there are no entries, return null
298 if (!iter.hasNext()) return null;
299 // Concatenate all available addresses, comma separated
300 String addresses = "";
301 while (iter.hasNext()) {
302 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900303 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800304 }
305 return addresses;
306 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900307
308 public static Locale createLocaleFromString(String localeStr) {
309 // TODO: is there a better way to actually construct a locale that will match?
310 // The main problem is, on top of Java specs, locale.toString() and
311 // new Locale(locale.toString()).toString() do not return equal() strings in
312 // many cases, because the constructor takes the only string as the language
313 // code. So : new Locale("en", "US").toString() => "en_US"
314 // And : new Locale("en_US").toString() => "en_us"
315 if (null == localeStr)
316 return Locale.getDefault();
317 String[] brokenDownLocale = localeStr.split("_", 3);
318 // split may not return a 0-length array.
319 if (1 == brokenDownLocale.length) {
320 return new Locale(brokenDownLocale[0]);
321 } else if (2 == brokenDownLocale.length) {
322 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
323 } else {
324 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
325 }
326 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700327
Elliott Hughes7253df32014-09-02 17:10:14 -0700328 /** Formats the ratio of amount/total as a percentage. */
329 public static String formatPercentage(long amount, long total) {
330 return formatPercentage(((double) amount) / total);
331 }
332
333 /** Formats an integer from 0..100 as a percentage. */
334 public static String formatPercentage(int percentage) {
335 return formatPercentage(((double) percentage) / 100.0);
336 }
337
338 /** Formats a double from 0.0..1.0 as a percentage. */
339 private static String formatPercentage(double percentage) {
Elliott Hughes83f013c2014-10-02 16:36:32 -0700340 return NumberFormat.getPercentInstance().format(percentage);
Elliott Hughes7253df32014-09-02 17:10:14 -0700341 }
342
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900343 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
344 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
345 }
346
Amith Yamasania4379d62011-07-22 10:34:58 -0700347 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Elliott Hughes7253df32014-09-02 17:10:14 -0700348 return formatPercentage(getBatteryLevel(batteryChangedIntent));
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700349 }
350
351 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900352 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
353 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700354 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700355 }
356
357 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
358 final Intent intent = batteryChangedIntent;
359
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900360 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
361 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
362 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700363 String statusString;
364 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700365 int resId;
366 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
367 resId = R.string.battery_info_status_charging_ac;
368 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
369 resId = R.string.battery_info_status_charging_usb;
370 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
371 resId = R.string.battery_info_status_charging_wireless;
372 } else {
373 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700374 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700375 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700376 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
377 statusString = res.getString(R.string.battery_info_status_discharging);
378 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
379 statusString = res.getString(R.string.battery_info_status_not_charging);
380 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
381 statusString = res.getString(R.string.battery_info_status_full);
382 } else {
383 statusString = res.getString(R.string.battery_info_status_unknown);
384 }
385
386 return statusString;
387 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700388
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800389 public static void forcePrepareCustomPreferencesList(
390 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
391 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
392 list.setClipToPadding(false);
393 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
394 }
395
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700396 /**
397 * Prepare a custom preferences layout, moving padding to {@link ListView}
398 * when outside scrollbars are requested. Usually used to display
399 * {@link ListView} and {@link TabWidget} with correct padding.
400 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700401 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800402 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700403 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700404 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700405 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700406 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700407 final int paddingBottom = res.getDimensionPixelSize(
408 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700409
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700410 if (parent instanceof PreferenceFrameLayout) {
411 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
412
413 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
414 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
415 } else {
416 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
417 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700418 }
419 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700420
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700421 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700422 final Resources res = view.getResources();
423 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700424
425 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
426 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700427 final int paddingBottom = res.getDimensionPixelSize(
428 com.android.internal.R.dimen.preference_fragment_padding_bottom);
429
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700430 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700431 }
432
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700433 /**
434 * Return string resource that best describes combination of tethering
435 * options available on this device.
436 */
437 public static int getTetheringLabel(ConnectivityManager cm) {
438 String[] usbRegexs = cm.getTetherableUsbRegexs();
439 String[] wifiRegexs = cm.getTetherableWifiRegexs();
440 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
441
442 boolean usbAvailable = usbRegexs.length != 0;
443 boolean wifiAvailable = wifiRegexs.length != 0;
444 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
445
446 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
447 return R.string.tether_settings_title_all;
448 } else if (wifiAvailable && usbAvailable) {
449 return R.string.tether_settings_title_all;
450 } else if (wifiAvailable && bluetoothAvailable) {
451 return R.string.tether_settings_title_all;
452 } else if (wifiAvailable) {
453 return R.string.tether_settings_title_wifi;
454 } else if (usbAvailable && bluetoothAvailable) {
455 return R.string.tether_settings_title_usb_bluetooth;
456 } else if (usbAvailable) {
457 return R.string.tether_settings_title_usb;
458 } else {
459 return R.string.tether_settings_title_bluetooth;
460 }
461 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700462
463 /* Used by UserSettings as well. Call this on a non-ui thread. */
464 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
465 Uri contactUri = Profile.CONTENT_URI;
466
467 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
468 context.getContentResolver(),
469 contactUri, true);
470 // If there's no profile photo, assign a default avatar
471 if (avatarDataStream == null) {
472 return false;
473 }
474 int userId = user != null ? user.id : UserHandle.myUserId();
475 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700476 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
477 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700478 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700479 avatarDataStream.close();
480 } catch (IOException ioe) { }
481 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700482 }
483
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700484 public static String getMeProfileName(Context context, boolean full) {
485 if (full) {
486 return getProfileDisplayName(context);
487 } else {
488 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700489 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700490 }
491
492 private static String getShorterNameIfPossible(Context context) {
493 final String given = getLocalProfileGivenName(context);
494 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
495 }
496
497 private static String getLocalProfileGivenName(Context context) {
498 final ContentResolver cr = context.getContentResolver();
499
500 // Find the raw contact ID for the local ME profile raw contact.
501 final long localRowProfileId;
502 final Cursor localRawProfile = cr.query(
503 Profile.CONTENT_RAW_CONTACTS_URI,
504 new String[] {RawContacts._ID},
505 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
506 RawContacts.ACCOUNT_NAME + " IS NULL",
507 null, null);
508 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700509
510 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700511 if (!localRawProfile.moveToFirst()) {
512 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700513 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700514 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700515 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700516 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700517 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700518
519 // Find the structured name for the raw contact.
520 final Cursor structuredName = cr.query(
521 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
522 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
523 CommonDataKinds.StructuredName.FAMILY_NAME},
524 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
525 null, null);
526 if (structuredName == null) return null;
527
528 try {
529 if (!structuredName.moveToFirst()) {
530 return null;
531 }
532 String partialName = structuredName.getString(0);
533 if (TextUtils.isEmpty(partialName)) {
534 partialName = structuredName.getString(1);
535 }
536 return partialName;
537 } finally {
538 structuredName.close();
539 }
540 }
541
542 private static final String getProfileDisplayName(Context context) {
543 final ContentResolver cr = context.getContentResolver();
544 final Cursor profile = cr.query(Profile.CONTENT_URI,
545 new String[] {Profile.DISPLAY_NAME}, null, null, null);
546 if (profile == null) return null;
547
548 try {
549 if (!profile.moveToFirst()) {
550 return null;
551 }
552 return profile.getString(0);
553 } finally {
554 profile.close();
555 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700556 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700557
558 /** Not global warming, it's global change warning. */
559 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
560 final Runnable positiveAction) {
561 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
562 builder.setTitle(titleResId);
563 builder.setMessage(R.string.global_change_warning);
564 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
565 @Override
566 public void onClick(DialogInterface dialog, int which) {
567 positiveAction.run();
568 }
569 });
570 builder.setNegativeButton(android.R.string.cancel, null);
571
572 return builder.create();
573 }
574
575 public static boolean hasMultipleUsers(Context context) {
576 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
577 .getUsers().size() > 1;
578 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700579
580 /**
581 * Start a new instance of the activity, showing only the given fragment.
582 * When launched in this mode, the given preference fragment will be instantiated and fill the
583 * entire activity.
584 *
585 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000586 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700587 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700588 * @param resultTo Option fragment that should receive the result of the activity launch.
589 * @param resultRequestCode If resultTo is non-null, this is the request code in which
590 * to report the result.
591 * @param titleResId resource id for the String to display for the title of this set
592 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700593 * @param title String to display for the title of this set of preferences.
594 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000595 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100596 Fragment resultTo, int resultRequestCode, int titleResId,
597 CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700598 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100599 null /* titleResPackageName */, titleResId, title, false /* not a shortcut */);
600 }
601
602 /**
603 * Start a new instance of the activity, showing only the given fragment.
604 * When launched in this mode, the given preference fragment will be instantiated and fill the
605 * entire activity.
606 *
607 * @param context The context.
608 * @param fragmentName The name of the fragment to display.
609 * @param args Optional arguments to supply to the fragment.
610 * @param resultTo Option fragment that should receive the result of the activity launch.
611 * @param resultRequestCode If resultTo is non-null, this is the request code in which
612 * to report the result.
613 * @param titleResPackageName Optional package name for the resource id of the title.
614 * @param titleResId resource id for the String to display for the title of this set
615 * of preferences.
616 * @param title String to display for the title of this set of preferences.
617 */
618 public static void startWithFragment(Context context, String fragmentName, Bundle args,
619 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
620 CharSequence title) {
621 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
622 titleResPackageName, titleResId, title, false /* not a shortcut */);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700623 }
624
625 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100626 Fragment resultTo, int resultRequestCode, int titleResId,
627 CharSequence title, boolean isShortcut) {
628 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
629 null /* titleResPackageName */, titleResId, title, isShortcut);
630 if (resultTo == null) {
631 context.startActivity(intent);
632 } else {
633 resultTo.startActivityForResult(intent, resultRequestCode);
634 }
635 }
636
637 public static void startWithFragment(Context context, String fragmentName, Bundle args,
638 Fragment resultTo, int resultRequestCode, String titleResPackageName, int titleResId,
639 CharSequence title, boolean isShortcut) {
640 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
641 titleResId, title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700642 if (resultTo == null) {
643 context.startActivity(intent);
644 } else {
645 resultTo.startActivityForResult(intent, resultRequestCode);
646 }
647 }
648
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100649 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100650 int titleResId, CharSequence title, boolean isShortcut,
651 UserHandle userHandle) {
652 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args,
653 null /* titleResPackageName */, titleResId, title, isShortcut);
654 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
655 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
656 context.startActivityAsUser(intent, userHandle);
657 }
658
659 public static void startWithFragmentAsUser(Context context, String fragmentName, Bundle args,
660 String titleResPackageName, int titleResId, CharSequence title, boolean isShortcut,
661 UserHandle userHandle) {
662 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResPackageName,
663 titleResId, title, isShortcut);
Zoltan Szatmary-Band50c7a82014-09-22 17:14:08 +0100664 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
665 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
Zoltan Szatmary-Ban7a2ccf22014-09-18 10:26:11 +0100666 context.startActivityAsUser(intent, userHandle);
667 }
668
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700669 /**
670 * Build an Intent to launch a new activity showing the selected fragment.
671 * The implementation constructs an Intent that re-launches the current activity with the
672 * appropriate arguments to display the fragment.
673 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700674 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700675 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000676 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700677 * @param args Optional arguments to supply to the fragment.
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100678 * @param titleResPackageName Optional package name for the resource id of the title.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700679 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700680 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700681 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700682 * @return Returns an Intent that can be launched to display the given
683 * fragment.
684 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000685 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100686 Bundle args, String titleResPackageName, int titleResId, CharSequence title,
687 boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700688 Intent intent = new Intent(Intent.ACTION_MAIN);
689 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000690 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700691 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Alexandra Gherghina62464b82014-08-11 12:40:13 +0100692 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RES_PACKAGE_NAME,
693 titleResPackageName);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700694 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700695 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700696 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700697 return intent;
698 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100699
700 /**
701 * Returns the managed profile of the current user or null if none found.
702 */
703 public static UserHandle getManagedProfile(UserManager userManager) {
704 List<UserHandle> userProfiles = userManager.getUserProfiles();
705 final int count = userProfiles.size();
706 for (int i = 0; i < count; i++) {
707 final UserHandle profile = userProfiles.get(i);
708 if (profile.getIdentifier() == userManager.getUserHandle()) {
709 continue;
710 }
711 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
712 if (userInfo.isManagedProfile()) {
713 return profile;
714 }
715 }
716 return null;
717 }
718
719 /**
720 * Returns true if the current profile is a managed one.
721 */
722 public static boolean isManagedProfile(UserManager userManager) {
723 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
724 return currentUser.isManagedProfile();
725 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100726
727 /**
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100728 * Creates a {@link UserSpinnerAdapter} if there is more than one profile on the device.
729 *
730 * <p> The adapter can be used to populate a spinner that switches between the Settings
731 * app on the different profiles.
732 *
733 * @return a {@link UserSpinnerAdapter} or null if there is only one profile.
734 */
735 public static UserSpinnerAdapter createUserSpinnerAdapter(UserManager userManager,
736 Context context) {
737 List<UserHandle> userProfiles = userManager.getUserProfiles();
738 if (userProfiles.size() < 2) {
739 return null;
740 }
741
742 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
743 // The first option should be the current profile
744 userProfiles.remove(myUserHandle);
745 userProfiles.add(0, myUserHandle);
746
747 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
748 final int count = userProfiles.size();
749 for (int i = 0; i < count; i++) {
750 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
751 }
752 return new UserSpinnerAdapter(context, userDetails);
753 }
754
755 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100756 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100757 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100758 * The target user can be either the current user, the user that launched this activity or
759 * the user contained as an extra in the arguments or intent extras.
760 *
761 * Note: This is secure in the sense that it only returns a target user different to the current
762 * one if the app launching this activity is the Settings app itself, running in the same user
763 * 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 +0100764 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100765 public static UserHandle getSecureTargetUser(IBinder activityToken,
766 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
767 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
768 IActivityManager am = ActivityManagerNative.getDefault();
769 try {
770 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
771 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
772
773 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
774 am.getLaunchedFromUid(activityToken)));
775 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
776 // Check it's secure
777 if (isProfileOf(um, launchedFromUser)) {
778 return launchedFromUser;
779 }
780 }
781 UserHandle extrasUser = intentExtras != null
782 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
783 if (extrasUser != null && !extrasUser.equals(currentUser)) {
784 // Check it's secure
785 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
786 return extrasUser;
787 }
788 }
789 UserHandle argumentsUser = arguments != null
790 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
791 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
792 // Check it's secure
793 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
794 return argumentsUser;
795 }
796 }
797 } catch (RemoteException e) {
798 // Should not happen
799 Log.v(TAG, "Could not talk to activity manager.", e);
800 }
801 return currentUser;
802 }
803
804 /**
805 * Returns the target user for a Settings activity.
806 *
807 * The target user can be either the current user, the user that launched this activity or
808 * the user contained as an extra in the arguments or intent extras.
809 *
810 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
811 * possible.
812 *
813 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
814 */
815 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
816 @Nullable Bundle intentExtras) {
817 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
818 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100819 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100820 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
821 am.getLaunchedFromUid(activityToken)));
822 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
823 return launchedFromUser;
824 }
825 UserHandle extrasUser = intentExtras != null
826 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
827 if (extrasUser != null && !extrasUser.equals(currentUser)) {
828 return extrasUser;
829 }
830 UserHandle argumentsUser = arguments != null
831 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
832 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
833 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100834 }
835 } catch (RemoteException e) {
836 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100837 Log.v(TAG, "Could not talk to activity manager.", e);
838 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100839 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100840 return currentUser;
841 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100842
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100843 /**
844 * Returns true if the user provided is in the same profiles group as the current user.
845 */
846 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
847 if (um == null || otherUser == null) return false;
848 return (UserHandle.myUserId() == otherUser.getIdentifier())
849 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100850 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530851
Andres Moralesce249fe2014-07-07 16:58:16 -0700852
853 /**
854 * Returns whether or not this device is able to be OEM unlocked.
855 */
856 static boolean isOemUnlockEnabled(Context context) {
857 PersistentDataBlockManager manager =(PersistentDataBlockManager)
858 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
859 return manager.getOemUnlockEnabled();
860 }
861
862 /**
863 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
864 * devices allow users to flash other OSes to them.
865 */
866 static void setOemUnlockEnabled(Context context, boolean enabled) {
867 PersistentDataBlockManager manager =(PersistentDataBlockManager)
868 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
869 manager.setOemUnlockEnabled(enabled);
870 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100871
872 /**
873 * Returns a circular icon for a user.
874 */
875 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000876 if (user.isManagedProfile()) {
877 // We use predefined values for managed profiles
878 Bitmap b = BitmapFactory.decodeResource(context.getResources(),
879 com.android.internal.R.drawable.ic_corp_icon);
880 return CircleFramedDrawable.getInstance(context, b);
881 }
Alexandra Gherghinabc6e78f2014-09-03 10:22:09 +0100882 if (user.iconPath != null) {
883 Bitmap icon = um.getUserIcon(user.id);
884 if (icon != null) {
885 return CircleFramedDrawable.getInstance(context, icon);
886 }
887 }
Zoltan Szatmary-Banae6ea362014-12-18 12:10:16 +0000888 return CircleFramedDrawable.getInstance(context, UserIcons.convertToBitmap(
889 UserIcons.getDefaultUserIcon(user.id, /* light= */ false)));
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100890 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700891
892 /**
Alexandra Gherghina0f5440f2014-10-30 11:56:18 +0000893 * Returns a label for the user, in the form of "User: user name" or "Work profile".
894 */
895 public static String getUserLabel(Context context, UserInfo info) {
896 if (info.isManagedProfile()) {
897 // We use predefined values for managed profiles
898 return context.getString(R.string.managed_user_title);
899 }
900 String name = info != null ? info.name : null;
901 if (name == null && info != null) {
902 name = Integer.toString(info.id);
903 } else if (info == null) {
904 name = context.getString(R.string.unknown);
905 }
906 return context.getResources().getString(R.string.running_process_item_user_label, name);
907 }
908
909 /**
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700910 * Return whether or not the user should have a SIM Cards option in Settings.
911 * TODO: Change back to returning true if count is greater than one after testing.
912 * TODO: See bug 16533525.
913 */
914 public static boolean showSimCardTile(Context context) {
915 final TelephonyManager tm =
916 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
917
PauloftheWestdbd03822014-12-04 11:56:35 -0800918 return tm.getSimCount() > 1;
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700919 }
Dan Sandlerb58b5122014-09-02 18:31:49 +0200920
921 /**
922 * Determine whether a package is a "system package", in which case certain things (like
923 * disabling notifications or disabling the package altogether) should be disallowed.
924 */
925 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) {
926 if (sSystemSignature == null) {
927 sSystemSignature = new Signature[]{ getSystemSignature(pm) };
928 }
929 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg));
930 }
931
932 private static Signature[] sSystemSignature;
933
934 private static Signature getFirstSignature(PackageInfo pkg) {
935 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) {
936 return pkg.signatures[0];
937 }
938 return null;
939 }
940
941 private static Signature getSystemSignature(PackageManager pm) {
942 try {
943 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES);
944 return getFirstSignature(sys);
945 } catch (NameNotFoundException e) {
946 }
947 return null;
948 }
949
Elliott Hughes7253df32014-09-02 17:10:14 -0700950 /**
951 * Returns elapsed time for the given millis, in the following format:
952 * 2d 5h 40m 29s
953 * @param context the application context
954 * @param millis the elapsed time in milli seconds
955 * @param withSeconds include seconds?
956 * @return the formatted elapsed time
957 */
958 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) {
959 StringBuilder sb = new StringBuilder();
960 int seconds = (int) Math.floor(millis / 1000);
961 if (!withSeconds) {
962 // Round up.
963 seconds += 30;
964 }
965
966 int days = 0, hours = 0, minutes = 0;
967 if (seconds >= SECONDS_PER_DAY) {
968 days = seconds / SECONDS_PER_DAY;
969 seconds -= days * SECONDS_PER_DAY;
970 }
971 if (seconds >= SECONDS_PER_HOUR) {
972 hours = seconds / SECONDS_PER_HOUR;
973 seconds -= hours * SECONDS_PER_HOUR;
974 }
975 if (seconds >= SECONDS_PER_MINUTE) {
976 minutes = seconds / SECONDS_PER_MINUTE;
977 seconds -= minutes * SECONDS_PER_MINUTE;
978 }
979 if (withSeconds) {
980 if (days > 0) {
981 sb.append(context.getString(R.string.battery_history_days,
982 days, hours, minutes, seconds));
983 } else if (hours > 0) {
984 sb.append(context.getString(R.string.battery_history_hours,
985 hours, minutes, seconds));
986 } else if (minutes > 0) {
987 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds));
988 } else {
989 sb.append(context.getString(R.string.battery_history_seconds, seconds));
990 }
991 } else {
992 if (days > 0) {
993 sb.append(context.getString(R.string.battery_history_days_no_seconds,
994 days, hours, minutes));
995 } else if (hours > 0) {
996 sb.append(context.getString(R.string.battery_history_hours_no_seconds,
997 hours, minutes));
998 } else {
999 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes));
1000 }
1001 }
1002 return sb.toString();
1003 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001004
1005 /**
1006 * finds a record with subId.
1007 * Since the number of SIMs are few, an array is fine.
1008 */
Wink Saville0183fb52014-11-22 10:11:39 -08001009 public static SubscriptionInfo findRecordBySubId(Context context, final int subId) {
Wink Savilleca756612014-11-08 10:47:12 -08001010 final List<SubscriptionInfo> subInfoList =
Wink Saville0183fb52014-11-22 10:11:39 -08001011 SubscriptionManager.from(context).getActiveSubscriptionInfoList();
1012 if (subInfoList != null) {
1013 final int subInfoLength = subInfoList.size();
PauloftheWest0a0daca2014-11-06 15:02:58 -08001014
Wink Saville0183fb52014-11-22 10:11:39 -08001015 for (int i = 0; i < subInfoLength; ++i) {
1016 final SubscriptionInfo sir = subInfoList.get(i);
1017 if (sir != null && sir.getSubscriptionId() == subId) {
1018 return sir;
1019 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001020 }
1021 }
1022
1023 return null;
1024 }
1025
1026 /**
1027 * finds a record with slotId.
1028 * Since the number of SIMs are few, an array is fine.
1029 */
Wink Saville0183fb52014-11-22 10:11:39 -08001030 public static SubscriptionInfo findRecordBySlotId(Context context, final int slotId) {
Wink Savilleca756612014-11-08 10:47:12 -08001031 final List<SubscriptionInfo> subInfoList =
Wink Saville0183fb52014-11-22 10:11:39 -08001032 SubscriptionManager.from(context).getActiveSubscriptionInfoList();
1033 if (subInfoList != null) {
1034 final int subInfoLength = subInfoList.size();
PauloftheWest0a0daca2014-11-06 15:02:58 -08001035
Wink Saville0183fb52014-11-22 10:11:39 -08001036 for (int i = 0; i < subInfoLength; ++i) {
1037 final SubscriptionInfo sir = subInfoList.get(i);
1038 if (sir.getSimSlotIndex() == slotId) {
1039 //Right now we take the first subscription on a SIM.
1040 return sir;
1041 }
PauloftheWest0a0daca2014-11-06 15:02:58 -08001042 }
1043 }
1044
1045 return null;
1046 }
1047
Amith Yamasani45f86232014-11-19 17:12:46 -08001048 /**
1049 * Queries for the UserInfo of a user. Returns null if the user doesn't exist (was removed).
1050 * @param userManager Instance of UserManager
1051 * @param checkUser The user to check the existence of.
1052 * @return UserInfo of the user or null for non-existent user.
1053 */
1054 public static UserInfo getExistingUser(UserManager userManager, UserHandle checkUser) {
1055 final List<UserInfo> users = userManager.getUsers(true /* excludeDying */);
1056 final int checkUserId = checkUser.getIdentifier();
1057 for (UserInfo user : users) {
1058 if (user.id == checkUserId) {
1059 return user;
1060 }
1061 }
1062 return null;
1063 }
1064
Zoltan Szatmary-Ban3af2e4c2014-12-19 17:17:23 +00001065 public static View inflateCategoryHeader(LayoutInflater inflater, ViewGroup parent) {
1066 final TypedArray a = inflater.getContext().obtainStyledAttributes(null,
1067 com.android.internal.R.styleable.Preference,
1068 com.android.internal.R.attr.preferenceCategoryStyle, 0);
1069 final int resId = a.getResourceId(com.android.internal.R.styleable.Preference_layout,
1070 0);
1071 a.recycle();
1072 return inflater.inflate(resId, parent, false);
1073 }
1074
Fabrice Di Megliodff3faa2015-02-27 11:14:11 -08001075 /**
1076 * Return if we are running low on storage space or not.
1077 *
1078 * @param context The context
1079 * @return true if we are running low on storage space
1080 */
1081 public static boolean isLowStorage(Context context) {
1082 final StorageManager sm = StorageManager.from(context);
1083 return (sm.getStorageBytesUntilLow(context.getFilesDir()) < 0);
1084 }
1085
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -08001086}