blob: 692d8f3bc6b3cedbf3a8046ef4e617ad24f0943d [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;
Amith Yamasani51c6dac2014-07-02 00:06:37 +053021import android.app.AlertDialog.Builder;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070022import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070023import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010024import android.app.IActivityManager;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070025import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080026import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070027import android.content.DialogInterface;
Amith Yamasani51c6dac2014-07-02 00:06:37 +053028import android.content.DialogInterface.OnClickListener;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080029import android.content.Intent;
30import android.content.pm.ApplicationInfo;
31import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070032import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070033import android.content.pm.ResolveInfo;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070034import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020035import android.content.res.Resources;
36import android.content.res.Resources.NotFoundException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070037import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070038import android.graphics.Bitmap;
39import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020040import android.graphics.drawable.Drawable;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080041import android.net.ConnectivityManager;
42import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070043import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070044import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020045import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010046import android.os.IBinder;
47import android.os.RemoteException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070048import android.os.UserHandle;
49import android.os.UserManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080050import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070051import android.preference.PreferenceFrameLayout;
52import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070053import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070054import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070055import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070056import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070057import android.provider.ContactsContract.RawContacts;
Amith Yamasani60133dd2010-09-11 14:17:31 -070058import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020059import android.text.TextUtils;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010060import android.util.Log;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070061import android.view.View;
62import android.view.ViewGroup;
63import android.widget.ListView;
64import android.widget.TabWidget;
Alexandra Gherghina3939cd72014-06-04 10:02:55 +010065
Amith Yamasani51c6dac2014-07-02 00:06:37 +053066import com.android.settings.R.string;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070067import com.android.settings.dashboard.DashboardCategory;
68import com.android.settings.dashboard.DashboardTile;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070069
Amith Yamasaniae47ef42012-09-16 17:53:35 -070070import java.io.IOException;
71import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080072import java.net.InetAddress;
73import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070074import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090075import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080076
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070077public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010078 private static final String TAG = "Settings";
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080079 /**
80 * Set the preference's title to the matching activity's label.
81 */
82 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
83
84 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090085 * The opacity level of a disabled icon.
86 */
87 public static final float DISABLED_ALPHA = 0.4f;
88
89 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -070090 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
91 * 1 is most bad (red), the last value is least bad (green).
92 */
93 public static final int[] BADNESS_COLORS = new int[] {
94 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
95 0xfffabf2c, 0xff679e37, 0xff0a7f42
96 };
97
98 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +020099 * Name of the meta-data item that should be set in the AndroidManifest.xml
100 * to specify the icon that should be displayed for the preference.
101 */
102 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
103
104 /**
105 * Name of the meta-data item that should be set in the AndroidManifest.xml
106 * to specify the title that should be displayed for the preference.
107 */
108 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
109
110 /**
111 * Name of the meta-data item that should be set in the AndroidManifest.xml
112 * to specify the summary text that should be displayed for the preference.
113 */
114 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
115
116 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800117 * Finds a matching activity for a preference's intent. If a matching
118 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800119 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800120 * @param context The context.
121 * @param parentPreferenceGroup The preference group that contains the
122 * preference whose intent is being resolved.
123 * @param preferenceKey The key of the preference whose intent is being
124 * resolved.
125 * @param flags 0 or one or more of
126 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
127 * .
128 * @return Whether an activity was found. If false, the preference was
129 * removed.
130 */
131 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
132 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800133
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800134 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
135 if (preference == null) {
136 return false;
137 }
Ying Wanga7188322010-01-04 18:45:10 -0800138
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800139 Intent intent = preference.getIntent();
140 if (intent != null) {
141 // Find the activity that is in the system image
142 PackageManager pm = context.getPackageManager();
143 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
144 int listSize = list.size();
145 for (int i = 0; i < listSize; i++) {
146 ResolveInfo resolveInfo = list.get(i);
147 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
148 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800149
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800150 // Replace the intent with this specific activity
151 preference.setIntent(new Intent().setClassName(
152 resolveInfo.activityInfo.packageName,
153 resolveInfo.activityInfo.name));
154
155 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
156 // Set the preference title to the activity's label
157 preference.setTitle(resolveInfo.loadLabel(pm));
158 }
Ying Wanga7188322010-01-04 18:45:10 -0800159
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800160 return true;
161 }
162 }
163 }
164
165 // Did not find a matching activity, so remove the preference
166 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800167
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900168 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800169 }
Ying Wanga7188322010-01-04 18:45:10 -0800170
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700171 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
172 DashboardCategory target, DashboardTile tile) {
173
174 Intent intent = tile.intent;
175 if (intent != null) {
176 // Find the activity that is in the system image
177 PackageManager pm = context.getPackageManager();
178 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
179 int listSize = list.size();
180 for (int i = 0; i < listSize; i++) {
181 ResolveInfo resolveInfo = list.get(i);
182 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
183 != 0) {
184 Drawable icon = null;
185 String title = null;
186 String summary = null;
187
188 // Get the activity's meta-data
189 try {
190 Resources res = pm.getResourcesForApplication(
191 resolveInfo.activityInfo.packageName);
192 Bundle metaData = resolveInfo.activityInfo.metaData;
193
194 if (res != null && metaData != null) {
195 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
196 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
197 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
198 }
199 } catch (NameNotFoundException e) {
200 // Ignore
201 } catch (NotFoundException e) {
202 // Ignore
203 }
204
205 // Set the preference title to the activity's label if no
206 // meta-data is found
207 if (TextUtils.isEmpty(title)) {
208 title = resolveInfo.loadLabel(pm).toString();
209 }
210
211 // Set icon, title and summary for the preference
212 // TODO:
213 //tile.icon = icon;
214 tile.title = title;
215 tile.summary = summary;
216 // Replace the intent with this specific activity
217 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
218 resolveInfo.activityInfo.name);
219
220 return true;
221 }
222 }
223 }
224
225 // Did not find a matching activity, so remove the preference
226 target.removeTile(tile);
227
228 return false;
229 }
230
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200231 /**
Ying Wanga7188322010-01-04 18:45:10 -0800232 * Returns true if Monkey is running.
233 */
234 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700235 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800236 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700237
238 /**
239 * Returns whether the device is voice-capable (meaning, it is also a phone).
240 */
241 public static boolean isVoiceCapable(Context context) {
242 TelephonyManager telephony =
243 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
244 return telephony != null && telephony.isVoiceCapable();
245 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800246
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700247 public static boolean isWifiOnly(Context context) {
248 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
249 Context.CONNECTIVITY_SERVICE);
250 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800251 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800252
253 /**
254 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
255 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900256 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800257 */
258 public static String getWifiIpAddresses(Context context) {
259 ConnectivityManager cm = (ConnectivityManager)
260 context.getSystemService(Context.CONNECTIVITY_SERVICE);
261 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700262 return formatIpAddresses(prop);
263 }
264
265 /**
266 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
267 * addresses.
268 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900269 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700270 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900271 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700272 LinkProperties prop = cm.getActiveLinkProperties();
273 return formatIpAddresses(prop);
274 }
275
276 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800277 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900278 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800279 // If there are no entries, return null
280 if (!iter.hasNext()) return null;
281 // Concatenate all available addresses, comma separated
282 String addresses = "";
283 while (iter.hasNext()) {
284 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900285 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800286 }
287 return addresses;
288 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900289
290 public static Locale createLocaleFromString(String localeStr) {
291 // TODO: is there a better way to actually construct a locale that will match?
292 // The main problem is, on top of Java specs, locale.toString() and
293 // new Locale(locale.toString()).toString() do not return equal() strings in
294 // many cases, because the constructor takes the only string as the language
295 // code. So : new Locale("en", "US").toString() => "en_US"
296 // And : new Locale("en_US").toString() => "en_us"
297 if (null == localeStr)
298 return Locale.getDefault();
299 String[] brokenDownLocale = localeStr.split("_", 3);
300 // split may not return a 0-length array.
301 if (1 == brokenDownLocale.length) {
302 return new Locale(brokenDownLocale[0]);
303 } else if (2 == brokenDownLocale.length) {
304 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
305 } else {
306 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
307 }
308 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700309
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900310 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
311 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
312 }
313
Amith Yamasania4379d62011-07-22 10:34:58 -0700314 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700315 return String.valueOf(getBatteryLevel(batteryChangedIntent)) + "%";
316 }
317
318 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900319 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
320 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700321 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700322 }
323
324 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
325 final Intent intent = batteryChangedIntent;
326
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900327 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
328 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
329 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700330 String statusString;
331 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700332 int resId;
333 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
334 resId = R.string.battery_info_status_charging_ac;
335 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
336 resId = R.string.battery_info_status_charging_usb;
337 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
338 resId = R.string.battery_info_status_charging_wireless;
339 } else {
340 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700341 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700342 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700343 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
344 statusString = res.getString(R.string.battery_info_status_discharging);
345 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
346 statusString = res.getString(R.string.battery_info_status_not_charging);
347 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
348 statusString = res.getString(R.string.battery_info_status_full);
349 } else {
350 statusString = res.getString(R.string.battery_info_status_unknown);
351 }
352
353 return statusString;
354 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700355
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800356 public static void forcePrepareCustomPreferencesList(
357 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
358 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
359 list.setClipToPadding(false);
360 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
361 }
362
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700363 /**
364 * Prepare a custom preferences layout, moving padding to {@link ListView}
365 * when outside scrollbars are requested. Usually used to display
366 * {@link ListView} and {@link TabWidget} with correct padding.
367 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700368 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800369 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700370 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
371 if (movePadding && parent instanceof PreferenceFrameLayout) {
372 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
373
374 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700375 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700376 final int paddingBottom = res.getDimensionPixelSize(
377 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700378
Amith Yamasanif0b05de2012-05-09 09:43:33 -0700379 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
Fabrice Di Megliob27223f2013-01-15 18:54:11 -0800380 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700381 }
382 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700383
384 /**
385 * Return string resource that best describes combination of tethering
386 * options available on this device.
387 */
388 public static int getTetheringLabel(ConnectivityManager cm) {
389 String[] usbRegexs = cm.getTetherableUsbRegexs();
390 String[] wifiRegexs = cm.getTetherableWifiRegexs();
391 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
392
393 boolean usbAvailable = usbRegexs.length != 0;
394 boolean wifiAvailable = wifiRegexs.length != 0;
395 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
396
397 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
398 return R.string.tether_settings_title_all;
399 } else if (wifiAvailable && usbAvailable) {
400 return R.string.tether_settings_title_all;
401 } else if (wifiAvailable && bluetoothAvailable) {
402 return R.string.tether_settings_title_all;
403 } else if (wifiAvailable) {
404 return R.string.tether_settings_title_wifi;
405 } else if (usbAvailable && bluetoothAvailable) {
406 return R.string.tether_settings_title_usb_bluetooth;
407 } else if (usbAvailable) {
408 return R.string.tether_settings_title_usb;
409 } else {
410 return R.string.tether_settings_title_bluetooth;
411 }
412 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700413
414 /* Used by UserSettings as well. Call this on a non-ui thread. */
415 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
416 Uri contactUri = Profile.CONTENT_URI;
417
418 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
419 context.getContentResolver(),
420 contactUri, true);
421 // If there's no profile photo, assign a default avatar
422 if (avatarDataStream == null) {
423 return false;
424 }
425 int userId = user != null ? user.id : UserHandle.myUserId();
426 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700427 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
428 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700429 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700430 avatarDataStream.close();
431 } catch (IOException ioe) { }
432 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700433 }
434
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700435 public static String getMeProfileName(Context context, boolean full) {
436 if (full) {
437 return getProfileDisplayName(context);
438 } else {
439 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700440 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700441 }
442
443 private static String getShorterNameIfPossible(Context context) {
444 final String given = getLocalProfileGivenName(context);
445 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
446 }
447
448 private static String getLocalProfileGivenName(Context context) {
449 final ContentResolver cr = context.getContentResolver();
450
451 // Find the raw contact ID for the local ME profile raw contact.
452 final long localRowProfileId;
453 final Cursor localRawProfile = cr.query(
454 Profile.CONTENT_RAW_CONTACTS_URI,
455 new String[] {RawContacts._ID},
456 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
457 RawContacts.ACCOUNT_NAME + " IS NULL",
458 null, null);
459 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700460
461 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700462 if (!localRawProfile.moveToFirst()) {
463 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700464 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700465 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700466 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700467 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700468 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700469
470 // Find the structured name for the raw contact.
471 final Cursor structuredName = cr.query(
472 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
473 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
474 CommonDataKinds.StructuredName.FAMILY_NAME},
475 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
476 null, null);
477 if (structuredName == null) return null;
478
479 try {
480 if (!structuredName.moveToFirst()) {
481 return null;
482 }
483 String partialName = structuredName.getString(0);
484 if (TextUtils.isEmpty(partialName)) {
485 partialName = structuredName.getString(1);
486 }
487 return partialName;
488 } finally {
489 structuredName.close();
490 }
491 }
492
493 private static final String getProfileDisplayName(Context context) {
494 final ContentResolver cr = context.getContentResolver();
495 final Cursor profile = cr.query(Profile.CONTENT_URI,
496 new String[] {Profile.DISPLAY_NAME}, null, null, null);
497 if (profile == null) return null;
498
499 try {
500 if (!profile.moveToFirst()) {
501 return null;
502 }
503 return profile.getString(0);
504 } finally {
505 profile.close();
506 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700507 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700508
509 /** Not global warming, it's global change warning. */
510 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
511 final Runnable positiveAction) {
512 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
513 builder.setTitle(titleResId);
514 builder.setMessage(R.string.global_change_warning);
515 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
516 @Override
517 public void onClick(DialogInterface dialog, int which) {
518 positiveAction.run();
519 }
520 });
521 builder.setNegativeButton(android.R.string.cancel, null);
522
523 return builder.create();
524 }
525
526 public static boolean hasMultipleUsers(Context context) {
527 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
528 .getUsers().size() > 1;
529 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700530
531 /**
532 * Start a new instance of the activity, showing only the given fragment.
533 * When launched in this mode, the given preference fragment will be instantiated and fill the
534 * entire activity.
535 *
536 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000537 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700538 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700539 * @param resultTo Option fragment that should receive the result of the activity launch.
540 * @param resultRequestCode If resultTo is non-null, this is the request code in which
541 * to report the result.
542 * @param titleResId resource id for the String to display for the title of this set
543 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700544 * @param title String to display for the title of this set of preferences.
545 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000546 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700547 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700548 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
549 titleResId, title, false /* not a shortcut */);
550 }
551
552 public static void startWithFragment(Context context, String fragmentName, Bundle args,
553 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title,
554 boolean isShortcut) {
555 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
556 title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700557 if (resultTo == null) {
558 context.startActivity(intent);
559 } else {
560 resultTo.startActivityForResult(intent, resultRequestCode);
561 }
562 }
563
564 /**
565 * Build an Intent to launch a new activity showing the selected fragment.
566 * The implementation constructs an Intent that re-launches the current activity with the
567 * appropriate arguments to display the fragment.
568 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700569 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700570 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000571 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700572 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700573 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700574 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700575 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700576 * @return Returns an Intent that can be launched to display the given
577 * fragment.
578 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000579 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700580 Bundle args, int titleResId, CharSequence title, boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700581 Intent intent = new Intent(Intent.ACTION_MAIN);
582 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000583 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700584 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700585 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700586 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700587 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700588 return intent;
589 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100590
591 /**
592 * Returns the managed profile of the current user or null if none found.
593 */
594 public static UserHandle getManagedProfile(UserManager userManager) {
595 List<UserHandle> userProfiles = userManager.getUserProfiles();
596 final int count = userProfiles.size();
597 for (int i = 0; i < count; i++) {
598 final UserHandle profile = userProfiles.get(i);
599 if (profile.getIdentifier() == userManager.getUserHandle()) {
600 continue;
601 }
602 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
603 if (userInfo.isManagedProfile()) {
604 return profile;
605 }
606 }
607 return null;
608 }
609
610 /**
611 * Returns true if the current profile is a managed one.
612 */
613 public static boolean isManagedProfile(UserManager userManager) {
614 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
615 return currentUser.isManagedProfile();
616 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100617
618 /**
619 * Returns the {@link UserHandle} of the profile that a settings screen should refer to.
620 *
621 * <p> This takes into account the id of the user that triggered the settings screen.
622 */
623 public static UserHandle getProfileToDisplay(IActivityManager am, IBinder activityToken,
624 Bundle arguments) {
625 int currentUser = UserHandle.getCallingUserId();
626 // Check to see if it was called from a different user
627 try {
628 int launchedFromUser = UserHandle.getUserId(am.getLaunchedFromUid(activityToken));
629 if (launchedFromUser != currentUser) {
630 // This is a forwarded intent
631 return new UserHandle(launchedFromUser);
632 }
633 } catch (RemoteException e) {
634 // Should not happen
635 Log.v(TAG, "Could not get launching user.");
636 }
637 // TODO: Check fragment arguments. See: http://b/15466880
638
639 // Default to current profile
640 return new UserHandle(currentUser);
641 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530642
643 /**
644 * Creates a dialog to confirm with the user if it's ok to remove the user
645 * and delete all the data.
646 *
647 * @param context a Context object
648 * @param removingUserId The userId of the user to remove
649 * @param onConfirmListener Callback object for positive action
650 * @return the created Dialog
651 */
652 public static Dialog createRemoveConfirmationDialog(Context context, int removingUserId,
653 DialogInterface.OnClickListener onConfirmListener) {
654 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
655 UserInfo userInfo = um.getUserInfo(removingUserId);
656 Dialog dlg = new AlertDialog.Builder(context)
657 .setTitle(UserHandle.myUserId() == removingUserId
658 ? R.string.user_confirm_remove_self_title
659 : (userInfo.isRestricted()
660 ? R.string.user_profile_confirm_remove_title
661 : R.string.user_confirm_remove_title))
662 .setMessage(UserHandle.myUserId() == removingUserId
663 ? R.string.user_confirm_remove_self_message
664 : (userInfo.isRestricted()
665 ? R.string.user_profile_confirm_remove_message
666 : R.string.user_confirm_remove_message))
667 .setPositiveButton(R.string.user_delete_button,
668 onConfirmListener)
669 .setNegativeButton(android.R.string.cancel, null)
670 .create();
671 return dlg;
672 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800673}