blob: feee90ebd2e5e97faea9ba6cbb32b034271b7a80 [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
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -070069import com.android.settings.dashboard.DashboardCategory;
70import com.android.settings.dashboard.DashboardTile;
Alexandra Gherghinafe47a8d2014-07-18 17:23:37 +010071import com.android.settings.drawable.CircleFramedDrawable;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070072
Amith Yamasaniae47ef42012-09-16 17:53:35 -070073import java.io.IOException;
74import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080075import java.net.InetAddress;
76import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070077import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090078import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080079
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070080public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010081 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010082
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080083 /**
84 * Set the preference's title to the matching activity's label.
85 */
86 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
87
88 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090089 * The opacity level of a disabled icon.
90 */
91 public static final float DISABLED_ALPHA = 0.4f;
92
93 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -070094 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
95 * 1 is most bad (red), the last value is least bad (green).
96 */
97 public static final int[] BADNESS_COLORS = new int[] {
98 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
99 0xfffabf2c, 0xff679e37, 0xff0a7f42
100 };
101
102 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200103 * Name of the meta-data item that should be set in the AndroidManifest.xml
104 * to specify the icon that should be displayed for the preference.
105 */
106 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
107
108 /**
109 * Name of the meta-data item that should be set in the AndroidManifest.xml
110 * to specify the title that should be displayed for the preference.
111 */
112 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
113
114 /**
115 * Name of the meta-data item that should be set in the AndroidManifest.xml
116 * to specify the summary text that should be displayed for the preference.
117 */
118 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
119
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100120 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
121
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200122 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800123 * Finds a matching activity for a preference's intent. If a matching
124 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800125 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800126 * @param context The context.
127 * @param parentPreferenceGroup The preference group that contains the
128 * preference whose intent is being resolved.
129 * @param preferenceKey The key of the preference whose intent is being
130 * resolved.
131 * @param flags 0 or one or more of
132 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
133 * .
134 * @return Whether an activity was found. If false, the preference was
135 * removed.
136 */
137 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
138 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800139
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800140 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
141 if (preference == null) {
142 return false;
143 }
Ying Wanga7188322010-01-04 18:45:10 -0800144
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800145 Intent intent = preference.getIntent();
146 if (intent != null) {
147 // Find the activity that is in the system image
148 PackageManager pm = context.getPackageManager();
149 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
150 int listSize = list.size();
151 for (int i = 0; i < listSize; i++) {
152 ResolveInfo resolveInfo = list.get(i);
153 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
154 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800155
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800156 // Replace the intent with this specific activity
157 preference.setIntent(new Intent().setClassName(
158 resolveInfo.activityInfo.packageName,
159 resolveInfo.activityInfo.name));
160
161 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
162 // Set the preference title to the activity's label
163 preference.setTitle(resolveInfo.loadLabel(pm));
164 }
Ying Wanga7188322010-01-04 18:45:10 -0800165
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800166 return true;
167 }
168 }
169 }
170
171 // Did not find a matching activity, so remove the preference
172 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800173
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900174 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800175 }
Ying Wanga7188322010-01-04 18:45:10 -0800176
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700177 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
178 DashboardCategory target, DashboardTile tile) {
179
180 Intent intent = tile.intent;
181 if (intent != null) {
182 // Find the activity that is in the system image
183 PackageManager pm = context.getPackageManager();
184 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
185 int listSize = list.size();
186 for (int i = 0; i < listSize; i++) {
187 ResolveInfo resolveInfo = list.get(i);
188 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
189 != 0) {
190 Drawable icon = null;
191 String title = null;
192 String summary = null;
193
194 // Get the activity's meta-data
195 try {
196 Resources res = pm.getResourcesForApplication(
197 resolveInfo.activityInfo.packageName);
198 Bundle metaData = resolveInfo.activityInfo.metaData;
199
200 if (res != null && metaData != null) {
201 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
202 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
203 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
204 }
205 } catch (NameNotFoundException e) {
206 // Ignore
207 } catch (NotFoundException e) {
208 // Ignore
209 }
210
211 // Set the preference title to the activity's label if no
212 // meta-data is found
213 if (TextUtils.isEmpty(title)) {
214 title = resolveInfo.loadLabel(pm).toString();
215 }
216
217 // Set icon, title and summary for the preference
218 // TODO:
219 //tile.icon = icon;
220 tile.title = title;
221 tile.summary = summary;
222 // Replace the intent with this specific activity
223 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
224 resolveInfo.activityInfo.name);
225
226 return true;
227 }
228 }
229 }
230
231 // Did not find a matching activity, so remove the preference
232 target.removeTile(tile);
233
234 return false;
235 }
236
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200237 /**
Ying Wanga7188322010-01-04 18:45:10 -0800238 * Returns true if Monkey is running.
239 */
240 public static boolean isMonkeyRunning() {
Amith Yamasaniae697552011-09-27 11:33:17 -0700241 return ActivityManager.isUserAMonkey();
Ying Wanga7188322010-01-04 18:45:10 -0800242 }
Amith Yamasani60133dd2010-09-11 14:17:31 -0700243
244 /**
245 * Returns whether the device is voice-capable (meaning, it is also a phone).
246 */
247 public static boolean isVoiceCapable(Context context) {
248 TelephonyManager telephony =
249 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
250 return telephony != null && telephony.isVoiceCapable();
251 }
Amith Yamasani0f85c482011-02-23 17:19:11 -0800252
Robert Greenwalt8af88fb2011-08-31 11:17:47 -0700253 public static boolean isWifiOnly(Context context) {
254 ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
255 Context.CONNECTIVITY_SERVICE);
256 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false);
Amith Yamasani0f85c482011-02-23 17:19:11 -0800257 }
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800258
259 /**
260 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses.
261 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900262 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800263 */
264 public static String getWifiIpAddresses(Context context) {
265 ConnectivityManager cm = (ConnectivityManager)
266 context.getSystemService(Context.CONNECTIVITY_SERVICE);
267 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI);
Amith Yamasani6822b742011-10-17 16:41:00 -0700268 return formatIpAddresses(prop);
269 }
270
271 /**
272 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style
273 * addresses.
274 * @param context the application context
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900275 * @return the formatted and newline-separated IP addresses, or null if none.
Amith Yamasani6822b742011-10-17 16:41:00 -0700276 */
Lorenzo Colitti6eb6a902013-11-08 03:53:29 +0900277 public static String getDefaultIpAddresses(ConnectivityManager cm) {
Amith Yamasani6822b742011-10-17 16:41:00 -0700278 LinkProperties prop = cm.getActiveLinkProperties();
279 return formatIpAddresses(prop);
280 }
281
282 private static String formatIpAddresses(LinkProperties prop) {
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800283 if (prop == null) return null;
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900284 Iterator<InetAddress> iter = prop.getAllAddresses().iterator();
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800285 // If there are no entries, return null
286 if (!iter.hasNext()) return null;
287 // Concatenate all available addresses, comma separated
288 String addresses = "";
289 while (iter.hasNext()) {
290 addresses += iter.next().getHostAddress();
Lorenzo Colitti769f0692013-08-01 17:30:07 +0900291 if (iter.hasNext()) addresses += "\n";
Amith Yamasanic06d4c42011-02-25 14:35:20 -0800292 }
293 return addresses;
294 }
Jean Chalard71ad1f42011-05-12 15:06:16 +0900295
296 public static Locale createLocaleFromString(String localeStr) {
297 // TODO: is there a better way to actually construct a locale that will match?
298 // The main problem is, on top of Java specs, locale.toString() and
299 // new Locale(locale.toString()).toString() do not return equal() strings in
300 // many cases, because the constructor takes the only string as the language
301 // code. So : new Locale("en", "US").toString() => "en_US"
302 // And : new Locale("en_US").toString() => "en_us"
303 if (null == localeStr)
304 return Locale.getDefault();
305 String[] brokenDownLocale = localeStr.split("_", 3);
306 // split may not return a 0-length array.
307 if (1 == brokenDownLocale.length) {
308 return new Locale(brokenDownLocale[0]);
309 } else if (2 == brokenDownLocale.length) {
310 return new Locale(brokenDownLocale[0], brokenDownLocale[1]);
311 } else {
312 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]);
313 }
314 }
Amith Yamasania4379d62011-07-22 10:34:58 -0700315
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900316 public static boolean isBatteryPresent(Intent batteryChangedIntent) {
317 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true);
318 }
319
Amith Yamasania4379d62011-07-22 10:34:58 -0700320 public static String getBatteryPercentage(Intent batteryChangedIntent) {
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700321 return String.valueOf(getBatteryLevel(batteryChangedIntent)) + "%";
322 }
323
324 public static int getBatteryLevel(Intent batteryChangedIntent) {
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900325 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
326 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
Dianne Hackborn525f2bd2014-04-29 11:24:06 -0700327 return (level * 100) / scale;
Amith Yamasania4379d62011-07-22 10:34:58 -0700328 }
329
330 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) {
331 final Intent intent = batteryChangedIntent;
332
Jaewan Kima3fe77b2013-06-04 21:17:40 +0900333 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
334 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
335 BatteryManager.BATTERY_STATUS_UNKNOWN);
Amith Yamasania4379d62011-07-22 10:34:58 -0700336 String statusString;
337 if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700338 int resId;
339 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) {
340 resId = R.string.battery_info_status_charging_ac;
341 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) {
342 resId = R.string.battery_info_status_charging_usb;
343 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
344 resId = R.string.battery_info_status_charging_wireless;
345 } else {
346 resId = R.string.battery_info_status_charging;
Amith Yamasania4379d62011-07-22 10:34:58 -0700347 }
Dianne Hackborn5a9ace32014-05-15 17:04:42 -0700348 statusString = res.getString(resId);
Amith Yamasania4379d62011-07-22 10:34:58 -0700349 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
350 statusString = res.getString(R.string.battery_info_status_discharging);
351 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
352 statusString = res.getString(R.string.battery_info_status_not_charging);
353 } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
354 statusString = res.getString(R.string.battery_info_status_full);
355 } else {
356 statusString = res.getString(R.string.battery_info_status_unknown);
357 }
358
359 return statusString;
360 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700361
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800362 public static void forcePrepareCustomPreferencesList(
363 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) {
364 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
365 list.setClipToPadding(false);
366 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding);
367 }
368
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700369 /**
370 * Prepare a custom preferences layout, moving padding to {@link ListView}
371 * when outside scrollbars are requested. Usually used to display
372 * {@link ListView} and {@link TabWidget} with correct padding.
373 */
Jeff Sharkey5d706792011-09-08 18:57:17 -0700374 public static void prepareCustomPreferencesList(
Jeff Sharkey97d07fa2012-11-30 12:36:53 -0800375 ViewGroup parent, View child, View list, boolean ignoreSidePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700376 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY;
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700377 if (movePadding) {
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700378 final Resources res = list.getResources();
Amith Yamasani56f51a82013-08-05 10:07:23 -0700379 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700380 final int paddingBottom = res.getDimensionPixelSize(
381 com.android.internal.R.dimen.preference_fragment_padding_bottom);
Jeff Sharkey5d706792011-09-08 18:57:17 -0700382
Fabrice Di Meglio97a18c82014-07-18 19:12:36 -0700383 if (parent instanceof PreferenceFrameLayout) {
384 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true;
385
386 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide;
387 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom);
388 } else {
389 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
390 }
Jeff Sharkeyb654cbb2011-08-18 11:59:19 -0700391 }
392 }
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700393
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700394 public static void forceCustomPadding(View view, boolean additive) {
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700395 final Resources res = view.getResources();
396 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700397
398 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0);
399 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700400 final int paddingBottom = res.getDimensionPixelSize(
401 com.android.internal.R.dimen.preference_fragment_padding_bottom);
402
Fabrice Di Meglio0f4a7792014-07-28 18:25:14 -0700403 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom);
Fabrice Di Meglio38ba9a22014-07-18 19:58:50 -0700404 }
405
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700406 /**
407 * Return string resource that best describes combination of tethering
408 * options available on this device.
409 */
410 public static int getTetheringLabel(ConnectivityManager cm) {
411 String[] usbRegexs = cm.getTetherableUsbRegexs();
412 String[] wifiRegexs = cm.getTetherableWifiRegexs();
413 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
414
415 boolean usbAvailable = usbRegexs.length != 0;
416 boolean wifiAvailable = wifiRegexs.length != 0;
417 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
418
419 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
420 return R.string.tether_settings_title_all;
421 } else if (wifiAvailable && usbAvailable) {
422 return R.string.tether_settings_title_all;
423 } else if (wifiAvailable && bluetoothAvailable) {
424 return R.string.tether_settings_title_all;
425 } else if (wifiAvailable) {
426 return R.string.tether_settings_title_wifi;
427 } else if (usbAvailable && bluetoothAvailable) {
428 return R.string.tether_settings_title_usb_bluetooth;
429 } else if (usbAvailable) {
430 return R.string.tether_settings_title_usb;
431 } else {
432 return R.string.tether_settings_title_bluetooth;
433 }
434 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700435
436 /* Used by UserSettings as well. Call this on a non-ui thread. */
437 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
438 Uri contactUri = Profile.CONTENT_URI;
439
440 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
441 context.getContentResolver(),
442 contactUri, true);
443 // If there's no profile photo, assign a default avatar
444 if (avatarDataStream == null) {
445 return false;
446 }
447 int userId = user != null ? user.id : UserHandle.myUserId();
448 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700449 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
450 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700451 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700452 avatarDataStream.close();
453 } catch (IOException ioe) { }
454 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700455 }
456
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700457 public static String getMeProfileName(Context context, boolean full) {
458 if (full) {
459 return getProfileDisplayName(context);
460 } else {
461 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700462 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700463 }
464
465 private static String getShorterNameIfPossible(Context context) {
466 final String given = getLocalProfileGivenName(context);
467 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
468 }
469
470 private static String getLocalProfileGivenName(Context context) {
471 final ContentResolver cr = context.getContentResolver();
472
473 // Find the raw contact ID for the local ME profile raw contact.
474 final long localRowProfileId;
475 final Cursor localRawProfile = cr.query(
476 Profile.CONTENT_RAW_CONTACTS_URI,
477 new String[] {RawContacts._ID},
478 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
479 RawContacts.ACCOUNT_NAME + " IS NULL",
480 null, null);
481 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700482
483 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700484 if (!localRawProfile.moveToFirst()) {
485 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700486 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700487 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700488 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700489 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700490 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700491
492 // Find the structured name for the raw contact.
493 final Cursor structuredName = cr.query(
494 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
495 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
496 CommonDataKinds.StructuredName.FAMILY_NAME},
497 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
498 null, null);
499 if (structuredName == null) return null;
500
501 try {
502 if (!structuredName.moveToFirst()) {
503 return null;
504 }
505 String partialName = structuredName.getString(0);
506 if (TextUtils.isEmpty(partialName)) {
507 partialName = structuredName.getString(1);
508 }
509 return partialName;
510 } finally {
511 structuredName.close();
512 }
513 }
514
515 private static final String getProfileDisplayName(Context context) {
516 final ContentResolver cr = context.getContentResolver();
517 final Cursor profile = cr.query(Profile.CONTENT_URI,
518 new String[] {Profile.DISPLAY_NAME}, null, null, null);
519 if (profile == null) return null;
520
521 try {
522 if (!profile.moveToFirst()) {
523 return null;
524 }
525 return profile.getString(0);
526 } finally {
527 profile.close();
528 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700529 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700530
531 /** Not global warming, it's global change warning. */
532 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
533 final Runnable positiveAction) {
534 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
535 builder.setTitle(titleResId);
536 builder.setMessage(R.string.global_change_warning);
537 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
538 @Override
539 public void onClick(DialogInterface dialog, int which) {
540 positiveAction.run();
541 }
542 });
543 builder.setNegativeButton(android.R.string.cancel, null);
544
545 return builder.create();
546 }
547
548 public static boolean hasMultipleUsers(Context context) {
549 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
550 .getUsers().size() > 1;
551 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700552
553 /**
554 * Start a new instance of the activity, showing only the given fragment.
555 * When launched in this mode, the given preference fragment will be instantiated and fill the
556 * entire activity.
557 *
558 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000559 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700560 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700561 * @param resultTo Option fragment that should receive the result of the activity launch.
562 * @param resultRequestCode If resultTo is non-null, this is the request code in which
563 * to report the result.
564 * @param titleResId resource id for the String to display for the title of this set
565 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700566 * @param title String to display for the title of this set of preferences.
567 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000568 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700569 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700570 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
571 titleResId, title, false /* not a shortcut */);
572 }
573
574 public static void startWithFragment(Context context, String fragmentName, Bundle args,
575 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title,
576 boolean isShortcut) {
577 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
578 title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700579 if (resultTo == null) {
580 context.startActivity(intent);
581 } else {
582 resultTo.startActivityForResult(intent, resultRequestCode);
583 }
584 }
585
586 /**
587 * Build an Intent to launch a new activity showing the selected fragment.
588 * The implementation constructs an Intent that re-launches the current activity with the
589 * appropriate arguments to display the fragment.
590 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700591 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700592 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000593 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700594 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700595 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700596 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700597 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700598 * @return Returns an Intent that can be launched to display the given
599 * fragment.
600 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000601 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700602 Bundle args, int titleResId, CharSequence title, boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700603 Intent intent = new Intent(Intent.ACTION_MAIN);
604 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000605 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700606 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700607 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700608 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700609 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700610 return intent;
611 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100612
613 /**
614 * Returns the managed profile of the current user or null if none found.
615 */
616 public static UserHandle getManagedProfile(UserManager userManager) {
617 List<UserHandle> userProfiles = userManager.getUserProfiles();
618 final int count = userProfiles.size();
619 for (int i = 0; i < count; i++) {
620 final UserHandle profile = userProfiles.get(i);
621 if (profile.getIdentifier() == userManager.getUserHandle()) {
622 continue;
623 }
624 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
625 if (userInfo.isManagedProfile()) {
626 return profile;
627 }
628 }
629 return null;
630 }
631
632 /**
633 * Returns true if the current profile is a managed one.
634 */
635 public static boolean isManagedProfile(UserManager userManager) {
636 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
637 return currentUser.isManagedProfile();
638 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100639
640 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100641 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100642 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100643 * The target user can be either the current user, the user that launched this activity or
644 * the user contained as an extra in the arguments or intent extras.
645 *
646 * Note: This is secure in the sense that it only returns a target user different to the current
647 * one if the app launching this activity is the Settings app itself, running in the same user
648 * 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 +0100649 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100650 public static UserHandle getSecureTargetUser(IBinder activityToken,
651 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
652 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
653 IActivityManager am = ActivityManagerNative.getDefault();
654 try {
655 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
656 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
657
658 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
659 am.getLaunchedFromUid(activityToken)));
660 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
661 // Check it's secure
662 if (isProfileOf(um, launchedFromUser)) {
663 return launchedFromUser;
664 }
665 }
666 UserHandle extrasUser = intentExtras != null
667 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
668 if (extrasUser != null && !extrasUser.equals(currentUser)) {
669 // Check it's secure
670 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
671 return extrasUser;
672 }
673 }
674 UserHandle argumentsUser = arguments != null
675 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
676 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
677 // Check it's secure
678 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
679 return argumentsUser;
680 }
681 }
682 } catch (RemoteException e) {
683 // Should not happen
684 Log.v(TAG, "Could not talk to activity manager.", e);
685 }
686 return currentUser;
687 }
688
689 /**
690 * Returns the target user for a Settings activity.
691 *
692 * The target user can be either the current user, the user that launched this activity or
693 * the user contained as an extra in the arguments or intent extras.
694 *
695 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
696 * possible.
697 *
698 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
699 */
700 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
701 @Nullable Bundle intentExtras) {
702 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
703 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100704 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100705 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
706 am.getLaunchedFromUid(activityToken)));
707 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
708 return launchedFromUser;
709 }
710 UserHandle extrasUser = intentExtras != null
711 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
712 if (extrasUser != null && !extrasUser.equals(currentUser)) {
713 return extrasUser;
714 }
715 UserHandle argumentsUser = arguments != null
716 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
717 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
718 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100719 }
720 } catch (RemoteException e) {
721 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100722 Log.v(TAG, "Could not talk to activity manager.", e);
723 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100724 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100725 return currentUser;
726 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100727
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100728 /**
729 * Returns true if the user provided is in the same profiles group as the current user.
730 */
731 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
732 if (um == null || otherUser == null) return false;
733 return (UserHandle.myUserId() == otherUser.getIdentifier())
734 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100735 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530736
737 /**
738 * Creates a dialog to confirm with the user if it's ok to remove the user
739 * and delete all the data.
740 *
741 * @param context a Context object
742 * @param removingUserId The userId of the user to remove
743 * @param onConfirmListener Callback object for positive action
744 * @return the created Dialog
745 */
746 public static Dialog createRemoveConfirmationDialog(Context context, int removingUserId,
747 DialogInterface.OnClickListener onConfirmListener) {
748 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
749 UserInfo userInfo = um.getUserInfo(removingUserId);
750 Dialog dlg = new AlertDialog.Builder(context)
751 .setTitle(UserHandle.myUserId() == removingUserId
752 ? R.string.user_confirm_remove_self_title
753 : (userInfo.isRestricted()
754 ? R.string.user_profile_confirm_remove_title
755 : R.string.user_confirm_remove_title))
756 .setMessage(UserHandle.myUserId() == removingUserId
757 ? R.string.user_confirm_remove_self_message
758 : (userInfo.isRestricted()
759 ? R.string.user_profile_confirm_remove_message
760 : R.string.user_confirm_remove_message))
761 .setPositiveButton(R.string.user_delete_button,
762 onConfirmListener)
763 .setNegativeButton(android.R.string.cancel, null)
764 .create();
765 return dlg;
766 }
Andres Moralesce249fe2014-07-07 16:58:16 -0700767
768 /**
769 * Returns whether or not this device is able to be OEM unlocked.
770 */
771 static boolean isOemUnlockEnabled(Context context) {
772 PersistentDataBlockManager manager =(PersistentDataBlockManager)
773 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
774 return manager.getOemUnlockEnabled();
775 }
776
777 /**
778 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
779 * devices allow users to flash other OSes to them.
780 */
781 static void setOemUnlockEnabled(Context context, boolean enabled) {
782 PersistentDataBlockManager manager =(PersistentDataBlockManager)
783 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
784 manager.setOemUnlockEnabled(enabled);
785 }
Alexandra Gherghina95b86a52014-07-24 19:13:25 +0100786
787 /**
788 * Returns a circular icon for a user.
789 */
790 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) {
791 if (user.iconPath == null) return null;
792 Bitmap icon = um.getUserIcon(user.id);
793 if (icon == null) return null;
794 return CircleFramedDrawable.getInstance(context, icon);
795 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800796}