blob: cd5dec7a5edcf21d335800444372d6ab5270f7fa [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;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070071
Amith Yamasaniae47ef42012-09-16 17:53:35 -070072import java.io.IOException;
73import java.io.InputStream;
Amith Yamasanic06d4c42011-02-25 14:35:20 -080074import java.net.InetAddress;
75import java.util.Iterator;
Daisuke Miyakawaa2633d02010-09-15 20:09:12 -070076import java.util.List;
Jean Chalard71ad1f42011-05-12 15:06:16 +090077import java.util.Locale;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080078
Fabrice Di Meglioc9711be2014-06-17 12:30:18 -070079public final class Utils {
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +010080 private static final String TAG = "Settings";
Alexandra Gherghina7d748c02014-06-27 12:33:42 +010081
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -080082 /**
83 * Set the preference's title to the matching activity's label.
84 */
85 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1;
86
87 /**
Shuhrat Dehkanov96577682012-10-03 12:24:07 +090088 * The opacity level of a disabled icon.
89 */
90 public static final float DISABLED_ALPHA = 0.4f;
91
92 /**
Dianne Hackborn68f005f2014-06-18 18:29:12 -070093 * Color spectrum to use to indicate badness. 0 is completely transparent (no data),
94 * 1 is most bad (red), the last value is least bad (green).
95 */
96 public static final int[] BADNESS_COLORS = new int[] {
97 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00,
98 0xfffabf2c, 0xff679e37, 0xff0a7f42
99 };
100
101 /**
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200102 * Name of the meta-data item that should be set in the AndroidManifest.xml
103 * to specify the icon that should be displayed for the preference.
104 */
105 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon";
106
107 /**
108 * Name of the meta-data item that should be set in the AndroidManifest.xml
109 * to specify the title that should be displayed for the preference.
110 */
111 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title";
112
113 /**
114 * Name of the meta-data item that should be set in the AndroidManifest.xml
115 * to specify the summary text that should be displayed for the preference.
116 */
117 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary";
118
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100119 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings";
120
Anders Hammar1b2dd9032010-04-08 10:03:50 +0200121 /**
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800122 * Finds a matching activity for a preference's intent. If a matching
123 * activity is not found, it will remove the preference.
Ying Wanga7188322010-01-04 18:45:10 -0800124 *
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800125 * @param context The context.
126 * @param parentPreferenceGroup The preference group that contains the
127 * preference whose intent is being resolved.
128 * @param preferenceKey The key of the preference whose intent is being
129 * resolved.
130 * @param flags 0 or one or more of
131 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY}
132 * .
133 * @return Whether an activity was found. If false, the preference was
134 * removed.
135 */
136 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context,
137 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) {
Ying Wanga7188322010-01-04 18:45:10 -0800138
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800139 Preference preference = parentPreferenceGroup.findPreference(preferenceKey);
140 if (preference == null) {
141 return false;
142 }
Ying Wanga7188322010-01-04 18:45:10 -0800143
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800144 Intent intent = preference.getIntent();
145 if (intent != null) {
146 // Find the activity that is in the system image
147 PackageManager pm = context.getPackageManager();
148 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
149 int listSize = list.size();
150 for (int i = 0; i < listSize; i++) {
151 ResolveInfo resolveInfo = list.get(i);
152 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
153 != 0) {
Ying Wanga7188322010-01-04 18:45:10 -0800154
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800155 // Replace the intent with this specific activity
156 preference.setIntent(new Intent().setClassName(
157 resolveInfo.activityInfo.packageName,
158 resolveInfo.activityInfo.name));
159
160 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) {
161 // Set the preference title to the activity's label
162 preference.setTitle(resolveInfo.loadLabel(pm));
163 }
Ying Wanga7188322010-01-04 18:45:10 -0800164
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800165 return true;
166 }
167 }
168 }
169
170 // Did not find a matching activity, so remove the preference
171 parentPreferenceGroup.removePreference(preference);
Ying Wanga7188322010-01-04 18:45:10 -0800172
Shuhrat Dehkanov7dc567a2012-04-23 01:59:56 +0900173 return false;
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800174 }
Ying Wanga7188322010-01-04 18:45:10 -0800175
Fabrice Di Meglio63bbb8e2014-04-23 16:44:30 -0700176 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context,
177 DashboardCategory target, DashboardTile tile) {
178
179 Intent intent = tile.intent;
180 if (intent != null) {
181 // Find the activity that is in the system image
182 PackageManager pm = context.getPackageManager();
183 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA);
184 int listSize = list.size();
185 for (int i = 0; i < listSize; i++) {
186 ResolveInfo resolveInfo = list.get(i);
187 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)
188 != 0) {
189 Drawable icon = null;
190 String title = null;
191 String summary = null;
192
193 // Get the activity's meta-data
194 try {
195 Resources res = pm.getResourcesForApplication(
196 resolveInfo.activityInfo.packageName);
197 Bundle metaData = resolveInfo.activityInfo.metaData;
198
199 if (res != null && metaData != null) {
200 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON));
201 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE));
202 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY));
203 }
204 } catch (NameNotFoundException e) {
205 // Ignore
206 } catch (NotFoundException e) {
207 // Ignore
208 }
209
210 // Set the preference title to the activity's label if no
211 // meta-data is found
212 if (TextUtils.isEmpty(title)) {
213 title = resolveInfo.loadLabel(pm).toString();
214 }
215
216 // Set icon, title and summary for the preference
217 // TODO:
218 //tile.icon = icon;
219 tile.title = title;
220 tile.summary = summary;
221 // Replace the intent with this specific activity
222 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName,
223 resolveInfo.activityInfo.name);
224
225 return true;
226 }
227 }
228 }
229
230 // Did not find a matching activity, so remove the preference
231 target.removeTile(tile);
232
233 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 Meglio38ba9a22014-07-18 19:58:50 -0700393 public static void forceCustomPadding(View view) {
394 final Resources res = view.getResources();
395 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin);
396 final int paddingBottom = res.getDimensionPixelSize(
397 com.android.internal.R.dimen.preference_fragment_padding_bottom);
398
399 view.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom);
400 }
401
Jeff Sharkeya83a24f2011-09-16 01:52:39 -0700402 /**
403 * Return string resource that best describes combination of tethering
404 * options available on this device.
405 */
406 public static int getTetheringLabel(ConnectivityManager cm) {
407 String[] usbRegexs = cm.getTetherableUsbRegexs();
408 String[] wifiRegexs = cm.getTetherableWifiRegexs();
409 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs();
410
411 boolean usbAvailable = usbRegexs.length != 0;
412 boolean wifiAvailable = wifiRegexs.length != 0;
413 boolean bluetoothAvailable = bluetoothRegexs.length != 0;
414
415 if (wifiAvailable && usbAvailable && bluetoothAvailable) {
416 return R.string.tether_settings_title_all;
417 } else if (wifiAvailable && usbAvailable) {
418 return R.string.tether_settings_title_all;
419 } else if (wifiAvailable && bluetoothAvailable) {
420 return R.string.tether_settings_title_all;
421 } else if (wifiAvailable) {
422 return R.string.tether_settings_title_wifi;
423 } else if (usbAvailable && bluetoothAvailable) {
424 return R.string.tether_settings_title_usb_bluetooth;
425 } else if (usbAvailable) {
426 return R.string.tether_settings_title_usb;
427 } else {
428 return R.string.tether_settings_title_bluetooth;
429 }
430 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700431
432 /* Used by UserSettings as well. Call this on a non-ui thread. */
433 public static boolean copyMeProfilePhoto(Context context, UserInfo user) {
434 Uri contactUri = Profile.CONTENT_URI;
435
436 InputStream avatarDataStream = Contacts.openContactPhotoInputStream(
437 context.getContentResolver(),
438 contactUri, true);
439 // If there's no profile photo, assign a default avatar
440 if (avatarDataStream == null) {
441 return false;
442 }
443 int userId = user != null ? user.id : UserHandle.myUserId();
444 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700445 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream);
446 um.setUserIcon(userId, icon);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700447 try {
Amith Yamasanif34a85d2012-09-17 18:31:45 -0700448 avatarDataStream.close();
449 } catch (IOException ioe) { }
450 return true;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700451 }
452
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700453 public static String getMeProfileName(Context context, boolean full) {
454 if (full) {
455 return getProfileDisplayName(context);
456 } else {
457 return getShorterNameIfPossible(context);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700458 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700459 }
460
461 private static String getShorterNameIfPossible(Context context) {
462 final String given = getLocalProfileGivenName(context);
463 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context);
464 }
465
466 private static String getLocalProfileGivenName(Context context) {
467 final ContentResolver cr = context.getContentResolver();
468
469 // Find the raw contact ID for the local ME profile raw contact.
470 final long localRowProfileId;
471 final Cursor localRawProfile = cr.query(
472 Profile.CONTENT_RAW_CONTACTS_URI,
473 new String[] {RawContacts._ID},
474 RawContacts.ACCOUNT_TYPE + " IS NULL AND " +
475 RawContacts.ACCOUNT_NAME + " IS NULL",
476 null, null);
477 if (localRawProfile == null) return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700478
479 try {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700480 if (!localRawProfile.moveToFirst()) {
481 return null;
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700482 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700483 localRowProfileId = localRawProfile.getLong(0);
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700484 } finally {
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700485 localRawProfile.close();
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700486 }
Amith Yamasani8d40fac2012-10-23 15:36:16 -0700487
488 // Find the structured name for the raw contact.
489 final Cursor structuredName = cr.query(
490 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(),
491 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME,
492 CommonDataKinds.StructuredName.FAMILY_NAME},
493 Data.RAW_CONTACT_ID + "=" + localRowProfileId,
494 null, null);
495 if (structuredName == null) return null;
496
497 try {
498 if (!structuredName.moveToFirst()) {
499 return null;
500 }
501 String partialName = structuredName.getString(0);
502 if (TextUtils.isEmpty(partialName)) {
503 partialName = structuredName.getString(1);
504 }
505 return partialName;
506 } finally {
507 structuredName.close();
508 }
509 }
510
511 private static final String getProfileDisplayName(Context context) {
512 final ContentResolver cr = context.getContentResolver();
513 final Cursor profile = cr.query(Profile.CONTENT_URI,
514 new String[] {Profile.DISPLAY_NAME}, null, null, null);
515 if (profile == null) return null;
516
517 try {
518 if (!profile.moveToFirst()) {
519 return null;
520 }
521 return profile.getString(0);
522 } finally {
523 profile.close();
524 }
Amith Yamasaniae47ef42012-09-16 17:53:35 -0700525 }
Amith Yamasani9627a8e2012-09-23 12:54:14 -0700526
527 /** Not global warming, it's global change warning. */
528 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId,
529 final Runnable positiveAction) {
530 final AlertDialog.Builder builder = new AlertDialog.Builder(context);
531 builder.setTitle(titleResId);
532 builder.setMessage(R.string.global_change_warning);
533 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
534 @Override
535 public void onClick(DialogInterface dialog, int which) {
536 positiveAction.run();
537 }
538 });
539 builder.setNegativeButton(android.R.string.cancel, null);
540
541 return builder.create();
542 }
543
544 public static boolean hasMultipleUsers(Context context) {
545 return ((UserManager) context.getSystemService(Context.USER_SERVICE))
546 .getUsers().size() > 1;
547 }
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700548
549 /**
550 * Start a new instance of the activity, showing only the given fragment.
551 * When launched in this mode, the given preference fragment will be instantiated and fill the
552 * entire activity.
553 *
554 * @param context The context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000555 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700556 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700557 * @param resultTo Option fragment that should receive the result of the activity launch.
558 * @param resultRequestCode If resultTo is non-null, this is the request code in which
559 * to report the result.
560 * @param titleResId resource id for the String to display for the title of this set
561 * of preferences.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700562 * @param title String to display for the title of this set of preferences.
563 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000564 public static void startWithFragment(Context context, String fragmentName, Bundle args,
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700565 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title) {
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700566 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode,
567 titleResId, title, false /* not a shortcut */);
568 }
569
570 public static void startWithFragment(Context context, String fragmentName, Bundle args,
571 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title,
572 boolean isShortcut) {
573 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId,
574 title, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700575 if (resultTo == null) {
576 context.startActivity(intent);
577 } else {
578 resultTo.startActivityForResult(intent, resultRequestCode);
579 }
580 }
581
582 /**
583 * Build an Intent to launch a new activity showing the selected fragment.
584 * The implementation constructs an Intent that re-launches the current activity with the
585 * appropriate arguments to display the fragment.
586 *
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700587 *
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700588 * @param context The Context.
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000589 * @param fragmentName The name of the fragment to display.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700590 * @param args Optional arguments to supply to the fragment.
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700591 * @param titleResId Optional title resource id to show for this item.
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700592 * @param title Optional title to show for this item.
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700593 * @param isShortcut tell if this is a Launcher Shortcut or not
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700594 * @return Returns an Intent that can be launched to display the given
595 * fragment.
596 */
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000597 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName,
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700598 Bundle args, int titleResId, CharSequence title, boolean isShortcut) {
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700599 Intent intent = new Intent(Intent.ACTION_MAIN);
600 intent.setClass(context, SubSettings.class);
Fabrice Di Meglio93b77b72014-05-17 00:01:07 +0000601 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700602 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args);
Fabrice Di Meglioa9e77992014-06-09 12:52:24 -0700603 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700604 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title);
Fabrice Di Meglio0d643fd2014-06-16 20:11:27 -0700605 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut);
Fabrice Di Meglio769630c2014-04-24 14:48:48 -0700606 return intent;
607 }
Alexandra Gherghina3939cd72014-06-04 10:02:55 +0100608
609 /**
610 * Returns the managed profile of the current user or null if none found.
611 */
612 public static UserHandle getManagedProfile(UserManager userManager) {
613 List<UserHandle> userProfiles = userManager.getUserProfiles();
614 final int count = userProfiles.size();
615 for (int i = 0; i < count; i++) {
616 final UserHandle profile = userProfiles.get(i);
617 if (profile.getIdentifier() == userManager.getUserHandle()) {
618 continue;
619 }
620 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier());
621 if (userInfo.isManagedProfile()) {
622 return profile;
623 }
624 }
625 return null;
626 }
627
628 /**
629 * Returns true if the current profile is a managed one.
630 */
631 public static boolean isManagedProfile(UserManager userManager) {
632 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle());
633 return currentUser.isManagedProfile();
634 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100635
636 /**
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100637 * Returns the target user for a Settings activity.
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100638 *
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100639 * The target user can be either the current user, the user that launched this activity or
640 * the user contained as an extra in the arguments or intent extras.
641 *
642 * Note: This is secure in the sense that it only returns a target user different to the current
643 * one if the app launching this activity is the Settings app itself, running in the same user
644 * 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 +0100645 */
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100646 public static UserHandle getSecureTargetUser(IBinder activityToken,
647 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) {
648 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
649 IActivityManager am = ActivityManagerNative.getDefault();
650 try {
651 String launchedFromPackage = am.getLaunchedFromPackage(activityToken);
652 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage);
653
654 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
655 am.getLaunchedFromUid(activityToken)));
656 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
657 // Check it's secure
658 if (isProfileOf(um, launchedFromUser)) {
659 return launchedFromUser;
660 }
661 }
662 UserHandle extrasUser = intentExtras != null
663 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
664 if (extrasUser != null && !extrasUser.equals(currentUser)) {
665 // Check it's secure
666 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) {
667 return extrasUser;
668 }
669 }
670 UserHandle argumentsUser = arguments != null
671 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
672 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
673 // Check it's secure
674 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) {
675 return argumentsUser;
676 }
677 }
678 } catch (RemoteException e) {
679 // Should not happen
680 Log.v(TAG, "Could not talk to activity manager.", e);
681 }
682 return currentUser;
683 }
684
685 /**
686 * Returns the target user for a Settings activity.
687 *
688 * The target user can be either the current user, the user that launched this activity or
689 * the user contained as an extra in the arguments or intent extras.
690 *
691 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if
692 * possible.
693 *
694 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle)
695 */
696 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments,
697 @Nullable Bundle intentExtras) {
698 UserHandle currentUser = new UserHandle(UserHandle.myUserId());
699 IActivityManager am = ActivityManagerNative.getDefault();
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100700 try {
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100701 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId(
702 am.getLaunchedFromUid(activityToken)));
703 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) {
704 return launchedFromUser;
705 }
706 UserHandle extrasUser = intentExtras != null
707 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null;
708 if (extrasUser != null && !extrasUser.equals(currentUser)) {
709 return extrasUser;
710 }
711 UserHandle argumentsUser = arguments != null
712 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null;
713 if (argumentsUser != null && !argumentsUser.equals(currentUser)) {
714 return argumentsUser;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100715 }
716 } catch (RemoteException e) {
717 // Should not happen
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100718 Log.v(TAG, "Could not talk to activity manager.", e);
719 return null;
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100720 }
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100721 return currentUser;
722 }
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100723
Alexandra Gherghina7d748c02014-06-27 12:33:42 +0100724 /**
725 * Returns true if the user provided is in the same profiles group as the current user.
726 */
727 private static boolean isProfileOf(UserManager um, UserHandle otherUser) {
728 if (um == null || otherUser == null) return false;
729 return (UserHandle.myUserId() == otherUser.getIdentifier())
730 || um.getUserProfiles().contains(otherUser);
Alexandra Gherghina1eb3f312014-06-10 14:01:10 +0100731 }
Amith Yamasani51c6dac2014-07-02 00:06:37 +0530732
733 /**
734 * Creates a dialog to confirm with the user if it's ok to remove the user
735 * and delete all the data.
736 *
737 * @param context a Context object
738 * @param removingUserId The userId of the user to remove
739 * @param onConfirmListener Callback object for positive action
740 * @return the created Dialog
741 */
742 public static Dialog createRemoveConfirmationDialog(Context context, int removingUserId,
743 DialogInterface.OnClickListener onConfirmListener) {
744 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE);
745 UserInfo userInfo = um.getUserInfo(removingUserId);
746 Dialog dlg = new AlertDialog.Builder(context)
747 .setTitle(UserHandle.myUserId() == removingUserId
748 ? R.string.user_confirm_remove_self_title
749 : (userInfo.isRestricted()
750 ? R.string.user_profile_confirm_remove_title
751 : R.string.user_confirm_remove_title))
752 .setMessage(UserHandle.myUserId() == removingUserId
753 ? R.string.user_confirm_remove_self_message
754 : (userInfo.isRestricted()
755 ? R.string.user_profile_confirm_remove_message
756 : R.string.user_confirm_remove_message))
757 .setPositiveButton(R.string.user_delete_button,
758 onConfirmListener)
759 .setNegativeButton(android.R.string.cancel, null)
760 .create();
761 return dlg;
762 }
Andres Moralesce249fe2014-07-07 16:58:16 -0700763
764 /**
765 * Returns whether or not this device is able to be OEM unlocked.
766 */
767 static boolean isOemUnlockEnabled(Context context) {
768 PersistentDataBlockManager manager =(PersistentDataBlockManager)
769 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
770 return manager.getOemUnlockEnabled();
771 }
772
773 /**
774 * Allows enabling or disabling OEM unlock on this device. OEM unlocked
775 * devices allow users to flash other OSes to them.
776 */
777 static void setOemUnlockEnabled(Context context, boolean enabled) {
778 PersistentDataBlockManager manager =(PersistentDataBlockManager)
779 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE);
780 manager.setOemUnlockEnabled(enabled);
781 }
The Android Open Source Projectafc4ab22009-03-03 19:32:34 -0800782}