blob: 26750e7e1f07faa129060fd1d7e8a7758f62ea05 [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
Amith Yamasaniae697552011-09-27 11:33:17 -070019import android.app.ActivityManager;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070020import android.app.AlertDialog;
21import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070022import android.app.Fragment;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070023import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080024import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070025import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080026import android.content.Intent;
27import android.content.pm.ApplicationInfo;
28import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070029import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070030import android.content.pm.ResolveInfo;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070031import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020032import android.content.res.Resources;
33import android.content.res.Resources.NotFoundException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070034import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070035import android.graphics.Bitmap;
36import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020037import android.graphics.drawable.Drawable;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080038import android.net.ConnectivityManager;
39import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070040import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070041import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020042import android.os.Bundle;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070043import android.os.UserHandle;
44import android.os.UserManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080045import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070046import android.preference.PreferenceFrameLayout;
47import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070048import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070049import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070050import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070051import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070052import android.provider.ContactsContract.RawContacts;
Amith Yamasani60133dd2010-09-11 14:17:31 -070053import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020054import android.text.TextUtils;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070055import android.view.View;
56import android.view.ViewGroup;
57import android.widget.ListView;
58import android.widget.TabWidget;
Alexandra Gherghina3939cd72014-06-04 10:02:55 +010059
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070060import com.android.settings.dashboard.DashboardCategory;
61import com.android.settings.dashboard.DashboardTile;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070062
Amith Yamasaniae47ef42012-09-16 17:53:35 -070063import java.io.IOException;
64import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080065import java.net.InetAddress;
Alexandra Gherghina3939cd72014-06-04 10:02:55 +010066import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080067import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070068import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090069import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080070
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070071public final class Utils {
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080072
73 /**
74 * Set the preference's title to the matching activity's label.
75 */
76 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
77
78 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090079 * The opacity level of a disabled icon.
80 */
81 public static final float DISABLED_ALPHA = 0.4f;
82
83 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -070084 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
85 * 1 is most bad (red), the last value is least bad (green).
86 */
87 public static final int[] BADNESS_COLORS = new int[] {
88 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
89 0xfffabf2c, 0xff679e37, 0xff0a7f42
90 };
91
92 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +020093 * Name of the meta-data item that should be set in the AndroidManifest.xml
94 * to specify the icon that should be displayed for the preference.
95 */
96 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
97
98 /**
99 * Name of the meta-data item that should be set in the AndroidManifest.xml
100 * to specify the title that should be displayed for the preference.
101 */
102 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
103
104 /**
105 * Name of the meta-data item that should be set in the AndroidManifest.xml
106 * to specify the summary text that should be displayed for the preference.
107 */
108 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
109
110 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800111 * Finds a matching activity for a preference's intent. If a matching
112 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800113 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800114 * @param context The context.
115 * @param parentPreferenceGroup The preference group that contains the
116 * preference whose intent is being resolved.
117 * @param preferenceKey The key of the preference whose intent is being
118 * resolved.
119 * @param flags 0 or one or more of
120 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
121 * .
122 * @return Whether an activity was found. If false, the preference was
123 * removed.
124 */
125 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
126 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800127
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800128 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
129 if (preference == null) {
130 return false;
131 }
Ying Wanga7188322010-01-04 18:45:10 -0800132
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800133 Intent intent = preference.getIntent();
134 if (intent != null) {
135 // Find the activity that is in the system image
136 PackageManager pm = context.getPackageManager();
137 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
138 int listSize = list.size();
139 for (int i = 0; i < listSize; i++) {
140 ResolveInfo resolveInfo = list.get(i);
141 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
142 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800143
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800144 // Replace the intent with this specific activity
145 preference.setIntent(new Intent().setClassName(
146 resolveInfo.activityInfo.packageName,
147 resolveInfo.activityInfo.name));
148
149 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
150 // Set the preference title to the activity's label
151 preference.setTitle(resolveInfo.loadLabel(pm));
152 }
Ying Wanga7188322010-01-04 18:45:10 -0800153
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800154 return true;
155 }
156 }
157 }
158
159 // Did not find a matching activity, so remove the preference
160 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800161
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900162 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800163 }
Ying Wanga7188322010-01-04 18:45:10 -0800164
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700165 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
166 DashboardCategory target, DashboardTile tile) {
167
168 Intent intent = tile.intent;
169 if (intent != null) {
170 // Find the activity that is in the system image
171 PackageManager pm = context.getPackageManager();
172 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
173 int listSize = list.size();
174 for (int i = 0; i < listSize; i++) {
175 ResolveInfo resolveInfo = list.get(i);
176 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
177 != 0) {
178 Drawable icon = null;
179 String title = null;
180 String summary = null;
181
182 // Get the activity's meta-data
183 try {
184 Resources res = pm.getResourcesForApplication(
185 resolveInfo.activityInfo.packageName);
186 Bundle metaData = resolveInfo.activityInfo.metaData;
187
188 if (res != null && metaData != null) {
189 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
190 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
191 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
192 }
193 } catch (NameNotFoundException e) {
194 // Ignore
195 } catch (NotFoundException e) {
196 // Ignore
197 }
198
199 // Set the preference title to the activity's label if no
200 // meta-data is found
201 if (TextUtils.isEmpty(title)) {
202 title = resolveInfo.loadLabel(pm).toString();
203 }
204
205 // Set icon, title and summary for the preference
206 // TODO:
207 //tile.icon = icon;
208 tile.title = title;
209 tile.summary = summary;
210 // Replace the intent with this specific activity
211 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
212 resolveInfo.activityInfo.name);
213
214 return true;
215 }
216 }
217 }
218
219 // Did not find a matching activity, so remove the preference
220 target.removeTile(tile);
221
222 return false;
223 }
224
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200225 /**
Ying Wanga7188322010-01-04 18:45:10 -0800226 * Returns true if Monkey is running.
227 */
228 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700229 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800230 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700231
232 /**
233 * Returns whether the device is voice-capable (meaning, it is also a phone).
234 */
235 public static boolean isVoiceCapable(Context context) {
236 TelephonyManager telephony =
237 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
238 return telephony != null && telephony.isVoiceCapable();
239 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800240
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700241 public static boolean isWifiOnly(Context context) {
242 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
243 Context.CONNECTIVITY_SERVICE);
244 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800245 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800246
247 /**
248 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
249 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900250 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800251 */
252 public static String getWifiIpAddresses(Context context) {
253 ConnectivityManager cm = (ConnectivityManager)
254 context.getSystemService(Context.CONNECTIVITY_SERVICE);
255 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700256 return formatIpAddresses(prop);
257 }
258
259 /**
260 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
261 * addresses.
262 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900263 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700264 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900265 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700266 LinkProperties prop = cm.getActiveLinkProperties();
267 return formatIpAddresses(prop);
268 }
269
270 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800271 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900272 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800273 // If there are no entries, return null
274 if (!iter.hasNext()) return null;
275 // Concatenate all available addresses, comma separated
276 String addresses = "";
277 while (iter.hasNext()) {
278 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900279 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800280 }
281 return addresses;
282 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900283
284 public static Locale createLocaleFromString(String localeStr) {
285 // TODO: is there a better way to actually construct a locale that will match?
286 // The main problem is, on top of Java specs, locale.toString() and
287 // new Locale(locale.toString()).toString() do not return equal() strings in
288 // many cases, because the constructor takes the only string as the language
289 // code. So : new Locale("en", "US").toString() => "en_US"
290 // And : new Locale("en_US").toString() => "en_us"
291 if (null == localeStr)
292 return Locale.getDefault();
293 String[] brokenDownLocale = localeStr.split("_", 3);
294 // split may not return a 0-length array.
295 if (1 == brokenDownLocale.length) {
296 return new Locale(brokenDownLocale[0]);
297 } else if (2 == brokenDownLocale.length) {
298 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
299 } else {
300 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
301 }
302 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700303
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900304 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
305 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
306 }
307
Amith Yamasania4379d62011-07-22 10:34:58 -0700308 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700309 return String.valueOf(getBatteryLevel(batteryChangedIntent)) + "%";
310 }
311
312 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900313 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
314 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700315 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700316 }
317
318 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
319 final Intent intent = batteryChangedIntent;
320
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900321 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
322 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
323 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700324 String statusString;
325 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700326 int resId;
327 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
328 resId = R.string.battery_info_status_charging_ac;
329 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
330 resId = R.string.battery_info_status_charging_usb;
331 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
332 resId = R.string.battery_info_status_charging_wireless;
333 } else {
334 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700335 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700336 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700337 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
338 statusString = res.getString(R.string.battery_info_status_discharging);
339 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
340 statusString = res.getString(R.string.battery_info_status_not_charging);
341 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
342 statusString = res.getString(R.string.battery_info_status_full);
343 } else {
344 statusString = res.getString(R.string.battery_info_status_unknown);
345 }
346
347 return statusString;
348 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700349
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800350 public static void forcePrepareCustomPreferencesList(
351 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
352 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
353 list.setClipToPadding(false);
354 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
355 }
356
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700357 /**
358 * Prepare a custom preferences layout, moving padding to {@link ListView}
359 * when outside scrollbars are requested. Usually used to display
360 * {@link ListView} and {@link TabWidget} with correct padding.
361 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700362 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800363 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700364 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
365 if (movePadding && parent instanceof PreferenceFrameLayout) {
366 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
367
368 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700369 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700370 final int paddingBottom = res.getDimensionPixelSize(
371 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700372
Amith Yamasanif0b05de2012-05-09 09:43:33 -0700373 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
Fabrice Di Megliob27223f2013-01-15 18:54:11 -0800374 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700375 }
376 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700377
378 /**
379 * Return string resource that best describes combination of tethering
380 * options available on this device.
381 */
382 public static int getTetheringLabel(ConnectivityManager cm) {
383 String[] usbRegexs = cm.getTetherableUsbRegexs();
384 String[] wifiRegexs = cm.getTetherableWifiRegexs();
385 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
386
387 boolean usbAvailable = usbRegexs.length != 0;
388 boolean wifiAvailable = wifiRegexs.length != 0;
389 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
390
391 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
392 return R.string.tether_settings_title_all;
393 } else if (wifiAvailable && usbAvailable) {
394 return R.string.tether_settings_title_all;
395 } else if (wifiAvailable && bluetoothAvailable) {
396 return R.string.tether_settings_title_all;
397 } else if (wifiAvailable) {
398 return R.string.tether_settings_title_wifi;
399 } else if (usbAvailable && bluetoothAvailable) {
400 return R.string.tether_settings_title_usb_bluetooth;
401 } else if (usbAvailable) {
402 return R.string.tether_settings_title_usb;
403 } else {
404 return R.string.tether_settings_title_bluetooth;
405 }
406 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700407
408 /* Used by UserSettings as well. Call this on a non-ui thread. */
409 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
410 Uri contactUri = Profile.CONTENT_URI;
411
412 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
413 context.getContentResolver(),
414 contactUri, true);
415 // If there's no profile photo, assign a default avatar
416 if (avatarDataStream == null) {
417 return false;
418 }
419 int userId = user != null ? user.id : UserHandle.myUserId();
420 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700421 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
422 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700423 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700424 avatarDataStream.close();
425 } catch (IOException ioe) { }
426 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700427 }
428
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700429 public static String getMeProfileName(Context context, boolean full) {
430 if (full) {
431 return getProfileDisplayName(context);
432 } else {
433 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700434 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700435 }
436
437 private static String getShorterNameIfPossible(Context context) {
438 final String given = getLocalProfileGivenName(context);
439 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
440 }
441
442 private static String getLocalProfileGivenName(Context context) {
443 final ContentResolver cr = context.getContentResolver();
444
445 // Find the raw contact ID for the local ME profile raw contact.
446 final long localRowProfileId;
447 final Cursor localRawProfile = cr.query(
448 Profile.CONTENT_RAW_CONTACTS_URI,
449 new String[] {RawContacts._ID},
450 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
451 RawContacts.ACCOUNT_NAME + " IS NULL",
452 null, null);
453 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700454
455 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700456 if (!localRawProfile.moveToFirst()) {
457 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700458 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700459 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700460 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700461 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700462 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700463
464 // Find the structured name for the raw contact.
465 final Cursor structuredName = cr.query(
466 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
467 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
468 CommonDataKinds.StructuredName.FAMILY_NAME},
469 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
470 null, null);
471 if (structuredName == null) return null;
472
473 try {
474 if (!structuredName.moveToFirst()) {
475 return null;
476 }
477 String partialName = structuredName.getString(0);
478 if (TextUtils.isEmpty(partialName)) {
479 partialName = structuredName.getString(1);
480 }
481 return partialName;
482 } finally {
483 structuredName.close();
484 }
485 }
486
487 private static final String getProfileDisplayName(Context context) {
488 final ContentResolver cr = context.getContentResolver();
489 final Cursor profile = cr.query(Profile.CONTENT_URI,
490 new String[] {Profile.DISPLAY_NAME}, null, null, null);
491 if (profile == null) return null;
492
493 try {
494 if (!profile.moveToFirst()) {
495 return null;
496 }
497 return profile.getString(0);
498 } finally {
499 profile.close();
500 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700501 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700502
503 /** Not global warming, it's global change warning. */
504 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
505 final Runnable positiveAction) {
506 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
507 builder.setTitle(titleResId);
508 builder.setMessage(R.string.global_change_warning);
509 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
510 @Override
511 public void onClick(DialogInterface dialog, int which) {
512 positiveAction.run();
513 }
514 });
515 builder.setNegativeButton(android.R.string.cancel, null);
516
517 return builder.create();
518 }
519
520 public static boolean hasMultipleUsers(Context context) {
521 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
522 .getUsers().size() > 1;
523 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700524
525 /**
526 * Start a new instance of the activity, showing only the given fragment.
527 * When launched in this mode, the given preference fragment will be instantiated and fill the
528 * entire activity.
529 *
530 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000531 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700532 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700533 * @param resultTo Option fragment that should receive the result of the activity launch.
534 * @param resultRequestCode If resultTo is non-null, this is the request code in which
535 * to report the result.
536 * @param titleResId resource id for the String to display for the title of this set
537 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700538 * @param title String to display for the title of this set of preferences.
539 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000540 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700541 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700542 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
543 titleResId, title, false /* not a shortcut */);
544 }
545
546 public static void startWithFragment(Context context, String fragmentName, Bundle args,
547 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title,
548 boolean isShortcut) {
549 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
550 title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700551 if (resultTo == null) {
552 context.startActivity(intent);
553 } else {
554 resultTo.startActivityForResult(intent, resultRequestCode);
555 }
556 }
557
558 /**
559 * Build an Intent to launch a new activity showing the selected fragment.
560 * The implementation constructs an Intent that re-launches the current activity with the
561 * appropriate arguments to display the fragment.
562 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700563 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700564 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000565 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700566 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700567 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700568 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700569 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700570 * @return Returns an Intent that can be launched to display the given
571 * fragment.
572 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000573 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700574 Bundle args, int titleResId, CharSequence title, boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700575 Intent intent = new Intent(Intent.ACTION_MAIN);
576 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000577 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700578 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700579 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700580 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700581 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700582 return intent;
583 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100584
585 /**
586 * Returns the managed profile of the current user or null if none found.
587 */
588 public static UserHandle getManagedProfile(UserManager userManager) {
589 List<UserHandle> userProfiles = userManager.getUserProfiles();
590 final int count = userProfiles.size();
591 for (int i = 0; i < count; i++) {
592 final UserHandle profile = userProfiles.get(i);
593 if (profile.getIdentifier() == userManager.getUserHandle()) {
594 continue;
595 }
596 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
597 if (userInfo.isManagedProfile()) {
598 return profile;
599 }
600 }
601 return null;
602 }
603
604 /**
605 * Returns true if the current profile is a managed one.
606 */
607 public static boolean isManagedProfile(UserManager userManager) {
608 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
609 return currentUser.isManagedProfile();
610 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800611}