blob: 8cb1ff74a4e81b0e0f4bfc0fb35d148e14d0d095 [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;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010023import android.app.IActivityManager;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070024import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080025import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070026import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080027import android.content.Intent;
28import android.content.pm.ApplicationInfo;
29import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070030import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070031import android.content.pm.ResolveInfo;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070032import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020033import android.content.res.Resources;
34import android.content.res.Resources.NotFoundException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070035import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070036import android.graphics.Bitmap;
37import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020038import android.graphics.drawable.Drawable;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080039import android.net.ConnectivityManager;
40import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070041import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070042import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020043import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010044import android.os.IBinder;
45import android.os.RemoteException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070046import android.os.UserHandle;
47import android.os.UserManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080048import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070049import android.preference.PreferenceFrameLayout;
50import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070051import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070052import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070053import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070054import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070055import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070056import android.service.persistentdata.PersistentDataBlockManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070057import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020058import android.text.TextUtils;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010059import android.util.Log;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070060import android.view.View;
61import android.view.ViewGroup;
62import android.widget.ListView;
63import android.widget.TabWidget;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070064import com.android.settings.dashboard.DashboardCategory;
65import com.android.settings.dashboard.DashboardTile;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070066
Amith Yamasaniae47ef42012-09-16 17:53:35 -070067import java.io.IOException;
68import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080069import java.net.InetAddress;
70import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070071import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090072import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080073
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070074public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010075 private static final String TAG = "Settings";
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080076 /**
77 * Set the preference's title to the matching activity's label.
78 */
79 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
80
81 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090082 * The opacity level of a disabled icon.
83 */
84 public static final float DISABLED_ALPHA = 0.4f;
85
86 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -070087 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
88 * 1 is most bad (red), the last value is least bad (green).
89 */
90 public static final int[] BADNESS_COLORS = new int[] {
91 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
92 0xfffabf2c, 0xff679e37, 0xff0a7f42
93 };
94
95 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +020096 * Name of the meta-data item that should be set in the AndroidManifest.xml
97 * to specify the icon that should be displayed for the preference.
98 */
99 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
100
101 /**
102 * Name of the meta-data item that should be set in the AndroidManifest.xml
103 * to specify the title that should be displayed for the preference.
104 */
105 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
106
107 /**
108 * Name of the meta-data item that should be set in the AndroidManifest.xml
109 * to specify the summary text that should be displayed for the preference.
110 */
111 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
112
113 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800114 * Finds a matching activity for a preference's intent. If a matching
115 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800116 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800117 * @param context The context.
118 * @param parentPreferenceGroup The preference group that contains the
119 * preference whose intent is being resolved.
120 * @param preferenceKey The key of the preference whose intent is being
121 * resolved.
122 * @param flags 0 or one or more of
123 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
124 * .
125 * @return Whether an activity was found. If false, the preference was
126 * removed.
127 */
128 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
129 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800130
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800131 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
132 if (preference == null) {
133 return false;
134 }
Ying Wanga7188322010-01-04 18:45:10 -0800135
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800136 Intent intent = preference.getIntent();
137 if (intent != null) {
138 // Find the activity that is in the system image
139 PackageManager pm = context.getPackageManager();
140 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
141 int listSize = list.size();
142 for (int i = 0; i < listSize; i++) {
143 ResolveInfo resolveInfo = list.get(i);
144 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
145 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800146
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800147 // Replace the intent with this specific activity
148 preference.setIntent(new Intent().setClassName(
149 resolveInfo.activityInfo.packageName,
150 resolveInfo.activityInfo.name));
151
152 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
153 // Set the preference title to the activity's label
154 preference.setTitle(resolveInfo.loadLabel(pm));
155 }
Ying Wanga7188322010-01-04 18:45:10 -0800156
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800157 return true;
158 }
159 }
160 }
161
162 // Did not find a matching activity, so remove the preference
163 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800164
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900165 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800166 }
Ying Wanga7188322010-01-04 18:45:10 -0800167
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700168 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
169 DashboardCategory target, DashboardTile tile) {
170
171 Intent intent = tile.intent;
172 if (intent != null) {
173 // Find the activity that is in the system image
174 PackageManager pm = context.getPackageManager();
175 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
176 int listSize = list.size();
177 for (int i = 0; i < listSize; i++) {
178 ResolveInfo resolveInfo = list.get(i);
179 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
180 != 0) {
181 Drawable icon = null;
182 String title = null;
183 String summary = null;
184
185 // Get the activity's meta-data
186 try {
187 Resources res = pm.getResourcesForApplication(
188 resolveInfo.activityInfo.packageName);
189 Bundle metaData = resolveInfo.activityInfo.metaData;
190
191 if (res != null && metaData != null) {
192 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
193 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
194 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
195 }
196 } catch (NameNotFoundException e) {
197 // Ignore
198 } catch (NotFoundException e) {
199 // Ignore
200 }
201
202 // Set the preference title to the activity's label if no
203 // meta-data is found
204 if (TextUtils.isEmpty(title)) {
205 title = resolveInfo.loadLabel(pm).toString();
206 }
207
208 // Set icon, title and summary for the preference
209 // TODO:
210 //tile.icon = icon;
211 tile.title = title;
212 tile.summary = summary;
213 // Replace the intent with this specific activity
214 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
215 resolveInfo.activityInfo.name);
216
217 return true;
218 }
219 }
220 }
221
222 // Did not find a matching activity, so remove the preference
223 target.removeTile(tile);
224
225 return false;
226 }
227
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200228 /**
Ying Wanga7188322010-01-04 18:45:10 -0800229 * Returns true if Monkey is running.
230 */
231 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700232 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800233 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700234
235 /**
236 * Returns whether the device is voice-capable (meaning, it is also a phone).
237 */
238 public static boolean isVoiceCapable(Context context) {
239 TelephonyManager telephony =
240 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
241 return telephony != null && telephony.isVoiceCapable();
242 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800243
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700244 public static boolean isWifiOnly(Context context) {
245 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
246 Context.CONNECTIVITY_SERVICE);
247 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800248 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800249
250 /**
251 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
252 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900253 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800254 */
255 public static String getWifiIpAddresses(Context context) {
256 ConnectivityManager cm = (ConnectivityManager)
257 context.getSystemService(Context.CONNECTIVITY_SERVICE);
258 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700259 return formatIpAddresses(prop);
260 }
261
262 /**
263 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
264 * addresses.
265 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900266 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700267 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900268 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700269 LinkProperties prop = cm.getActiveLinkProperties();
270 return formatIpAddresses(prop);
271 }
272
273 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800274 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900275 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800276 // If there are no entries, return null
277 if (!iter.hasNext()) return null;
278 // Concatenate all available addresses, comma separated
279 String addresses = "";
280 while (iter.hasNext()) {
281 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900282 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800283 }
284 return addresses;
285 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900286
287 public static Locale createLocaleFromString(String localeStr) {
288 // TODO: is there a better way to actually construct a locale that will match?
289 // The main problem is, on top of Java specs, locale.toString() and
290 // new Locale(locale.toString()).toString() do not return equal() strings in
291 // many cases, because the constructor takes the only string as the language
292 // code. So : new Locale("en", "US").toString() => "en_US"
293 // And : new Locale("en_US").toString() => "en_us"
294 if (null == localeStr)
295 return Locale.getDefault();
296 String[] brokenDownLocale = localeStr.split("_", 3);
297 // split may not return a 0-length array.
298 if (1 == brokenDownLocale.length) {
299 return new Locale(brokenDownLocale[0]);
300 } else if (2 == brokenDownLocale.length) {
301 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
302 } else {
303 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
304 }
305 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700306
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900307 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
308 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
309 }
310
Amith Yamasania4379d62011-07-22 10:34:58 -0700311 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700312 return String.valueOf(getBatteryLevel(batteryChangedIntent)) + "%";
313 }
314
315 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900316 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
317 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700318 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700319 }
320
321 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
322 final Intent intent = batteryChangedIntent;
323
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900324 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
325 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
326 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700327 String statusString;
328 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700329 int resId;
330 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
331 resId = R.string.battery_info_status_charging_ac;
332 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
333 resId = R.string.battery_info_status_charging_usb;
334 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
335 resId = R.string.battery_info_status_charging_wireless;
336 } else {
337 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700338 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700339 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700340 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
341 statusString = res.getString(R.string.battery_info_status_discharging);
342 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
343 statusString = res.getString(R.string.battery_info_status_not_charging);
344 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
345 statusString = res.getString(R.string.battery_info_status_full);
346 } else {
347 statusString = res.getString(R.string.battery_info_status_unknown);
348 }
349
350 return statusString;
351 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700352
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800353 public static void forcePrepareCustomPreferencesList(
354 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
355 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
356 list.setClipToPadding(false);
357 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
358 }
359
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700360 /**
361 * Prepare a custom preferences layout, moving padding to {@link ListView}
362 * when outside scrollbars are requested. Usually used to display
363 * {@link ListView} and {@link TabWidget} with correct padding.
364 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700365 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800366 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700367 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700368 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700369 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700370 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700371 final int paddingBottom = res.getDimensionPixelSize(
372 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700373
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700374 if (parent instanceof PreferenceFrameLayout) {
375 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
376
377 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
378 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
379 } else {
380 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
381 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700382 }
383 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700384
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700385 public static void forceCustomPadding(View view) {
386 final Resources res = view.getResources();
387 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
388 final int paddingBottom = res.getDimensionPixelSize(
389 com.android.internal.R.dimen.preference_fragment_padding_bottom);
390
391 view.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
392 }
393
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700394 /**
395 * Return string resource that best describes combination of tethering
396 * options available on this device.
397 */
398 public static int getTetheringLabel(ConnectivityManager cm) {
399 String[] usbRegexs = cm.getTetherableUsbRegexs();
400 String[] wifiRegexs = cm.getTetherableWifiRegexs();
401 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
402
403 boolean usbAvailable = usbRegexs.length != 0;
404 boolean wifiAvailable = wifiRegexs.length != 0;
405 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
406
407 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
408 return R.string.tether_settings_title_all;
409 } else if (wifiAvailable && usbAvailable) {
410 return R.string.tether_settings_title_all;
411 } else if (wifiAvailable && bluetoothAvailable) {
412 return R.string.tether_settings_title_all;
413 } else if (wifiAvailable) {
414 return R.string.tether_settings_title_wifi;
415 } else if (usbAvailable && bluetoothAvailable) {
416 return R.string.tether_settings_title_usb_bluetooth;
417 } else if (usbAvailable) {
418 return R.string.tether_settings_title_usb;
419 } else {
420 return R.string.tether_settings_title_bluetooth;
421 }
422 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700423
424 /* Used by UserSettings as well. Call this on a non-ui thread. */
425 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
426 Uri contactUri = Profile.CONTENT_URI;
427
428 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
429 context.getContentResolver(),
430 contactUri, true);
431 // If there's no profile photo, assign a default avatar
432 if (avatarDataStream == null) {
433 return false;
434 }
435 int userId = user != null ? user.id : UserHandle.myUserId();
436 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700437 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
438 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700439 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700440 avatarDataStream.close();
441 } catch (IOException ioe) { }
442 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700443 }
444
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700445 public static String getMeProfileName(Context context, boolean full) {
446 if (full) {
447 return getProfileDisplayName(context);
448 } else {
449 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700450 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700451 }
452
453 private static String getShorterNameIfPossible(Context context) {
454 final String given = getLocalProfileGivenName(context);
455 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
456 }
457
458 private static String getLocalProfileGivenName(Context context) {
459 final ContentResolver cr = context.getContentResolver();
460
461 // Find the raw contact ID for the local ME profile raw contact.
462 final long localRowProfileId;
463 final Cursor localRawProfile = cr.query(
464 Profile.CONTENT_RAW_CONTACTS_URI,
465 new String[] {RawContacts._ID},
466 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
467 RawContacts.ACCOUNT_NAME + " IS NULL",
468 null, null);
469 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700470
471 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700472 if (!localRawProfile.moveToFirst()) {
473 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700474 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700475 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700476 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700477 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700478 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700479
480 // Find the structured name for the raw contact.
481 final Cursor structuredName = cr.query(
482 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
483 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
484 CommonDataKinds.StructuredName.FAMILY_NAME},
485 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
486 null, null);
487 if (structuredName == null) return null;
488
489 try {
490 if (!structuredName.moveToFirst()) {
491 return null;
492 }
493 String partialName = structuredName.getString(0);
494 if (TextUtils.isEmpty(partialName)) {
495 partialName = structuredName.getString(1);
496 }
497 return partialName;
498 } finally {
499 structuredName.close();
500 }
501 }
502
503 private static final String getProfileDisplayName(Context context) {
504 final ContentResolver cr = context.getContentResolver();
505 final Cursor profile = cr.query(Profile.CONTENT_URI,
506 new String[] {Profile.DISPLAY_NAME}, null, null, null);
507 if (profile == null) return null;
508
509 try {
510 if (!profile.moveToFirst()) {
511 return null;
512 }
513 return profile.getString(0);
514 } finally {
515 profile.close();
516 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700517 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700518
519 /** Not global warming, it's global change warning. */
520 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
521 final Runnable positiveAction) {
522 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
523 builder.setTitle(titleResId);
524 builder.setMessage(R.string.global_change_warning);
525 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
526 @Override
527 public void onClick(DialogInterface dialog, int which) {
528 positiveAction.run();
529 }
530 });
531 builder.setNegativeButton(android.R.string.cancel, null);
532
533 return builder.create();
534 }
535
536 public static boolean hasMultipleUsers(Context context) {
537 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
538 .getUsers().size() > 1;
539 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700540
541 /**
542 * Start a new instance of the activity, showing only the given fragment.
543 * When launched in this mode, the given preference fragment will be instantiated and fill the
544 * entire activity.
545 *
546 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000547 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700548 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700549 * @param resultTo Option fragment that should receive the result of the activity launch.
550 * @param resultRequestCode If resultTo is non-null, this is the request code in which
551 * to report the result.
552 * @param titleResId resource id for the String to display for the title of this set
553 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700554 * @param title String to display for the title of this set of preferences.
555 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000556 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700557 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700558 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
559 titleResId, title, false /* not a shortcut */);
560 }
561
562 public static void startWithFragment(Context context, String fragmentName, Bundle args,
563 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title,
564 boolean isShortcut) {
565 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
566 title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700567 if (resultTo == null) {
568 context.startActivity(intent);
569 } else {
570 resultTo.startActivityForResult(intent, resultRequestCode);
571 }
572 }
573
574 /**
575 * Build an Intent to launch a new activity showing the selected fragment.
576 * The implementation constructs an Intent that re-launches the current activity with the
577 * appropriate arguments to display the fragment.
578 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700579 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700580 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000581 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700582 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700583 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700584 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700585 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700586 * @return Returns an Intent that can be launched to display the given
587 * fragment.
588 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000589 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700590 Bundle args, int titleResId, CharSequence title, boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700591 Intent intent = new Intent(Intent.ACTION_MAIN);
592 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000593 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700594 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700595 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700596 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700597 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700598 return intent;
599 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100600
601 /**
602 * Returns the managed profile of the current user or null if none found.
603 */
604 public static UserHandle getManagedProfile(UserManager userManager) {
605 List<UserHandle> userProfiles = userManager.getUserProfiles();
606 final int count = userProfiles.size();
607 for (int i = 0; i < count; i++) {
608 final UserHandle profile = userProfiles.get(i);
609 if (profile.getIdentifier() == userManager.getUserHandle()) {
610 continue;
611 }
612 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
613 if (userInfo.isManagedProfile()) {
614 return profile;
615 }
616 }
617 return null;
618 }
619
620 /**
621 * Returns true if the current profile is a managed one.
622 */
623 public static boolean isManagedProfile(UserManager userManager) {
624 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
625 return currentUser.isManagedProfile();
626 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100627
628 /**
629 * Returns the {@link UserHandle} of the profile that a settings screen should refer to.
630 *
631 * <p> This takes into account the id of the user that triggered the settings screen.
632 */
633 public static UserHandle getProfileToDisplay(IActivityManager am, IBinder activityToken,
634 Bundle arguments) {
635 int currentUser = UserHandle.getCallingUserId();
636 // Check to see if it was called from a different user
637 try {
638 int launchedFromUser = UserHandle.getUserId(am.getLaunchedFromUid(activityToken));
639 if (launchedFromUser != currentUser) {
640 // This is a forwarded intent
641 return new UserHandle(launchedFromUser);
642 }
643 } catch (RemoteException e) {
644 // Should not happen
645 Log.v(TAG, "Could not get launching user.");
646 }
647 // TODO: Check fragment arguments. See: http://b/15466880
648
649 // Default to current profile
650 return new UserHandle(currentUser);
651 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530652
653 /**
654 * Creates a dialog to confirm with the user if it's ok to remove the user
655 * and delete all the data.
656 *
657 * @param context a Context object
658 * @param removingUserId The userId of the user to remove
659 * @param onConfirmListener Callback object for positive action
660 * @return the created Dialog
661 */
662 public static Dialog createRemoveConfirmationDialog(Context context, int removingUserId,
663 DialogInterface.OnClickListener onConfirmListener) {
664 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
665 UserInfo userInfo = um.getUserInfo(removingUserId);
666 Dialog dlg = new AlertDialog.Builder(context)
667 .setTitle(UserHandle.myUserId() == removingUserId
668 ? R.string.user_confirm_remove_self_title
669 : (userInfo.isRestricted()
670 ? R.string.user_profile_confirm_remove_title
671 : R.string.user_confirm_remove_title))
672 .setMessage(UserHandle.myUserId() == removingUserId
673 ? R.string.user_confirm_remove_self_message
674 : (userInfo.isRestricted()
675 ? R.string.user_profile_confirm_remove_message
676 : R.string.user_confirm_remove_message))
677 .setPositiveButton(R.string.user_delete_button,
678 onConfirmListener)
679 .setNegativeButton(android.R.string.cancel, null)
680 .create();
681 return dlg;
682 }
Andres Moralesce249fe2014-07-07 16:58:16 -0700683
684 /**
685 * Returns whether or not this device is able to be OEM unlocked.
686 */
687 static boolean isOemUnlockEnabled(Context context) {
688 PersistentDataBlockManager manager =(PersistentDataBlockManager)
689 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
690 return manager.getOemUnlockEnabled();
691 }
692
693 /**
694 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
695 * devices allow users to flash other OSes to them.
696 */
697 static void setOemUnlockEnabled(Context context, boolean enabled) {
698 PersistentDataBlockManager manager =(PersistentDataBlockManager)
699 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
700 manager.setOemUnlockEnabled(enabled);
701 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800702}