blob: 78d40982ecf2ebc86507be75e8f3e5dc7cea2381 [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;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070059import com.android.settings.dashboard.DashboardCategory;
60import com.android.settings.dashboard.DashboardTile;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070061
Amith Yamasaniae47ef42012-09-16 17:53:35 -070062import java.io.IOException;
63import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080064import java.net.InetAddress;
65import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070066import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090067import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080068
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070069public final class Utils {
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080070
71 /**
72 * Set the preference's title to the matching activity's label.
73 */
74 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
75
76 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090077 * The opacity level of a disabled icon.
78 */
79 public static final float DISABLED_ALPHA = 0.4f;
80
81 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +020082 * Name of the meta-data item that should be set in the AndroidManifest.xml
83 * to specify the icon that should be displayed for the preference.
84 */
85 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
86
87 /**
88 * Name of the meta-data item that should be set in the AndroidManifest.xml
89 * to specify the title that should be displayed for the preference.
90 */
91 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
92
93 /**
94 * Name of the meta-data item that should be set in the AndroidManifest.xml
95 * to specify the summary text that should be displayed for the preference.
96 */
97 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
98
99 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800100 * Finds a matching activity for a preference's intent. If a matching
101 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800102 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800103 * @param context The context.
104 * @param parentPreferenceGroup The preference group that contains the
105 * preference whose intent is being resolved.
106 * @param preferenceKey The key of the preference whose intent is being
107 * resolved.
108 * @param flags 0 or one or more of
109 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
110 * .
111 * @return Whether an activity was found. If false, the preference was
112 * removed.
113 */
114 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
115 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800116
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800117 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
118 if (preference == null) {
119 return false;
120 }
Ying Wanga7188322010-01-04 18:45:10 -0800121
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800122 Intent intent = preference.getIntent();
123 if (intent != null) {
124 // Find the activity that is in the system image
125 PackageManager pm = context.getPackageManager();
126 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
127 int listSize = list.size();
128 for (int i = 0; i < listSize; i++) {
129 ResolveInfo resolveInfo = list.get(i);
130 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
131 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800132
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800133 // Replace the intent with this specific activity
134 preference.setIntent(new Intent().setClassName(
135 resolveInfo.activityInfo.packageName,
136 resolveInfo.activityInfo.name));
137
138 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
139 // Set the preference title to the activity's label
140 preference.setTitle(resolveInfo.loadLabel(pm));
141 }
Ying Wanga7188322010-01-04 18:45:10 -0800142
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800143 return true;
144 }
145 }
146 }
147
148 // Did not find a matching activity, so remove the preference
149 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800150
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900151 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800152 }
Ying Wanga7188322010-01-04 18:45:10 -0800153
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700154 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
155 DashboardCategory target, DashboardTile tile) {
156
157 Intent intent = tile.intent;
158 if (intent != null) {
159 // Find the activity that is in the system image
160 PackageManager pm = context.getPackageManager();
161 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
162 int listSize = list.size();
163 for (int i = 0; i < listSize; i++) {
164 ResolveInfo resolveInfo = list.get(i);
165 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
166 != 0) {
167 Drawable icon = null;
168 String title = null;
169 String summary = null;
170
171 // Get the activity's meta-data
172 try {
173 Resources res = pm.getResourcesForApplication(
174 resolveInfo.activityInfo.packageName);
175 Bundle metaData = resolveInfo.activityInfo.metaData;
176
177 if (res != null && metaData != null) {
178 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
179 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
180 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
181 }
182 } catch (NameNotFoundException e) {
183 // Ignore
184 } catch (NotFoundException e) {
185 // Ignore
186 }
187
188 // Set the preference title to the activity's label if no
189 // meta-data is found
190 if (TextUtils.isEmpty(title)) {
191 title = resolveInfo.loadLabel(pm).toString();
192 }
193
194 // Set icon, title and summary for the preference
195 // TODO:
196 //tile.icon = icon;
197 tile.title = title;
198 tile.summary = summary;
199 // Replace the intent with this specific activity
200 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
201 resolveInfo.activityInfo.name);
202
203 return true;
204 }
205 }
206 }
207
208 // Did not find a matching activity, so remove the preference
209 target.removeTile(tile);
210
211 return false;
212 }
213
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200214 /**
Ying Wanga7188322010-01-04 18:45:10 -0800215 * Returns true if Monkey is running.
216 */
217 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700218 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800219 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700220
221 /**
222 * Returns whether the device is voice-capable (meaning, it is also a phone).
223 */
224 public static boolean isVoiceCapable(Context context) {
225 TelephonyManager telephony =
226 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
227 return telephony != null && telephony.isVoiceCapable();
228 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800229
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700230 public static boolean isWifiOnly(Context context) {
231 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
232 Context.CONNECTIVITY_SERVICE);
233 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800234 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800235
236 /**
237 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
238 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900239 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800240 */
241 public static String getWifiIpAddresses(Context context) {
242 ConnectivityManager cm = (ConnectivityManager)
243 context.getSystemService(Context.CONNECTIVITY_SERVICE);
244 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700245 return formatIpAddresses(prop);
246 }
247
248 /**
249 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
250 * addresses.
251 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900252 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700253 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900254 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700255 LinkProperties prop = cm.getActiveLinkProperties();
256 return formatIpAddresses(prop);
257 }
258
259 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800260 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900261 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800262 // If there are no entries, return null
263 if (!iter.hasNext()) return null;
264 // Concatenate all available addresses, comma separated
265 String addresses = "";
266 while (iter.hasNext()) {
267 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900268 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800269 }
270 return addresses;
271 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900272
273 public static Locale createLocaleFromString(String localeStr) {
274 // TODO: is there a better way to actually construct a locale that will match?
275 // The main problem is, on top of Java specs, locale.toString() and
276 // new Locale(locale.toString()).toString() do not return equal() strings in
277 // many cases, because the constructor takes the only string as the language
278 // code. So : new Locale("en", "US").toString() => "en_US"
279 // And : new Locale("en_US").toString() => "en_us"
280 if (null == localeStr)
281 return Locale.getDefault();
282 String[] brokenDownLocale = localeStr.split("_", 3);
283 // split may not return a 0-length array.
284 if (1 == brokenDownLocale.length) {
285 return new Locale(brokenDownLocale[0]);
286 } else if (2 == brokenDownLocale.length) {
287 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
288 } else {
289 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
290 }
291 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700292
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900293 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
294 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
295 }
296
Amith Yamasania4379d62011-07-22 10:34:58 -0700297 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700298 return String.valueOf(getBatteryLevel(batteryChangedIntent)) + "%";
299 }
300
301 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900302 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
303 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700304 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700305 }
306
307 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
308 final Intent intent = batteryChangedIntent;
309
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900310 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
311 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
312 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700313 String statusString;
314 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700315 int resId;
316 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
317 resId = R.string.battery_info_status_charging_ac;
318 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
319 resId = R.string.battery_info_status_charging_usb;
320 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
321 resId = R.string.battery_info_status_charging_wireless;
322 } else {
323 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700324 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700325 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700326 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
327 statusString = res.getString(R.string.battery_info_status_discharging);
328 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
329 statusString = res.getString(R.string.battery_info_status_not_charging);
330 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
331 statusString = res.getString(R.string.battery_info_status_full);
332 } else {
333 statusString = res.getString(R.string.battery_info_status_unknown);
334 }
335
336 return statusString;
337 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700338
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800339 public static void forcePrepareCustomPreferencesList(
340 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
341 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
342 list.setClipToPadding(false);
343 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
344 }
345
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700346 /**
347 * Prepare a custom preferences layout, moving padding to {@link ListView}
348 * when outside scrollbars are requested. Usually used to display
349 * {@link ListView} and {@link TabWidget} with correct padding.
350 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700351 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800352 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700353 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
354 if (movePadding && parent instanceof PreferenceFrameLayout) {
355 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
356
357 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700358 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700359 final int paddingBottom = res.getDimensionPixelSize(
360 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700361
Amith Yamasanif0b05de2012-05-09 09:43:33 -0700362 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
Fabrice Di Megliob27223f2013-01-15 18:54:11 -0800363 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700364 }
365 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700366
367 /**
368 * Return string resource that best describes combination of tethering
369 * options available on this device.
370 */
371 public static int getTetheringLabel(ConnectivityManager cm) {
372 String[] usbRegexs = cm.getTetherableUsbRegexs();
373 String[] wifiRegexs = cm.getTetherableWifiRegexs();
374 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
375
376 boolean usbAvailable = usbRegexs.length != 0;
377 boolean wifiAvailable = wifiRegexs.length != 0;
378 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
379
380 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
381 return R.string.tether_settings_title_all;
382 } else if (wifiAvailable && usbAvailable) {
383 return R.string.tether_settings_title_all;
384 } else if (wifiAvailable && bluetoothAvailable) {
385 return R.string.tether_settings_title_all;
386 } else if (wifiAvailable) {
387 return R.string.tether_settings_title_wifi;
388 } else if (usbAvailable && bluetoothAvailable) {
389 return R.string.tether_settings_title_usb_bluetooth;
390 } else if (usbAvailable) {
391 return R.string.tether_settings_title_usb;
392 } else {
393 return R.string.tether_settings_title_bluetooth;
394 }
395 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700396
397 /* Used by UserSettings as well. Call this on a non-ui thread. */
398 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
399 Uri contactUri = Profile.CONTENT_URI;
400
401 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
402 context.getContentResolver(),
403 contactUri, true);
404 // If there's no profile photo, assign a default avatar
405 if (avatarDataStream == null) {
406 return false;
407 }
408 int userId = user != null ? user.id : UserHandle.myUserId();
409 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700410 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
411 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700412 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700413 avatarDataStream.close();
414 } catch (IOException ioe) { }
415 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700416 }
417
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700418 public static String getMeProfileName(Context context, boolean full) {
419 if (full) {
420 return getProfileDisplayName(context);
421 } else {
422 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700423 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700424 }
425
426 private static String getShorterNameIfPossible(Context context) {
427 final String given = getLocalProfileGivenName(context);
428 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
429 }
430
431 private static String getLocalProfileGivenName(Context context) {
432 final ContentResolver cr = context.getContentResolver();
433
434 // Find the raw contact ID for the local ME profile raw contact.
435 final long localRowProfileId;
436 final Cursor localRawProfile = cr.query(
437 Profile.CONTENT_RAW_CONTACTS_URI,
438 new String[] {RawContacts._ID},
439 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
440 RawContacts.ACCOUNT_NAME + " IS NULL",
441 null, null);
442 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700443
444 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700445 if (!localRawProfile.moveToFirst()) {
446 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700447 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700448 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700449 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700450 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700451 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700452
453 // Find the structured name for the raw contact.
454 final Cursor structuredName = cr.query(
455 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
456 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
457 CommonDataKinds.StructuredName.FAMILY_NAME},
458 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
459 null, null);
460 if (structuredName == null) return null;
461
462 try {
463 if (!structuredName.moveToFirst()) {
464 return null;
465 }
466 String partialName = structuredName.getString(0);
467 if (TextUtils.isEmpty(partialName)) {
468 partialName = structuredName.getString(1);
469 }
470 return partialName;
471 } finally {
472 structuredName.close();
473 }
474 }
475
476 private static final String getProfileDisplayName(Context context) {
477 final ContentResolver cr = context.getContentResolver();
478 final Cursor profile = cr.query(Profile.CONTENT_URI,
479 new String[] {Profile.DISPLAY_NAME}, null, null, null);
480 if (profile == null) return null;
481
482 try {
483 if (!profile.moveToFirst()) {
484 return null;
485 }
486 return profile.getString(0);
487 } finally {
488 profile.close();
489 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700490 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700491
492 /** Not global warming, it's global change warning. */
493 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
494 final Runnable positiveAction) {
495 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
496 builder.setTitle(titleResId);
497 builder.setMessage(R.string.global_change_warning);
498 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
499 @Override
500 public void onClick(DialogInterface dialog, int which) {
501 positiveAction.run();
502 }
503 });
504 builder.setNegativeButton(android.R.string.cancel, null);
505
506 return builder.create();
507 }
508
509 public static boolean hasMultipleUsers(Context context) {
510 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
511 .getUsers().size() > 1;
512 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700513
514 /**
515 * Start a new instance of the activity, showing only the given fragment.
516 * When launched in this mode, the given preference fragment will be instantiated and fill the
517 * entire activity.
518 *
519 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000520 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700521 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700522 * @param resultTo Option fragment that should receive the result of the activity launch.
523 * @param resultRequestCode If resultTo is non-null, this is the request code in which
524 * to report the result.
525 * @param titleResId resource id for the String to display for the title of this set
526 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700527 * @param title String to display for the title of this set of preferences.
528 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000529 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700530 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700531 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
532 titleResId, title, false /* not a shortcut */);
533 }
534
535 public static void startWithFragment(Context context, String fragmentName, Bundle args,
536 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title,
537 boolean isShortcut) {
538 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
539 title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700540 if (resultTo == null) {
541 context.startActivity(intent);
542 } else {
543 resultTo.startActivityForResult(intent, resultRequestCode);
544 }
545 }
546
547 /**
548 * Build an Intent to launch a new activity showing the selected fragment.
549 * The implementation constructs an Intent that re-launches the current activity with the
550 * appropriate arguments to display the fragment.
551 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700552 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700553 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000554 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700555 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700556 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700557 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700558 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700559 * @return Returns an Intent that can be launched to display the given
560 * fragment.
561 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000562 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700563 Bundle args, int titleResId, CharSequence title, boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700564 Intent intent = new Intent(Intent.ACTION_MAIN);
565 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000566 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700567 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700568 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700569 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700570 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700571 return intent;
572 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800573}