blob: 4fb166ab551e0bcc1a04abc2a21da802bd1ff8d6 [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
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010019import static android.content.Intent.EXTRA_USER;
20
21import android.annotation.Nullable;
Amith Yamasaniae697552011-09-27 11:33:17 -070022import android.app.ActivityManager;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010023import android.app.ActivityManagerNative;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070024import android.app.AlertDialog;
25import android.app.Dialog;
Fabrice Di Meglio769630c2014-04-24 14:48:48 -070026import android.app.Fragment;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010027import android.app.IActivityManager;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070028import android.content.ContentResolver;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080029import android.content.Context;
Amith Yamasani9627a8e2012-09-23 12:54:14 -070030import android.content.DialogInterface;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080031import android.content.Intent;
32import android.content.pm.ApplicationInfo;
33import android.content.pm.PackageManager;
Amith Yamasani02cf71a2010-09-21 15:48:52 -070034import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070035import android.content.pm.ResolveInfo;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070036import android.content.pm.UserInfo;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020037import android.content.res.Resources;
38import android.content.res.Resources.NotFoundException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070039import android.database.Cursor;
Amith Yamasanif34a85d2012-09-17 18:31:45 -070040import android.graphics.Bitmap;
41import android.graphics.BitmapFactory;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020042import android.graphics.drawable.Drawable;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080043import android.net.ConnectivityManager;
44import android.net.LinkProperties;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070045import android.net.Uri;
Amith Yamasania4379d62011-07-22 10:34:58 -070046import android.os.BatteryManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020047import android.os.Bundle;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010048import android.os.IBinder;
49import android.os.RemoteException;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070050import android.os.UserHandle;
51import android.os.UserManager;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080052import android.preference.Preference;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070053import android.preference.PreferenceFrameLayout;
54import android.preference.PreferenceGroup;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070055import android.provider.ContactsContract.CommonDataKinds;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070056import android.provider.ContactsContract.Contacts;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070057import android.provider.ContactsContract.Data;
Amith Yamasaniae47ef42012-09-16 17:53:35 -070058import android.provider.ContactsContract.Profile;
Amith Yamasani8d40fac2012-10-23 15:36:16 -070059import android.provider.ContactsContract.RawContacts;
Andres Moralesce249fe2014-07-07 16:58:16 -070060import android.service.persistentdata.PersistentDataBlockManager;
Amith Yamasani60133dd2010-09-11 14:17:31 -070061import android.telephony.TelephonyManager;
Anders Hammar1b2dd9032010-04-08 10:03:50 +020062import android.text.TextUtils;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010063import android.util.Log;
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -070064import android.view.View;
65import android.view.ViewGroup;
66import android.widget.ListView;
67import android.widget.TabWidget;
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010068
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010069import com.android.settings.UserSpinnerAdapter.UserDetails;
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070070import com.android.settings.dashboard.DashboardCategory;
71import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010072import com.android.settings.drawable.CircleFramedDrawable;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070073
Amith Yamasaniae47ef42012-09-16 17:53:35 -070074import java.io.IOException;
75import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080076import java.net.InetAddress;
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +010077import java.util.ArrayList;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080078import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070079import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090080import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080081
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070082public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010083 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010084
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080085 /**
86 * Set the preference's title to the matching activity's label.
87 */
88 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
89
90 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090091 * The opacity level of a disabled icon.
92 */
93 public static final float DISABLED_ALPHA = 0.4f;
94
95 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -070096 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
97 * 1 is most bad (red), the last value is least bad (green).
98 */
99 public static final int[] BADNESS_COLORS = new int[] {
100 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
101 0xfffabf2c, 0xff679e37, 0xff0a7f42
102 };
103
104 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200105 * Name of the meta-data item that should be set in the AndroidManifest.xml
106 * to specify the icon that should be displayed for the preference.
107 */
108 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
109
110 /**
111 * Name of the meta-data item that should be set in the AndroidManifest.xml
112 * to specify the title that should be displayed for the preference.
113 */
114 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
115
116 /**
117 * Name of the meta-data item that should be set in the AndroidManifest.xml
118 * to specify the summary text that should be displayed for the preference.
119 */
120 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
121
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100122 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
123
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200124 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800125 * Finds a matching activity for a preference's intent. If a matching
126 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800127 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800128 * @param context The context.
129 * @param parentPreferenceGroup The preference group that contains the
130 * preference whose intent is being resolved.
131 * @param preferenceKey The key of the preference whose intent is being
132 * resolved.
133 * @param flags 0 or one or more of
134 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
135 * .
136 * @return Whether an activity was found. If false, the preference was
137 * removed.
138 */
139 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
140 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800141
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800142 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
143 if (preference == null) {
144 return false;
145 }
Ying Wanga7188322010-01-04 18:45:10 -0800146
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800147 Intent intent = preference.getIntent();
148 if (intent != null) {
149 // Find the activity that is in the system image
150 PackageManager pm = context.getPackageManager();
151 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
152 int listSize = list.size();
153 for (int i = 0; i < listSize; i++) {
154 ResolveInfo resolveInfo = list.get(i);
155 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
156 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800157
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800158 // Replace the intent with this specific activity
159 preference.setIntent(new Intent().setClassName(
160 resolveInfo.activityInfo.packageName,
161 resolveInfo.activityInfo.name));
162
163 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
164 // Set the preference title to the activity's label
165 preference.setTitle(resolveInfo.loadLabel(pm));
166 }
Ying Wanga7188322010-01-04 18:45:10 -0800167
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800168 return true;
169 }
170 }
171 }
172
173 // Did not find a matching activity, so remove the preference
174 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800175
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900176 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800177 }
Ying Wanga7188322010-01-04 18:45:10 -0800178
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700179 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
Amith Yamasani57fd5fd2014-08-06 15:48:10 -0700180 DashboardTile tile) {
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700181
182 Intent intent = tile.intent;
183 if (intent != null) {
184 // Find the activity that is in the system image
185 PackageManager pm = context.getPackageManager();
186 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
187 int listSize = list.size();
188 for (int i = 0; i < listSize; i++) {
189 ResolveInfo resolveInfo = list.get(i);
190 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
191 != 0) {
192 Drawable icon = null;
193 String title = null;
194 String summary = null;
195
196 // Get the activity's meta-data
197 try {
198 Resources res = pm.getResourcesForApplication(
199 resolveInfo.activityInfo.packageName);
200 Bundle metaData = resolveInfo.activityInfo.metaData;
201
202 if (res != null && metaData != null) {
203 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
204 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
205 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
206 }
207 } catch (NameNotFoundException e) {
208 // Ignore
209 } catch (NotFoundException e) {
210 // Ignore
211 }
212
213 // Set the preference title to the activity's label if no
214 // meta-data is found
215 if (TextUtils.isEmpty(title)) {
216 title = resolveInfo.loadLabel(pm).toString();
217 }
218
219 // Set icon, title and summary for the preference
220 // TODO:
221 //tile.icon = icon;
222 tile.title = title;
223 tile.summary = summary;
224 // Replace the intent with this specific activity
225 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
226 resolveInfo.activityInfo.name);
227
228 return true;
229 }
230 }
231 }
232
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700233 return false;
234 }
235
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200236 /**
Ying Wanga7188322010-01-04 18:45:10 -0800237 * Returns true if Monkey is running.
238 */
239 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700240 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800241 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700242
243 /**
244 * Returns whether the device is voice-capable (meaning, it is also a phone).
245 */
246 public static boolean isVoiceCapable(Context context) {
247 TelephonyManager telephony =
248 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
249 return telephony != null && telephony.isVoiceCapable();
250 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800251
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700252 public static boolean isWifiOnly(Context context) {
253 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
254 Context.CONNECTIVITY_SERVICE);
255 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800256 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800257
258 /**
259 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
260 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900261 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800262 */
263 public static String getWifiIpAddresses(Context context) {
264 ConnectivityManager cm = (ConnectivityManager)
265 context.getSystemService(Context.CONNECTIVITY_SERVICE);
266 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700267 return formatIpAddresses(prop);
268 }
269
270 /**
271 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
272 * addresses.
273 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900274 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700275 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900276 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700277 LinkProperties prop = cm.getActiveLinkProperties();
278 return formatIpAddresses(prop);
279 }
280
281 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800282 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900283 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800284 // If there are no entries, return null
285 if (!iter.hasNext()) return null;
286 // Concatenate all available addresses, comma separated
287 String addresses = "";
288 while (iter.hasNext()) {
289 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900290 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800291 }
292 return addresses;
293 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900294
295 public static Locale createLocaleFromString(String localeStr) {
296 // TODO: is there a better way to actually construct a locale that will match?
297 // The main problem is, on top of Java specs, locale.toString() and
298 // new Locale(locale.toString()).toString() do not return equal() strings in
299 // many cases, because the constructor takes the only string as the language
300 // code. So : new Locale("en", "US").toString() => "en_US"
301 // And : new Locale("en_US").toString() => "en_us"
302 if (null == localeStr)
303 return Locale.getDefault();
304 String[] brokenDownLocale = localeStr.split("_", 3);
305 // split may not return a 0-length array.
306 if (1 == brokenDownLocale.length) {
307 return new Locale(brokenDownLocale[0]);
308 } else if (2 == brokenDownLocale.length) {
309 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
310 } else {
311 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
312 }
313 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700314
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900315 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
316 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
317 }
318
Amith Yamasania4379d62011-07-22 10:34:58 -0700319 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700320 return String.valueOf(getBatteryLevel(batteryChangedIntent)) + "%";
321 }
322
323 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900324 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
325 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700326 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700327 }
328
329 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
330 final Intent intent = batteryChangedIntent;
331
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900332 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
333 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
334 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700335 String statusString;
336 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700337 int resId;
338 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
339 resId = R.string.battery_info_status_charging_ac;
340 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
341 resId = R.string.battery_info_status_charging_usb;
342 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
343 resId = R.string.battery_info_status_charging_wireless;
344 } else {
345 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700346 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700347 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700348 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
349 statusString = res.getString(R.string.battery_info_status_discharging);
350 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
351 statusString = res.getString(R.string.battery_info_status_not_charging);
352 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
353 statusString = res.getString(R.string.battery_info_status_full);
354 } else {
355 statusString = res.getString(R.string.battery_info_status_unknown);
356 }
357
358 return statusString;
359 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700360
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800361 public static void forcePrepareCustomPreferencesList(
362 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
363 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
364 list.setClipToPadding(false);
365 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
366 }
367
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700368 /**
369 * Prepare a custom preferences layout, moving padding to {@link ListView}
370 * when outside scrollbars are requested. Usually used to display
371 * {@link ListView} and {@link TabWidget} with correct padding.
372 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700373 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800374 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700375 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700376 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700377 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700378 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700379 final int paddingBottom = res.getDimensionPixelSize(
380 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700381
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700382 if (parent instanceof PreferenceFrameLayout) {
383 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
384
385 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
386 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
387 } else {
388 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
389 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700390 }
391 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700392
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700393 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700394 final Resources res = view.getResources();
395 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700396
397 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
398 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700399 final int paddingBottom = res.getDimensionPixelSize(
400 com.android.internal.R.dimen.preference_fragment_padding_bottom);
401
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700402 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700403 }
404
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700405 /**
406 * Return string resource that best describes combination of tethering
407 * options available on this device.
408 */
409 public static int getTetheringLabel(ConnectivityManager cm) {
410 String[] usbRegexs = cm.getTetherableUsbRegexs();
411 String[] wifiRegexs = cm.getTetherableWifiRegexs();
412 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
413
414 boolean usbAvailable = usbRegexs.length != 0;
415 boolean wifiAvailable = wifiRegexs.length != 0;
416 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
417
418 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
419 return R.string.tether_settings_title_all;
420 } else if (wifiAvailable && usbAvailable) {
421 return R.string.tether_settings_title_all;
422 } else if (wifiAvailable && bluetoothAvailable) {
423 return R.string.tether_settings_title_all;
424 } else if (wifiAvailable) {
425 return R.string.tether_settings_title_wifi;
426 } else if (usbAvailable && bluetoothAvailable) {
427 return R.string.tether_settings_title_usb_bluetooth;
428 } else if (usbAvailable) {
429 return R.string.tether_settings_title_usb;
430 } else {
431 return R.string.tether_settings_title_bluetooth;
432 }
433 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700434
435 /* Used by UserSettings as well. Call this on a non-ui thread. */
436 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
437 Uri contactUri = Profile.CONTENT_URI;
438
439 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
440 context.getContentResolver(),
441 contactUri, true);
442 // If there's no profile photo, assign a default avatar
443 if (avatarDataStream == null) {
444 return false;
445 }
446 int userId = user != null ? user.id : UserHandle.myUserId();
447 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700448 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
449 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700450 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700451 avatarDataStream.close();
452 } catch (IOException ioe) { }
453 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700454 }
455
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700456 public static String getMeProfileName(Context context, boolean full) {
457 if (full) {
458 return getProfileDisplayName(context);
459 } else {
460 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700461 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700462 }
463
464 private static String getShorterNameIfPossible(Context context) {
465 final String given = getLocalProfileGivenName(context);
466 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
467 }
468
469 private static String getLocalProfileGivenName(Context context) {
470 final ContentResolver cr = context.getContentResolver();
471
472 // Find the raw contact ID for the local ME profile raw contact.
473 final long localRowProfileId;
474 final Cursor localRawProfile = cr.query(
475 Profile.CONTENT_RAW_CONTACTS_URI,
476 new String[] {RawContacts._ID},
477 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
478 RawContacts.ACCOUNT_NAME + " IS NULL",
479 null, null);
480 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700481
482 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700483 if (!localRawProfile.moveToFirst()) {
484 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700485 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700486 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700487 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700488 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700489 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700490
491 // Find the structured name for the raw contact.
492 final Cursor structuredName = cr.query(
493 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
494 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
495 CommonDataKinds.StructuredName.FAMILY_NAME},
496 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
497 null, null);
498 if (structuredName == null) return null;
499
500 try {
501 if (!structuredName.moveToFirst()) {
502 return null;
503 }
504 String partialName = structuredName.getString(0);
505 if (TextUtils.isEmpty(partialName)) {
506 partialName = structuredName.getString(1);
507 }
508 return partialName;
509 } finally {
510 structuredName.close();
511 }
512 }
513
514 private static final String getProfileDisplayName(Context context) {
515 final ContentResolver cr = context.getContentResolver();
516 final Cursor profile = cr.query(Profile.CONTENT_URI,
517 new String[] {Profile.DISPLAY_NAME}, null, null, null);
518 if (profile == null) return null;
519
520 try {
521 if (!profile.moveToFirst()) {
522 return null;
523 }
524 return profile.getString(0);
525 } finally {
526 profile.close();
527 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700528 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700529
530 /** Not global warming, it's global change warning. */
531 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
532 final Runnable positiveAction) {
533 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
534 builder.setTitle(titleResId);
535 builder.setMessage(R.string.global_change_warning);
536 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
537 @Override
538 public void onClick(DialogInterface dialog, int which) {
539 positiveAction.run();
540 }
541 });
542 builder.setNegativeButton(android.R.string.cancel, null);
543
544 return builder.create();
545 }
546
547 public static boolean hasMultipleUsers(Context context) {
548 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
549 .getUsers().size() > 1;
550 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700551
552 /**
553 * Start a new instance of the activity, showing only the given fragment.
554 * When launched in this mode, the given preference fragment will be instantiated and fill the
555 * entire activity.
556 *
557 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000558 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700559 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700560 * @param resultTo Option fragment that should receive the result of the activity launch.
561 * @param resultRequestCode If resultTo is non-null, this is the request code in which
562 * to report the result.
563 * @param titleResId resource id for the String to display for the title of this set
564 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700565 * @param title String to display for the title of this set of preferences.
566 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000567 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700568 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700569 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
570 titleResId, title, false /* not a shortcut */);
571 }
572
573 public static void startWithFragment(Context context, String fragmentName, Bundle args,
574 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title,
575 boolean isShortcut) {
576 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
577 title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700578 if (resultTo == null) {
579 context.startActivity(intent);
580 } else {
581 resultTo.startActivityForResult(intent, resultRequestCode);
582 }
583 }
584
585 /**
586 * Build an Intent to launch a new activity showing the selected fragment.
587 * The implementation constructs an Intent that re-launches the current activity with the
588 * appropriate arguments to display the fragment.
589 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700590 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700591 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000592 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700593 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700594 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700595 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700596 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700597 * @return Returns an Intent that can be launched to display the given
598 * fragment.
599 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000600 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700601 Bundle args, int titleResId, CharSequence title, boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700602 Intent intent = new Intent(Intent.ACTION_MAIN);
603 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000604 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700605 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700606 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700607 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700608 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700609 return intent;
610 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100611
612 /**
613 * Returns the managed profile of the current user or null if none found.
614 */
615 public static UserHandle getManagedProfile(UserManager userManager) {
616 List<UserHandle> userProfiles = userManager.getUserProfiles();
617 final int count = userProfiles.size();
618 for (int i = 0; i < count; i++) {
619 final UserHandle profile = userProfiles.get(i);
620 if (profile.getIdentifier() == userManager.getUserHandle()) {
621 continue;
622 }
623 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
624 if (userInfo.isManagedProfile()) {
625 return profile;
626 }
627 }
628 return null;
629 }
630
631 /**
632 * Returns true if the current profile is a managed one.
633 */
634 public static boolean isManagedProfile(UserManager userManager) {
635 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
636 return currentUser.isManagedProfile();
637 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100638
639 /**
Alexandra Gherghina80e1f1b2014-07-31 14:56:33 +0100640 * Creates a {@link UserSpinnerAdapter} if there is more than one profile on the device.
641 *
642 * <p> The adapter can be used to populate a spinner that switches between the Settings
643 * app on the different profiles.
644 *
645 * @return a {@link UserSpinnerAdapter} or null if there is only one profile.
646 */
647 public static UserSpinnerAdapter createUserSpinnerAdapter(UserManager userManager,
648 Context context) {
649 List<UserHandle> userProfiles = userManager.getUserProfiles();
650 if (userProfiles.size() < 2) {
651 return null;
652 }
653
654 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId());
655 // The first option should be the current profile
656 userProfiles.remove(myUserHandle);
657 userProfiles.add(0, myUserHandle);
658
659 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size());
660 final int count = userProfiles.size();
661 for (int i = 0; i < count; i++) {
662 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context));
663 }
664 return new UserSpinnerAdapter(context, userDetails);
665 }
666
667 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100668 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100669 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100670 * The target user can be either the current user, the user that launched this activity or
671 * the user contained as an extra in the arguments or intent extras.
672 *
673 * Note: This is secure in the sense that it only returns a target user different to the current
674 * one if the app launching this activity is the Settings app itself, running in the same user
675 * or in one that is in the same profile group, or if the user id is provided by the system.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100676 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100677 public static UserHandle getSecureTargetUser(IBinder activityToken,
678 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
679 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
680 IActivityManager am = ActivityManagerNative.getDefault();
681 try {
682 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
683 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
684
685 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
686 am.getLaunchedFromUid(activityToken)));
687 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
688 // Check it's secure
689 if (isProfileOf(um, launchedFromUser)) {
690 return launchedFromUser;
691 }
692 }
693 UserHandle extrasUser = intentExtras != null
694 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
695 if (extrasUser != null && !extrasUser.equals(currentUser)) {
696 // Check it's secure
697 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
698 return extrasUser;
699 }
700 }
701 UserHandle argumentsUser = arguments != null
702 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
703 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
704 // Check it's secure
705 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
706 return argumentsUser;
707 }
708 }
709 } catch (RemoteException e) {
710 // Should not happen
711 Log.v(TAG, "Could not talk to activity manager.", e);
712 }
713 return currentUser;
714 }
715
716 /**
717 * Returns the target user for a Settings activity.
718 *
719 * The target user can be either the current user, the user that launched this activity or
720 * the user contained as an extra in the arguments or intent extras.
721 *
722 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
723 * possible.
724 *
725 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
726 */
727 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
728 @Nullable Bundle intentExtras) {
729 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
730 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100731 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100732 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
733 am.getLaunchedFromUid(activityToken)));
734 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
735 return launchedFromUser;
736 }
737 UserHandle extrasUser = intentExtras != null
738 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
739 if (extrasUser != null && !extrasUser.equals(currentUser)) {
740 return extrasUser;
741 }
742 UserHandle argumentsUser = arguments != null
743 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
744 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
745 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100746 }
747 } catch (RemoteException e) {
748 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100749 Log.v(TAG, "Could not talk to activity manager.", e);
750 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100751 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100752 return currentUser;
753 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100754
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100755 /**
756 * Returns true if the user provided is in the same profiles group as the current user.
757 */
758 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
759 if (um == null || otherUser == null) return false;
760 return (UserHandle.myUserId() == otherUser.getIdentifier())
761 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100762 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530763
764 /**
765 * Creates a dialog to confirm with the user if it's ok to remove the user
766 * and delete all the data.
767 *
768 * @param context a Context object
769 * @param removingUserId The userId of the user to remove
770 * @param onConfirmListener Callback object for positive action
771 * @return the created Dialog
772 */
773 public static Dialog createRemoveConfirmationDialog(Context context, int removingUserId,
774 DialogInterface.OnClickListener onConfirmListener) {
775 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
776 UserInfo userInfo = um.getUserInfo(removingUserId);
Alexandra Gherghina4c962672014-08-22 11:17:29 +0100777 int titleResId;
778 int messageResId;
779 if (UserHandle.myUserId() == removingUserId) {
780 titleResId = R.string.user_confirm_remove_self_title;
781 messageResId = R.string.user_confirm_remove_self_message;
782 } else if (userInfo.isRestricted()) {
783 titleResId = R.string.user_profile_confirm_remove_title;
784 messageResId = R.string.user_profile_confirm_remove_message;
785 } else if (userInfo.isManagedProfile()) {
786 titleResId = R.string.work_profile_confirm_remove_title;
787 messageResId = R.string.work_profile_confirm_remove_message;
788 } else {
789 titleResId = R.string.user_confirm_remove_title;
790 messageResId = R.string.user_confirm_remove_message;
791 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530792 Dialog dlg = new AlertDialog.Builder(context)
Alexandra Gherghina4c962672014-08-22 11:17:29 +0100793 .setTitle(titleResId)
794 .setMessage(messageResId)
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530795 .setPositiveButton(R.string.user_delete_button,
796 onConfirmListener)
797 .setNegativeButton(android.R.string.cancel, null)
798 .create();
799 return dlg;
800 }
Andres Moralesce249fe2014-07-07 16:58:16 -0700801
802 /**
803 * Returns whether or not this device is able to be OEM unlocked.
804 */
805 static boolean isOemUnlockEnabled(Context context) {
806 PersistentDataBlockManager manager =(PersistentDataBlockManager)
807 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
808 return manager.getOemUnlockEnabled();
809 }
810
811 /**
812 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
813 * devices allow users to flash other OSes to them.
814 */
815 static void setOemUnlockEnabled(Context context, boolean enabled) {
816 PersistentDataBlockManager manager =(PersistentDataBlockManager)
817 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
818 manager.setOemUnlockEnabled(enabled);
819 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100820
821 /**
822 * Returns a circular icon for a user.
823 */
824 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
825 if (user.iconPath == null) return null;
826 Bitmap icon = um.getUserIcon(user.id);
827 if (icon == null) return null;
828 return CircleFramedDrawable.getInstance(context, icon);
829 }
Fabrice Di Meglio22a2a492014-08-08 12:27:57 -0700830
831 /**
832 * Return whether or not the user should have a SIM Cards option in Settings.
833 * TODO: Change back to returning true if count is greater than one after testing.
834 * TODO: See bug 16533525.
835 */
836 public static boolean showSimCardTile(Context context) {
837 final TelephonyManager tm =
838 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
839
840 return tm.getSimCount() > 0;
841 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800842}