blob: e3335b8b467e92d46d33566ef8f12c95ab860577 [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) {
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700447 return String.valueOf(getBatteryLevel(batteryChangedIntent)) + "%";
448 }
449
450 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900451 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
452 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700453 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700454 }
455
456 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
457 final Intent intent = batteryChangedIntent;
458
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900459 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
460 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
461 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700462 String statusString;
463 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
464 statusString = res.getString(R.string.battery_info_status_charging);
465 if (plugType > 0) {
Brian Muramatsu0bd54a62012-08-14 15:13:16 -0700466 int resId;
467 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
468 resId = R.string.battery_info_status_charging_ac;
469 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
470 resId = R.string.battery_info_status_charging_usb;
471 } else {
472 resId = R.string.battery_info_status_charging_wireless;
473 }
474 statusString = statusString + " " + res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700475 }
476 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
477 statusString = res.getString(R.string.battery_info_status_discharging);
478 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
479 statusString = res.getString(R.string.battery_info_status_not_charging);
480 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
481 statusString = res.getString(R.string.battery_info_status_full);
482 } else {
483 statusString = res.getString(R.string.battery_info_status_unknown);
484 }
485
486 return statusString;
487 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700488
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800489 public static void forcePrepareCustomPreferencesList(
490 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
491 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
492 list.setClipToPadding(false);
493 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
494 }
495
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700496 /**
497 * Prepare a custom preferences layout, moving padding to {@link ListView}
498 * when outside scrollbars are requested. Usually used to display
499 * {@link ListView} and {@link TabWidget} with correct padding.
500 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700501 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800502 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700503 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
504 if (movePadding && parent instanceof PreferenceFrameLayout) {
505 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
506
507 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700508 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700509 final int paddingBottom = res.getDimensionPixelSize(
510 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700511
Amith Yamasanif0b05de2012-05-09 09:43:33 -0700512 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
Fabrice Di Megliob27223f2013-01-15 18:54:11 -0800513 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700514 }
515 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700516
517 /**
518 * Return string resource that best describes combination of tethering
519 * options available on this device.
520 */
521 public static int getTetheringLabel(ConnectivityManager cm) {
522 String[] usbRegexs = cm.getTetherableUsbRegexs();
523 String[] wifiRegexs = cm.getTetherableWifiRegexs();
524 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
525
526 boolean usbAvailable = usbRegexs.length != 0;
527 boolean wifiAvailable = wifiRegexs.length != 0;
528 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
529
530 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
531 return R.string.tether_settings_title_all;
532 } else if (wifiAvailable && usbAvailable) {
533 return R.string.tether_settings_title_all;
534 } else if (wifiAvailable && bluetoothAvailable) {
535 return R.string.tether_settings_title_all;
536 } else if (wifiAvailable) {
537 return R.string.tether_settings_title_wifi;
538 } else if (usbAvailable && bluetoothAvailable) {
539 return R.string.tether_settings_title_usb_bluetooth;
540 } else if (usbAvailable) {
541 return R.string.tether_settings_title_usb;
542 } else {
543 return R.string.tether_settings_title_bluetooth;
544 }
545 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700546
547 /* Used by UserSettings as well. Call this on a non-ui thread. */
548 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
549 Uri contactUri = Profile.CONTENT_URI;
550
551 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
552 context.getContentResolver(),
553 contactUri, true);
554 // If there's no profile photo, assign a default avatar
555 if (avatarDataStream == null) {
556 return false;
557 }
558 int userId = user != null ? user.id : UserHandle.myUserId();
559 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700560 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
561 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700562 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700563 avatarDataStream.close();
564 } catch (IOException ioe) { }
565 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700566 }
567
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700568 public static String getMeProfileName(Context context, boolean full) {
569 if (full) {
570 return getProfileDisplayName(context);
571 } else {
572 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700573 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700574 }
575
576 private static String getShorterNameIfPossible(Context context) {
577 final String given = getLocalProfileGivenName(context);
578 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
579 }
580
581 private static String getLocalProfileGivenName(Context context) {
582 final ContentResolver cr = context.getContentResolver();
583
584 // Find the raw contact ID for the local ME profile raw contact.
585 final long localRowProfileId;
586 final Cursor localRawProfile = cr.query(
587 Profile.CONTENT_RAW_CONTACTS_URI,
588 new String[] {RawContacts._ID},
589 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
590 RawContacts.ACCOUNT_NAME + " IS NULL",
591 null, null);
592 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700593
594 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700595 if (!localRawProfile.moveToFirst()) {
596 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700597 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700598 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700599 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700600 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700601 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700602
603 // Find the structured name for the raw contact.
604 final Cursor structuredName = cr.query(
605 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
606 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
607 CommonDataKinds.StructuredName.FAMILY_NAME},
608 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
609 null, null);
610 if (structuredName == null) return null;
611
612 try {
613 if (!structuredName.moveToFirst()) {
614 return null;
615 }
616 String partialName = structuredName.getString(0);
617 if (TextUtils.isEmpty(partialName)) {
618 partialName = structuredName.getString(1);
619 }
620 return partialName;
621 } finally {
622 structuredName.close();
623 }
624 }
625
626 private static final String getProfileDisplayName(Context context) {
627 final ContentResolver cr = context.getContentResolver();
628 final Cursor profile = cr.query(Profile.CONTENT_URI,
629 new String[] {Profile.DISPLAY_NAME}, null, null, null);
630 if (profile == null) return null;
631
632 try {
633 if (!profile.moveToFirst()) {
634 return null;
635 }
636 return profile.getString(0);
637 } finally {
638 profile.close();
639 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700640 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700641
642 /** Not global warming, it's global change warning. */
643 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
644 final Runnable positiveAction) {
645 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
646 builder.setTitle(titleResId);
647 builder.setMessage(R.string.global_change_warning);
648 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
649 @Override
650 public void onClick(DialogInterface dialog, int which) {
651 positiveAction.run();
652 }
653 });
654 builder.setNegativeButton(android.R.string.cancel, null);
655
656 return builder.create();
657 }
658
659 public static boolean hasMultipleUsers(Context context) {
660 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
661 .getUsers().size() > 1;
662 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700663
664 /**
665 * Start a new instance of the activity, showing only the given fragment.
666 * When launched in this mode, the given preference fragment will be instantiated and fill the
667 * entire activity.
668 *
669 * @param context The context.
670 * @param fragmentName The name of the fragment to display.
671 * @param args Optional arguments to supply to the fragment.
672 * @param resultTo Option fragment that should receive the result of
673 * the activity launch.
674 * @param resultRequestCode If resultTo is non-null, this is the request
675 * code in which to report the result.
676 * @param title String to display for the title of this set of preferences.
677 */
678 public static void startWithFragment(Context context, String fragmentName, Bundle args,
679 Fragment resultTo, int resultRequestCode, CharSequence title) {
680 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, title);
681 if (resultTo == null) {
682 context.startActivity(intent);
683 } else {
684 resultTo.startActivityForResult(intent, resultRequestCode);
685 }
686 }
687
688 /**
689 * Build an Intent to launch a new activity showing the selected fragment.
690 * The implementation constructs an Intent that re-launches the current activity with the
691 * appropriate arguments to display the fragment.
692 *
693 * @param context The Context.
694 * @param fragmentName The name of the fragment to display.
695 * @param args Optional arguments to supply to the fragment.
696 * @param title Optional title to show for this item.
697 * @return Returns an Intent that can be launched to display the given
698 * fragment.
699 */
700 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
701 Bundle args, CharSequence title) {
702 Intent intent = new Intent(Intent.ACTION_MAIN);
703 intent.setClass(context, SubSettings.class);
704 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
705 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
706 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
707 intent.putExtra(SettingsActivity.EXTRA_NO_HEADERS, true);
708 return intent;
709 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800710}