blob: 8abe30db0271b89cc00b2d1f629ba1766f6a7305 [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;
Fabrice Di Megliod25314d2014-03-21 19:24:43 -070061import com.android.settings.dashboard.Header;
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;
66import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070067import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090068import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080069
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080070public class Utils {
71
72 /**
73 * Set the preference's title to the matching activity's label.
74 */
75 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
76
77 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090078 * The opacity level of a disabled icon.
79 */
80 public static final float DISABLED_ALPHA = 0.4f;
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,
Fabrice Di Megliod25314d2014-03-21 19:24:43 -0700244 List<Header> target, Header header) {
Amith Yamasani02cf71a2010-09-21 15:48:52 -0700245
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
Dianne Hackborn79d42bb2012-11-28 18:05:00 -0800298 target.remove(header);
Amith Yamasani02cf71a2010-09-21 15:48:52 -0700299
300 return false;
301 }
302
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700303 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
304 DashboardCategory target, DashboardTile tile) {
305
306 Intent intent = tile.intent;
307 if (intent != null) {
308 // Find the activity that is in the system image
309 PackageManager pm = context.getPackageManager();
310 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
311 int listSize = list.size();
312 for (int i = 0; i < listSize; i++) {
313 ResolveInfo resolveInfo = list.get(i);
314 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
315 != 0) {
316 Drawable icon = null;
317 String title = null;
318 String summary = null;
319
320 // Get the activity's meta-data
321 try {
322 Resources res = pm.getResourcesForApplication(
323 resolveInfo.activityInfo.packageName);
324 Bundle metaData = resolveInfo.activityInfo.metaData;
325
326 if (res != null && metaData != null) {
327 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
328 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
329 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
330 }
331 } catch (NameNotFoundException e) {
332 // Ignore
333 } catch (NotFoundException e) {
334 // Ignore
335 }
336
337 // Set the preference title to the activity's label if no
338 // meta-data is found
339 if (TextUtils.isEmpty(title)) {
340 title = resolveInfo.loadLabel(pm).toString();
341 }
342
343 // Set icon, title and summary for the preference
344 // TODO:
345 //tile.icon = icon;
346 tile.title = title;
347 tile.summary = summary;
348 // Replace the intent with this specific activity
349 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
350 resolveInfo.activityInfo.name);
351
352 return true;
353 }
354 }
355 }
356
357 // Did not find a matching activity, so remove the preference
358 target.removeTile(tile);
359
360 return false;
361 }
362
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200363 /**
Ying Wanga7188322010-01-04 18:45:10 -0800364 * Returns true if Monkey is running.
365 */
366 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700367 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800368 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700369
370 /**
371 * Returns whether the device is voice-capable (meaning, it is also a phone).
372 */
373 public static boolean isVoiceCapable(Context context) {
374 TelephonyManager telephony =
375 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
376 return telephony != null && telephony.isVoiceCapable();
377 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800378
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700379 public static boolean isWifiOnly(Context context) {
380 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
381 Context.CONNECTIVITY_SERVICE);
382 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800383 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800384
385 /**
386 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
387 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900388 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800389 */
390 public static String getWifiIpAddresses(Context context) {
391 ConnectivityManager cm = (ConnectivityManager)
392 context.getSystemService(Context.CONNECTIVITY_SERVICE);
393 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700394 return formatIpAddresses(prop);
395 }
396
397 /**
398 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
399 * addresses.
400 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900401 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700402 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900403 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700404 LinkProperties prop = cm.getActiveLinkProperties();
405 return formatIpAddresses(prop);
406 }
407
408 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800409 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900410 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800411 // If there are no entries, return null
412 if (!iter.hasNext()) return null;
413 // Concatenate all available addresses, comma separated
414 String addresses = "";
415 while (iter.hasNext()) {
416 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900417 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800418 }
419 return addresses;
420 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900421
422 public static Locale createLocaleFromString(String localeStr) {
423 // TODO: is there a better way to actually construct a locale that will match?
424 // The main problem is, on top of Java specs, locale.toString() and
425 // new Locale(locale.toString()).toString() do not return equal() strings in
426 // many cases, because the constructor takes the only string as the language
427 // code. So : new Locale("en", "US").toString() => "en_US"
428 // And : new Locale("en_US").toString() => "en_us"
429 if (null == localeStr)
430 return Locale.getDefault();
431 String[] brokenDownLocale = localeStr.split("_", 3);
432 // split may not return a 0-length array.
433 if (1 == brokenDownLocale.length) {
434 return new Locale(brokenDownLocale[0]);
435 } else if (2 == brokenDownLocale.length) {
436 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
437 } else {
438 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
439 }
440 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700441
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900442 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
443 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
444 }
445
Amith Yamasania4379d62011-07-22 10:34:58 -0700446 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900447 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
448 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Amith Yamasania4379d62011-07-22 10:34:58 -0700449 return String.valueOf(level * 100 / scale) + "%";
450 }
451
452 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
453 final Intent intent = batteryChangedIntent;
454
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900455 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
456 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
457 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700458 String statusString;
459 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
460 statusString = res.getString(R.string.battery_info_status_charging);
461 if (plugType > 0) {
Brian Muramatsu0bd54a62012-08-14 15:13:16 -0700462 int resId;
463 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
464 resId = R.string.battery_info_status_charging_ac;
465 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
466 resId = R.string.battery_info_status_charging_usb;
467 } else {
468 resId = R.string.battery_info_status_charging_wireless;
469 }
470 statusString = statusString + " " + res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700471 }
472 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
473 statusString = res.getString(R.string.battery_info_status_discharging);
474 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
475 statusString = res.getString(R.string.battery_info_status_not_charging);
476 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
477 statusString = res.getString(R.string.battery_info_status_full);
478 } else {
479 statusString = res.getString(R.string.battery_info_status_unknown);
480 }
481
482 return statusString;
483 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700484
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800485 public static void forcePrepareCustomPreferencesList(
486 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
487 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
488 list.setClipToPadding(false);
489 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
490 }
491
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700492 /**
493 * Prepare a custom preferences layout, moving padding to {@link ListView}
494 * when outside scrollbars are requested. Usually used to display
495 * {@link ListView} and {@link TabWidget} with correct padding.
496 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700497 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800498 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700499 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
500 if (movePadding && parent instanceof PreferenceFrameLayout) {
501 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
502
503 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700504 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700505 final int paddingBottom = res.getDimensionPixelSize(
506 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700507
Amith Yamasanif0b05de2012-05-09 09:43:33 -0700508 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
Fabrice Di Megliob27223f2013-01-15 18:54:11 -0800509 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700510 }
511 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700512
513 /**
514 * Return string resource that best describes combination of tethering
515 * options available on this device.
516 */
517 public static int getTetheringLabel(ConnectivityManager cm) {
518 String[] usbRegexs = cm.getTetherableUsbRegexs();
519 String[] wifiRegexs = cm.getTetherableWifiRegexs();
520 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
521
522 boolean usbAvailable = usbRegexs.length != 0;
523 boolean wifiAvailable = wifiRegexs.length != 0;
524 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
525
526 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
527 return R.string.tether_settings_title_all;
528 } else if (wifiAvailable && usbAvailable) {
529 return R.string.tether_settings_title_all;
530 } else if (wifiAvailable && bluetoothAvailable) {
531 return R.string.tether_settings_title_all;
532 } else if (wifiAvailable) {
533 return R.string.tether_settings_title_wifi;
534 } else if (usbAvailable && bluetoothAvailable) {
535 return R.string.tether_settings_title_usb_bluetooth;
536 } else if (usbAvailable) {
537 return R.string.tether_settings_title_usb;
538 } else {
539 return R.string.tether_settings_title_bluetooth;
540 }
541 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700542
543 /* Used by UserSettings as well. Call this on a non-ui thread. */
544 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
545 Uri contactUri = Profile.CONTENT_URI;
546
547 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
548 context.getContentResolver(),
549 contactUri, true);
550 // If there's no profile photo, assign a default avatar
551 if (avatarDataStream == null) {
552 return false;
553 }
554 int userId = user != null ? user.id : UserHandle.myUserId();
555 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700556 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
557 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700558 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700559 avatarDataStream.close();
560 } catch (IOException ioe) { }
561 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700562 }
563
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700564 public static String getMeProfileName(Context context, boolean full) {
565 if (full) {
566 return getProfileDisplayName(context);
567 } else {
568 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700569 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700570 }
571
572 private static String getShorterNameIfPossible(Context context) {
573 final String given = getLocalProfileGivenName(context);
574 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
575 }
576
577 private static String getLocalProfileGivenName(Context context) {
578 final ContentResolver cr = context.getContentResolver();
579
580 // Find the raw contact ID for the local ME profile raw contact.
581 final long localRowProfileId;
582 final Cursor localRawProfile = cr.query(
583 Profile.CONTENT_RAW_CONTACTS_URI,
584 new String[] {RawContacts._ID},
585 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
586 RawContacts.ACCOUNT_NAME + " IS NULL",
587 null, null);
588 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700589
590 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700591 if (!localRawProfile.moveToFirst()) {
592 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700593 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700594 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700595 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700596 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700597 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700598
599 // Find the structured name for the raw contact.
600 final Cursor structuredName = cr.query(
601 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
602 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
603 CommonDataKinds.StructuredName.FAMILY_NAME},
604 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
605 null, null);
606 if (structuredName == null) return null;
607
608 try {
609 if (!structuredName.moveToFirst()) {
610 return null;
611 }
612 String partialName = structuredName.getString(0);
613 if (TextUtils.isEmpty(partialName)) {
614 partialName = structuredName.getString(1);
615 }
616 return partialName;
617 } finally {
618 structuredName.close();
619 }
620 }
621
622 private static final String getProfileDisplayName(Context context) {
623 final ContentResolver cr = context.getContentResolver();
624 final Cursor profile = cr.query(Profile.CONTENT_URI,
625 new String[] {Profile.DISPLAY_NAME}, null, null, null);
626 if (profile == null) return null;
627
628 try {
629 if (!profile.moveToFirst()) {
630 return null;
631 }
632 return profile.getString(0);
633 } finally {
634 profile.close();
635 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700636 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700637
638 /** Not global warming, it's global change warning. */
639 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
640 final Runnable positiveAction) {
641 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
642 builder.setTitle(titleResId);
643 builder.setMessage(R.string.global_change_warning);
644 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
645 @Override
646 public void onClick(DialogInterface dialog, int which) {
647 positiveAction.run();
648 }
649 });
650 builder.setNegativeButton(android.R.string.cancel, null);
651
652 return builder.create();
653 }
654
655 public static boolean hasMultipleUsers(Context context) {
656 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
657 .getUsers().size() > 1;
658 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700659
660 /**
661 * Start a new instance of the activity, showing only the given fragment.
662 * When launched in this mode, the given preference fragment will be instantiated and fill the
663 * entire activity.
664 *
665 * @param context The context.
666 * @param fragmentName The name of the fragment to display.
667 * @param args Optional arguments to supply to the fragment.
668 * @param resultTo Option fragment that should receive the result of
669 * the activity launch.
670 * @param resultRequestCode If resultTo is non-null, this is the request
671 * code in which to report the result.
672 * @param title String to display for the title of this set of preferences.
673 */
674 public static void startWithFragment(Context context, String fragmentName, Bundle args,
675 Fragment resultTo, int resultRequestCode, CharSequence title) {
676 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, title);
677 if (resultTo == null) {
678 context.startActivity(intent);
679 } else {
680 resultTo.startActivityForResult(intent, resultRequestCode);
681 }
682 }
683
684 /**
685 * Build an Intent to launch a new activity showing the selected fragment.
686 * The implementation constructs an Intent that re-launches the current activity with the
687 * appropriate arguments to display the fragment.
688 *
689 * @param context The Context.
690 * @param fragmentName The name of the fragment to display.
691 * @param args Optional arguments to supply to the fragment.
692 * @param title Optional title to show for this item.
693 * @return Returns an Intent that can be launched to display the given
694 * fragment.
695 */
696 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
697 Bundle args, CharSequence title) {
698 Intent intent = new Intent(Intent.ACTION_MAIN);
699 intent.setClass(context, SubSettings.class);
700 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
701 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
702 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
703 intent.putExtra(SettingsActivity.EXTRA_NO_HEADERS, true);
704 return intent;
705 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800706}