blob: 6d76bede591410252fd068ba0cd31bff8f85efd6 [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 Yamasani9627a8e2012-09-23 12:54:14 -070019import android.app.Activity;
Amith Yamasaniae697552011-09-27 11:33:17 -070020import android.app.ActivityManager;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070021import android.app.AlertDialog;
22import android.app.Dialog;
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.ParcelFileDescriptor;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070044import android.os.UserHandle;
45import android.os.UserManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080046import android.preference.Preference;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070047import android.preference.PreferenceActivity.Header;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070048import android.preference.PreferenceFrameLayout;
49import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070050import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070051import android.provider.ContactsContract.CommonDataKinds.Phone;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070052import android.provider.ContactsContract.CommonDataKinds.StructuredName;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070053import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070054import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070055import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070056import android.provider.ContactsContract.RawContacts;
Amith Yamasani60133dd2010-09-11 14:17:31 -070057import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020058import android.text.TextUtils;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070059import android.util.Log;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070060import android.view.View;
61import android.view.ViewGroup;
62import android.widget.ListView;
63import android.widget.TabWidget;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070064
Amith Yamasaniae47ef42012-09-16 17:53:35 -070065import com.android.settings.users.ProfileUpdateReceiver;
66
67import java.io.FileOutputStream;
68import java.io.IOException;
69import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080070import java.net.InetAddress;
71import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070072import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090073import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080074
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080075public class Utils {
76
77 /**
78 * Set the preference's title to the matching activity's label.
79 */
80 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
81
82 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +020083 * Name of the meta-data item that should be set in the AndroidManifest.xml
84 * to specify the icon that should be displayed for the preference.
85 */
86 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
87
88 /**
89 * Name of the meta-data item that should be set in the AndroidManifest.xml
90 * to specify the title that should be displayed for the preference.
91 */
92 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
93
94 /**
95 * Name of the meta-data item that should be set in the AndroidManifest.xml
96 * to specify the summary text that should be displayed for the preference.
97 */
98 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
99
100 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800101 * Finds a matching activity for a preference's intent. If a matching
102 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800103 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800104 * @param context The context.
105 * @param parentPreferenceGroup The preference group that contains the
106 * preference whose intent is being resolved.
107 * @param preferenceKey The key of the preference whose intent is being
108 * resolved.
109 * @param flags 0 or one or more of
110 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
111 * .
112 * @return Whether an activity was found. If false, the preference was
113 * removed.
114 */
115 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
116 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800117
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800118 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
119 if (preference == null) {
120 return false;
121 }
Ying Wanga7188322010-01-04 18:45:10 -0800122
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800123 Intent intent = preference.getIntent();
124 if (intent != null) {
125 // Find the activity that is in the system image
126 PackageManager pm = context.getPackageManager();
127 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
128 int listSize = list.size();
129 for (int i = 0; i < listSize; i++) {
130 ResolveInfo resolveInfo = list.get(i);
131 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
132 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800133
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800134 // Replace the intent with this specific activity
135 preference.setIntent(new Intent().setClassName(
136 resolveInfo.activityInfo.packageName,
137 resolveInfo.activityInfo.name));
138
139 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
140 // Set the preference title to the activity's label
141 preference.setTitle(resolveInfo.loadLabel(pm));
142 }
Ying Wanga7188322010-01-04 18:45:10 -0800143
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800144 return true;
145 }
146 }
147 }
148
149 // Did not find a matching activity, so remove the preference
150 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800151
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900152 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800153 }
Ying Wanga7188322010-01-04 18:45:10 -0800154
155 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200156 * Finds a matching activity for a preference's intent. If a matching
157 * activity is not found, it will remove the preference. The icon, title and
158 * summary of the preference will also be updated with the values retrieved
159 * from the activity's meta-data elements. If no meta-data elements are
160 * specified then the preference title will be set to match the label of the
161 * activity, an icon and summary text will not be displayed.
162 *
163 * @param context The context.
164 * @param parentPreferenceGroup The preference group that contains the
165 * preference whose intent is being resolved.
166 * @param preferenceKey The key of the preference whose intent is being
167 * resolved.
168 *
169 * @return Whether an activity was found. If false, the preference was
170 * removed.
171 *
172 * @see {@link #META_DATA_PREFERENCE_ICON}
173 * {@link #META_DATA_PREFERENCE_TITLE}
174 * {@link #META_DATA_PREFERENCE_SUMMARY}
175 */
176 public static boolean updatePreferenceToSpecificActivityFromMetaDataOrRemove(Context context,
177 PreferenceGroup parentPreferenceGroup, String preferenceKey) {
178
179 IconPreferenceScreen preference = (IconPreferenceScreen)parentPreferenceGroup
180 .findPreference(preferenceKey);
181 if (preference == null) {
182 return false;
183 }
184
185 Intent intent = preference.getIntent();
186 if (intent != null) {
187 // Find the activity that is in the system image
188 PackageManager pm = context.getPackageManager();
189 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
190 int listSize = list.size();
191 for (int i = 0; i < listSize; i++) {
192 ResolveInfo resolveInfo = list.get(i);
193 if ((resolveInfo.activityInfo.applicationInfo.flags
194 & ApplicationInfo.FLAG_SYSTEM) != 0) {
195 Drawable icon = null;
196 String title = null;
197 String summary = null;
198
199 // Get the activity's meta-data
200 try {
201 Resources res = pm
202 .getResourcesForApplication(resolveInfo.activityInfo.packageName);
203 Bundle metaData = resolveInfo.activityInfo.metaData;
204
205 if (res != null && metaData != null) {
206 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
207 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
208 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
209 }
210 } catch (NameNotFoundException e) {
211 // Ignore
212 } catch (NotFoundException e) {
213 // Ignore
214 }
215
216 // Set the preference title to the activity's label if no
217 // meta-data is found
218 if (TextUtils.isEmpty(title)) {
219 title = resolveInfo.loadLabel(pm).toString();
220 }
221
222 // Set icon, title and summary for the preference
223 preference.setIcon(icon);
224 preference.setTitle(title);
225 preference.setSummary(summary);
226
227 // Replace the intent with this specific activity
228 preference.setIntent(new Intent().setClassName(
229 resolveInfo.activityInfo.packageName,
230 resolveInfo.activityInfo.name));
231
232 return true;
233 }
234 }
235 }
236
237 // Did not find a matching activity, so remove the preference
238 parentPreferenceGroup.removePreference(preference);
239
240 return false;
241 }
242
Amith Yamasani02cf71a2010-09-21 15:48:52 -0700243 public static boolean updateHeaderToSpecificActivityFromMetaDataOrRemove(Context context,
244 List<Header> target, Header header) {
245
246 Intent intent = header.intent;
247 if (intent != null) {
248 // Find the activity that is in the system image
249 PackageManager pm = context.getPackageManager();
250 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
251 int listSize = list.size();
252 for (int i = 0; i < listSize; i++) {
253 ResolveInfo resolveInfo = list.get(i);
254 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
255 != 0) {
256 Drawable icon = null;
257 String title = null;
258 String summary = null;
259
260 // Get the activity's meta-data
261 try {
262 Resources res = pm.getResourcesForApplication(
263 resolveInfo.activityInfo.packageName);
264 Bundle metaData = resolveInfo.activityInfo.metaData;
265
266 if (res != null && metaData != null) {
267 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
268 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
269 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
270 }
271 } catch (NameNotFoundException e) {
272 // Ignore
273 } catch (NotFoundException e) {
274 // Ignore
275 }
276
277 // Set the preference title to the activity's label if no
278 // meta-data is found
279 if (TextUtils.isEmpty(title)) {
280 title = resolveInfo.loadLabel(pm).toString();
281 }
282
283 // Set icon, title and summary for the preference
284 // TODO:
285 //header.icon = icon;
286 header.title = title;
287 header.summary = summary;
288 // Replace the intent with this specific activity
289 header.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
290 resolveInfo.activityInfo.name);
291
292 return true;
293 }
294 }
295 }
296
297 // Did not find a matching activity, so remove the preference
298 if (target.remove(header)) System.err.println("Removed " + header.id);
299
300 return false;
301 }
302
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200303 /**
Ying Wanga7188322010-01-04 18:45:10 -0800304 * Returns true if Monkey is running.
305 */
306 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700307 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800308 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700309
310 /**
311 * Returns whether the device is voice-capable (meaning, it is also a phone).
312 */
313 public static boolean isVoiceCapable(Context context) {
314 TelephonyManager telephony =
315 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
316 return telephony != null && telephony.isVoiceCapable();
317 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800318
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700319 public static boolean isWifiOnly(Context context) {
320 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
321 Context.CONNECTIVITY_SERVICE);
322 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800323 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800324
325 /**
326 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
327 * @param context the application context
328 * @return the formatted and comma-separated IP addresses, or null if none.
329 */
330 public static String getWifiIpAddresses(Context context) {
331 ConnectivityManager cm = (ConnectivityManager)
332 context.getSystemService(Context.CONNECTIVITY_SERVICE);
333 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700334 return formatIpAddresses(prop);
335 }
336
337 /**
338 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
339 * addresses.
340 * @param context the application context
341 * @return the formatted and comma-separated IP addresses, or null if none.
342 */
343 public static String getDefaultIpAddresses(Context context) {
344 ConnectivityManager cm = (ConnectivityManager)
345 context.getSystemService(Context.CONNECTIVITY_SERVICE);
346 LinkProperties prop = cm.getActiveLinkProperties();
347 return formatIpAddresses(prop);
348 }
349
350 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800351 if (prop == null) return null;
352 Iterator<InetAddress> iter = prop.getAddresses().iterator();
353 // If there are no entries, return null
354 if (!iter.hasNext()) return null;
355 // Concatenate all available addresses, comma separated
356 String addresses = "";
357 while (iter.hasNext()) {
358 addresses += iter.next().getHostAddress();
359 if (iter.hasNext()) addresses += ", ";
360 }
361 return addresses;
362 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900363
364 public static Locale createLocaleFromString(String localeStr) {
365 // TODO: is there a better way to actually construct a locale that will match?
366 // The main problem is, on top of Java specs, locale.toString() and
367 // new Locale(locale.toString()).toString() do not return equal() strings in
368 // many cases, because the constructor takes the only string as the language
369 // code. So : new Locale("en", "US").toString() => "en_US"
370 // And : new Locale("en_US").toString() => "en_us"
371 if (null == localeStr)
372 return Locale.getDefault();
373 String[] brokenDownLocale = localeStr.split("_", 3);
374 // split may not return a 0-length array.
375 if (1 == brokenDownLocale.length) {
376 return new Locale(brokenDownLocale[0]);
377 } else if (2 == brokenDownLocale.length) {
378 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
379 } else {
380 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
381 }
382 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700383
384 public static String getBatteryPercentage(Intent batteryChangedIntent) {
385 int level = batteryChangedIntent.getIntExtra("level", 0);
386 int scale = batteryChangedIntent.getIntExtra("scale", 100);
387 return String.valueOf(level * 100 / scale) + "%";
388 }
389
390 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
391 final Intent intent = batteryChangedIntent;
392
393 int plugType = intent.getIntExtra("plugged", 0);
394 int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
395 String statusString;
396 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
397 statusString = res.getString(R.string.battery_info_status_charging);
398 if (plugType > 0) {
Brian Muramatsu0bd54a62012-08-14 15:13:16 -0700399 int resId;
400 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
401 resId = R.string.battery_info_status_charging_ac;
402 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
403 resId = R.string.battery_info_status_charging_usb;
404 } else {
405 resId = R.string.battery_info_status_charging_wireless;
406 }
407 statusString = statusString + " " + res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700408 }
409 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
410 statusString = res.getString(R.string.battery_info_status_discharging);
411 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
412 statusString = res.getString(R.string.battery_info_status_not_charging);
413 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
414 statusString = res.getString(R.string.battery_info_status_full);
415 } else {
416 statusString = res.getString(R.string.battery_info_status_unknown);
417 }
418
419 return statusString;
420 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700421
422 /**
423 * Prepare a custom preferences layout, moving padding to {@link ListView}
424 * when outside scrollbars are requested. Usually used to display
425 * {@link ListView} and {@link TabWidget} with correct padding.
426 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700427 public static void prepareCustomPreferencesList(
428 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700429 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
430 if (movePadding && parent instanceof PreferenceFrameLayout) {
431 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
432
433 final Resources res = list.getResources();
434 final int paddingSide = res.getDimensionPixelSize(
435 com.android.internal.R.dimen.preference_fragment_padding_side);
436 final int paddingBottom = res.getDimensionPixelSize(
437 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700438
Amith Yamasanif0b05de2012-05-09 09:43:33 -0700439 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
Jeff Sharkey5d706792011-09-08 18:57:17 -0700440 list.setPadding(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700441 }
442 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700443
444 /**
445 * Return string resource that best describes combination of tethering
446 * options available on this device.
447 */
448 public static int getTetheringLabel(ConnectivityManager cm) {
449 String[] usbRegexs = cm.getTetherableUsbRegexs();
450 String[] wifiRegexs = cm.getTetherableWifiRegexs();
451 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
452
453 boolean usbAvailable = usbRegexs.length != 0;
454 boolean wifiAvailable = wifiRegexs.length != 0;
455 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
456
457 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
458 return R.string.tether_settings_title_all;
459 } else if (wifiAvailable && usbAvailable) {
460 return R.string.tether_settings_title_all;
461 } else if (wifiAvailable && bluetoothAvailable) {
462 return R.string.tether_settings_title_all;
463 } else if (wifiAvailable) {
464 return R.string.tether_settings_title_wifi;
465 } else if (usbAvailable && bluetoothAvailable) {
466 return R.string.tether_settings_title_usb_bluetooth;
467 } else if (usbAvailable) {
468 return R.string.tether_settings_title_usb;
469 } else {
470 return R.string.tether_settings_title_bluetooth;
471 }
472 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700473
474 /* Used by UserSettings as well. Call this on a non-ui thread. */
475 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
476 Uri contactUri = Profile.CONTENT_URI;
477
478 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
479 context.getContentResolver(),
480 contactUri, true);
481 // If there's no profile photo, assign a default avatar
482 if (avatarDataStream == null) {
483 return false;
484 }
485 int userId = user != null ? user.id : UserHandle.myUserId();
486 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700487 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
488 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700489 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700490 avatarDataStream.close();
491 } catch (IOException ioe) { }
492 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700493 }
494
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700495 public static String getMeProfileName(Context context, boolean full) {
496 if (full) {
497 return getProfileDisplayName(context);
498 } else {
499 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700500 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700501 }
502
503 private static String getShorterNameIfPossible(Context context) {
504 final String given = getLocalProfileGivenName(context);
505 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
506 }
507
508 private static String getLocalProfileGivenName(Context context) {
509 final ContentResolver cr = context.getContentResolver();
510
511 // Find the raw contact ID for the local ME profile raw contact.
512 final long localRowProfileId;
513 final Cursor localRawProfile = cr.query(
514 Profile.CONTENT_RAW_CONTACTS_URI,
515 new String[] {RawContacts._ID},
516 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
517 RawContacts.ACCOUNT_NAME + " IS NULL",
518 null, null);
519 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700520
521 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700522 if (!localRawProfile.moveToFirst()) {
523 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700524 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700525 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700526 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700527 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700528 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700529
530 // Find the structured name for the raw contact.
531 final Cursor structuredName = cr.query(
532 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
533 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
534 CommonDataKinds.StructuredName.FAMILY_NAME},
535 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
536 null, null);
537 if (structuredName == null) return null;
538
539 try {
540 if (!structuredName.moveToFirst()) {
541 return null;
542 }
543 String partialName = structuredName.getString(0);
544 if (TextUtils.isEmpty(partialName)) {
545 partialName = structuredName.getString(1);
546 }
547 return partialName;
548 } finally {
549 structuredName.close();
550 }
551 }
552
553 private static final String getProfileDisplayName(Context context) {
554 final ContentResolver cr = context.getContentResolver();
555 final Cursor profile = cr.query(Profile.CONTENT_URI,
556 new String[] {Profile.DISPLAY_NAME}, null, null, null);
557 if (profile == null) return null;
558
559 try {
560 if (!profile.moveToFirst()) {
561 return null;
562 }
563 return profile.getString(0);
564 } finally {
565 profile.close();
566 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700567 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700568
569 /** Not global warming, it's global change warning. */
570 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
571 final Runnable positiveAction) {
572 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
573 builder.setTitle(titleResId);
574 builder.setMessage(R.string.global_change_warning);
575 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
576 @Override
577 public void onClick(DialogInterface dialog, int which) {
578 positiveAction.run();
579 }
580 });
581 builder.setNegativeButton(android.R.string.cancel, null);
582
583 return builder.create();
584 }
585
586 public static boolean hasMultipleUsers(Context context) {
587 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
588 .getUsers().size() > 1;
589 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800590}