Utils.java revision 5c0d0729b1701428d46ee7abb31f2a83d8da38ab
1/** 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 19import static android.content.Intent.EXTRA_USER; 20 21import android.annotation.Nullable; 22import android.app.ActivityManager; 23import android.app.ActivityManagerNative; 24import android.app.AlertDialog; 25import android.app.Dialog; 26import android.app.Fragment; 27import android.app.IActivityManager; 28import android.content.ContentResolver; 29import android.content.Context; 30import android.content.DialogInterface; 31import android.content.Intent; 32import android.content.pm.ApplicationInfo; 33import android.content.pm.PackageInfo; 34import android.content.pm.PackageManager; 35import android.content.pm.PackageManager.NameNotFoundException; 36import android.content.pm.ResolveInfo; 37import android.content.pm.Signature; 38import android.content.pm.UserInfo; 39import android.content.res.Resources; 40import android.content.res.Resources.NotFoundException; 41import android.database.Cursor; 42import android.graphics.Bitmap; 43import android.graphics.BitmapFactory; 44import android.graphics.drawable.Drawable; 45import android.net.ConnectivityManager; 46import android.net.LinkProperties; 47import android.net.Uri; 48import android.os.BatteryManager; 49import android.os.Bundle; 50import android.os.IBinder; 51import android.os.RemoteException; 52import android.os.UserHandle; 53import android.os.UserManager; 54import android.preference.Preference; 55import android.preference.PreferenceFrameLayout; 56import android.preference.PreferenceGroup; 57import android.provider.ContactsContract.CommonDataKinds; 58import android.provider.ContactsContract.Contacts; 59import android.provider.ContactsContract.Data; 60import android.provider.ContactsContract.Profile; 61import android.provider.ContactsContract.RawContacts; 62import android.service.persistentdata.PersistentDataBlockManager; 63import android.telephony.TelephonyManager; 64import android.text.BidiFormatter; 65import android.text.TextDirectionHeuristics; 66import android.text.TextUtils; 67import android.util.Log; 68import android.view.View; 69import android.view.ViewGroup; 70import android.widget.ListView; 71import android.widget.TabWidget; 72 73import com.android.settings.UserSpinnerAdapter.UserDetails; 74import com.android.settings.dashboard.DashboardCategory; 75import com.android.settings.dashboard.DashboardTile; 76import com.android.settings.drawable.CircleFramedDrawable; 77 78import java.io.IOException; 79import java.io.InputStream; 80import java.net.InetAddress; 81import java.text.NumberFormat; 82import java.util.ArrayList; 83import java.util.Iterator; 84import java.util.List; 85import java.util.Locale; 86 87public final class Utils { 88 private static final String TAG = "Settings"; 89 90 /** 91 * Set the preference's title to the matching activity's label. 92 */ 93 public static final int UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY = 1; 94 95 /** 96 * The opacity level of a disabled icon. 97 */ 98 public static final float DISABLED_ALPHA = 0.4f; 99 100 /** 101 * Color spectrum to use to indicate badness. 0 is completely transparent (no data), 102 * 1 is most bad (red), the last value is least bad (green). 103 */ 104 public static final int[] BADNESS_COLORS = new int[] { 105 0x00000000, 0xffc43828, 0xffe54918, 0xfff47b00, 106 0xfffabf2c, 0xff679e37, 0xff0a7f42 107 }; 108 109 /** 110 * Name of the meta-data item that should be set in the AndroidManifest.xml 111 * to specify the icon that should be displayed for the preference. 112 */ 113 private static final String META_DATA_PREFERENCE_ICON = "com.android.settings.icon"; 114 115 /** 116 * Name of the meta-data item that should be set in the AndroidManifest.xml 117 * to specify the title that should be displayed for the preference. 118 */ 119 private static final String META_DATA_PREFERENCE_TITLE = "com.android.settings.title"; 120 121 /** 122 * Name of the meta-data item that should be set in the AndroidManifest.xml 123 * to specify the summary text that should be displayed for the preference. 124 */ 125 private static final String META_DATA_PREFERENCE_SUMMARY = "com.android.settings.summary"; 126 127 private static final String SETTINGS_PACKAGE_NAME = "com.android.settings"; 128 129 private static final int SECONDS_PER_MINUTE = 60; 130 private static final int SECONDS_PER_HOUR = 60 * 60; 131 private static final int SECONDS_PER_DAY = 24 * 60 * 60; 132 133 /** 134 * Finds a matching activity for a preference's intent. If a matching 135 * activity is not found, it will remove the preference. 136 * 137 * @param context The context. 138 * @param parentPreferenceGroup The preference group that contains the 139 * preference whose intent is being resolved. 140 * @param preferenceKey The key of the preference whose intent is being 141 * resolved. 142 * @param flags 0 or one or more of 143 * {@link #UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY} 144 * . 145 * @return Whether an activity was found. If false, the preference was 146 * removed. 147 */ 148 public static boolean updatePreferenceToSpecificActivityOrRemove(Context context, 149 PreferenceGroup parentPreferenceGroup, String preferenceKey, int flags) { 150 151 Preference preference = parentPreferenceGroup.findPreference(preferenceKey); 152 if (preference == null) { 153 return false; 154 } 155 156 Intent intent = preference.getIntent(); 157 if (intent != null) { 158 // Find the activity that is in the system image 159 PackageManager pm = context.getPackageManager(); 160 List<ResolveInfo> list = pm.queryIntentActivities(intent, 0); 161 int listSize = list.size(); 162 for (int i = 0; i < listSize; i++) { 163 ResolveInfo resolveInfo = list.get(i); 164 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) 165 != 0) { 166 167 // Replace the intent with this specific activity 168 preference.setIntent(new Intent().setClassName( 169 resolveInfo.activityInfo.packageName, 170 resolveInfo.activityInfo.name)); 171 172 if ((flags & UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY) != 0) { 173 // Set the preference title to the activity's label 174 preference.setTitle(resolveInfo.loadLabel(pm)); 175 } 176 177 return true; 178 } 179 } 180 } 181 182 // Did not find a matching activity, so remove the preference 183 parentPreferenceGroup.removePreference(preference); 184 185 return false; 186 } 187 188 public static boolean updateTileToSpecificActivityFromMetaDataOrRemove(Context context, 189 DashboardTile tile) { 190 191 Intent intent = tile.intent; 192 if (intent != null) { 193 // Find the activity that is in the system image 194 PackageManager pm = context.getPackageManager(); 195 List<ResolveInfo> list = pm.queryIntentActivities(intent, PackageManager.GET_META_DATA); 196 int listSize = list.size(); 197 for (int i = 0; i < listSize; i++) { 198 ResolveInfo resolveInfo = list.get(i); 199 if ((resolveInfo.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) 200 != 0) { 201 Drawable icon = null; 202 String title = null; 203 String summary = null; 204 205 // Get the activity's meta-data 206 try { 207 Resources res = pm.getResourcesForApplication( 208 resolveInfo.activityInfo.packageName); 209 Bundle metaData = resolveInfo.activityInfo.metaData; 210 211 if (res != null && metaData != null) { 212 icon = res.getDrawable(metaData.getInt(META_DATA_PREFERENCE_ICON)); 213 title = res.getString(metaData.getInt(META_DATA_PREFERENCE_TITLE)); 214 summary = res.getString(metaData.getInt(META_DATA_PREFERENCE_SUMMARY)); 215 } 216 } catch (NameNotFoundException e) { 217 // Ignore 218 } catch (NotFoundException e) { 219 // Ignore 220 } 221 222 // Set the preference title to the activity's label if no 223 // meta-data is found 224 if (TextUtils.isEmpty(title)) { 225 title = resolveInfo.loadLabel(pm).toString(); 226 } 227 228 // Set icon, title and summary for the preference 229 // TODO: 230 //tile.icon = icon; 231 tile.title = title; 232 tile.summary = summary; 233 // Replace the intent with this specific activity 234 tile.intent = new Intent().setClassName(resolveInfo.activityInfo.packageName, 235 resolveInfo.activityInfo.name); 236 237 return true; 238 } 239 } 240 } 241 242 return false; 243 } 244 245 /** 246 * Returns true if Monkey is running. 247 */ 248 public static boolean isMonkeyRunning() { 249 return ActivityManager.isUserAMonkey(); 250 } 251 252 /** 253 * Returns whether the device is voice-capable (meaning, it is also a phone). 254 */ 255 public static boolean isVoiceCapable(Context context) { 256 TelephonyManager telephony = 257 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 258 return telephony != null && telephony.isVoiceCapable(); 259 } 260 261 public static boolean isWifiOnly(Context context) { 262 ConnectivityManager cm = (ConnectivityManager)context.getSystemService( 263 Context.CONNECTIVITY_SERVICE); 264 return (cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE) == false); 265 } 266 267 /** 268 * Returns the WIFI IP Addresses, if any, taking into account IPv4 and IPv6 style addresses. 269 * @param context the application context 270 * @return the formatted and newline-separated IP addresses, or null if none. 271 */ 272 public static String getWifiIpAddresses(Context context) { 273 ConnectivityManager cm = (ConnectivityManager) 274 context.getSystemService(Context.CONNECTIVITY_SERVICE); 275 LinkProperties prop = cm.getLinkProperties(ConnectivityManager.TYPE_WIFI); 276 return formatIpAddresses(prop); 277 } 278 279 /** 280 * Returns the default link's IP addresses, if any, taking into account IPv4 and IPv6 style 281 * addresses. 282 * @param context the application context 283 * @return the formatted and newline-separated IP addresses, or null if none. 284 */ 285 public static String getDefaultIpAddresses(ConnectivityManager cm) { 286 LinkProperties prop = cm.getActiveLinkProperties(); 287 return formatIpAddresses(prop); 288 } 289 290 private static String formatIpAddresses(LinkProperties prop) { 291 if (prop == null) return null; 292 Iterator<InetAddress> iter = prop.getAllAddresses().iterator(); 293 // If there are no entries, return null 294 if (!iter.hasNext()) return null; 295 // Concatenate all available addresses, comma separated 296 String addresses = ""; 297 while (iter.hasNext()) { 298 addresses += iter.next().getHostAddress(); 299 if (iter.hasNext()) addresses += "\n"; 300 } 301 return addresses; 302 } 303 304 public static Locale createLocaleFromString(String localeStr) { 305 // TODO: is there a better way to actually construct a locale that will match? 306 // The main problem is, on top of Java specs, locale.toString() and 307 // new Locale(locale.toString()).toString() do not return equal() strings in 308 // many cases, because the constructor takes the only string as the language 309 // code. So : new Locale("en", "US").toString() => "en_US" 310 // And : new Locale("en_US").toString() => "en_us" 311 if (null == localeStr) 312 return Locale.getDefault(); 313 String[] brokenDownLocale = localeStr.split("_", 3); 314 // split may not return a 0-length array. 315 if (1 == brokenDownLocale.length) { 316 return new Locale(brokenDownLocale[0]); 317 } else if (2 == brokenDownLocale.length) { 318 return new Locale(brokenDownLocale[0], brokenDownLocale[1]); 319 } else { 320 return new Locale(brokenDownLocale[0], brokenDownLocale[1], brokenDownLocale[2]); 321 } 322 } 323 324 /** Formats the ratio of amount/total as a percentage. */ 325 public static String formatPercentage(long amount, long total) { 326 return formatPercentage(((double) amount) / total); 327 } 328 329 /** Formats an integer from 0..100 as a percentage. */ 330 public static String formatPercentage(int percentage) { 331 return formatPercentage(((double) percentage) / 100.0); 332 } 333 334 /** Formats a double from 0.0..1.0 as a percentage. */ 335 private static String formatPercentage(double percentage) { 336 BidiFormatter bf = BidiFormatter.getInstance(); 337 return bf.unicodeWrap(NumberFormat.getPercentInstance().format(percentage)); 338 } 339 340 public static boolean isBatteryPresent(Intent batteryChangedIntent) { 341 return batteryChangedIntent.getBooleanExtra(BatteryManager.EXTRA_PRESENT, true); 342 } 343 344 public static String getBatteryPercentage(Intent batteryChangedIntent) { 345 return formatPercentage(getBatteryLevel(batteryChangedIntent)); 346 } 347 348 public static int getBatteryLevel(Intent batteryChangedIntent) { 349 int level = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0); 350 int scale = batteryChangedIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100); 351 return (level * 100) / scale; 352 } 353 354 public static String getBatteryStatus(Resources res, Intent batteryChangedIntent) { 355 final Intent intent = batteryChangedIntent; 356 357 int plugType = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0); 358 int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 359 BatteryManager.BATTERY_STATUS_UNKNOWN); 360 String statusString; 361 if (status == BatteryManager.BATTERY_STATUS_CHARGING) { 362 int resId; 363 if (plugType == BatteryManager.BATTERY_PLUGGED_AC) { 364 resId = R.string.battery_info_status_charging_ac; 365 } else if (plugType == BatteryManager.BATTERY_PLUGGED_USB) { 366 resId = R.string.battery_info_status_charging_usb; 367 } else if (plugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) { 368 resId = R.string.battery_info_status_charging_wireless; 369 } else { 370 resId = R.string.battery_info_status_charging; 371 } 372 statusString = res.getString(resId); 373 } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) { 374 statusString = res.getString(R.string.battery_info_status_discharging); 375 } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) { 376 statusString = res.getString(R.string.battery_info_status_not_charging); 377 } else if (status == BatteryManager.BATTERY_STATUS_FULL) { 378 statusString = res.getString(R.string.battery_info_status_full); 379 } else { 380 statusString = res.getString(R.string.battery_info_status_unknown); 381 } 382 383 return statusString; 384 } 385 386 public static void forcePrepareCustomPreferencesList( 387 ViewGroup parent, View child, ListView list, boolean ignoreSidePadding) { 388 list.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY); 389 list.setClipToPadding(false); 390 prepareCustomPreferencesList(parent, child, list, ignoreSidePadding); 391 } 392 393 /** 394 * Prepare a custom preferences layout, moving padding to {@link ListView} 395 * when outside scrollbars are requested. Usually used to display 396 * {@link ListView} and {@link TabWidget} with correct padding. 397 */ 398 public static void prepareCustomPreferencesList( 399 ViewGroup parent, View child, View list, boolean ignoreSidePadding) { 400 final boolean movePadding = list.getScrollBarStyle() == View.SCROLLBARS_OUTSIDE_OVERLAY; 401 if (movePadding) { 402 final Resources res = list.getResources(); 403 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin); 404 final int paddingBottom = res.getDimensionPixelSize( 405 com.android.internal.R.dimen.preference_fragment_padding_bottom); 406 407 if (parent instanceof PreferenceFrameLayout) { 408 ((PreferenceFrameLayout.LayoutParams) child.getLayoutParams()).removeBorders = true; 409 410 final int effectivePaddingSide = ignoreSidePadding ? 0 : paddingSide; 411 list.setPaddingRelative(effectivePaddingSide, 0, effectivePaddingSide, paddingBottom); 412 } else { 413 list.setPaddingRelative(paddingSide, 0, paddingSide, paddingBottom); 414 } 415 } 416 } 417 418 public static void forceCustomPadding(View view, boolean additive) { 419 final Resources res = view.getResources(); 420 final int paddingSide = res.getDimensionPixelSize(R.dimen.settings_side_margin); 421 422 final int paddingStart = paddingSide + (additive ? view.getPaddingStart() : 0); 423 final int paddingEnd = paddingSide + (additive ? view.getPaddingEnd() : 0); 424 final int paddingBottom = res.getDimensionPixelSize( 425 com.android.internal.R.dimen.preference_fragment_padding_bottom); 426 427 view.setPaddingRelative(paddingStart, 0, paddingEnd, paddingBottom); 428 } 429 430 /** 431 * Return string resource that best describes combination of tethering 432 * options available on this device. 433 */ 434 public static int getTetheringLabel(ConnectivityManager cm) { 435 String[] usbRegexs = cm.getTetherableUsbRegexs(); 436 String[] wifiRegexs = cm.getTetherableWifiRegexs(); 437 String[] bluetoothRegexs = cm.getTetherableBluetoothRegexs(); 438 439 boolean usbAvailable = usbRegexs.length != 0; 440 boolean wifiAvailable = wifiRegexs.length != 0; 441 boolean bluetoothAvailable = bluetoothRegexs.length != 0; 442 443 if (wifiAvailable && usbAvailable && bluetoothAvailable) { 444 return R.string.tether_settings_title_all; 445 } else if (wifiAvailable && usbAvailable) { 446 return R.string.tether_settings_title_all; 447 } else if (wifiAvailable && bluetoothAvailable) { 448 return R.string.tether_settings_title_all; 449 } else if (wifiAvailable) { 450 return R.string.tether_settings_title_wifi; 451 } else if (usbAvailable && bluetoothAvailable) { 452 return R.string.tether_settings_title_usb_bluetooth; 453 } else if (usbAvailable) { 454 return R.string.tether_settings_title_usb; 455 } else { 456 return R.string.tether_settings_title_bluetooth; 457 } 458 } 459 460 /* Used by UserSettings as well. Call this on a non-ui thread. */ 461 public static boolean copyMeProfilePhoto(Context context, UserInfo user) { 462 Uri contactUri = Profile.CONTENT_URI; 463 464 InputStream avatarDataStream = Contacts.openContactPhotoInputStream( 465 context.getContentResolver(), 466 contactUri, true); 467 // If there's no profile photo, assign a default avatar 468 if (avatarDataStream == null) { 469 return false; 470 } 471 int userId = user != null ? user.id : UserHandle.myUserId(); 472 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE); 473 Bitmap icon = BitmapFactory.decodeStream(avatarDataStream); 474 um.setUserIcon(userId, icon); 475 try { 476 avatarDataStream.close(); 477 } catch (IOException ioe) { } 478 return true; 479 } 480 481 public static String getMeProfileName(Context context, boolean full) { 482 if (full) { 483 return getProfileDisplayName(context); 484 } else { 485 return getShorterNameIfPossible(context); 486 } 487 } 488 489 private static String getShorterNameIfPossible(Context context) { 490 final String given = getLocalProfileGivenName(context); 491 return !TextUtils.isEmpty(given) ? given : getProfileDisplayName(context); 492 } 493 494 private static String getLocalProfileGivenName(Context context) { 495 final ContentResolver cr = context.getContentResolver(); 496 497 // Find the raw contact ID for the local ME profile raw contact. 498 final long localRowProfileId; 499 final Cursor localRawProfile = cr.query( 500 Profile.CONTENT_RAW_CONTACTS_URI, 501 new String[] {RawContacts._ID}, 502 RawContacts.ACCOUNT_TYPE + " IS NULL AND " + 503 RawContacts.ACCOUNT_NAME + " IS NULL", 504 null, null); 505 if (localRawProfile == null) return null; 506 507 try { 508 if (!localRawProfile.moveToFirst()) { 509 return null; 510 } 511 localRowProfileId = localRawProfile.getLong(0); 512 } finally { 513 localRawProfile.close(); 514 } 515 516 // Find the structured name for the raw contact. 517 final Cursor structuredName = cr.query( 518 Profile.CONTENT_URI.buildUpon().appendPath(Contacts.Data.CONTENT_DIRECTORY).build(), 519 new String[] {CommonDataKinds.StructuredName.GIVEN_NAME, 520 CommonDataKinds.StructuredName.FAMILY_NAME}, 521 Data.RAW_CONTACT_ID + "=" + localRowProfileId, 522 null, null); 523 if (structuredName == null) return null; 524 525 try { 526 if (!structuredName.moveToFirst()) { 527 return null; 528 } 529 String partialName = structuredName.getString(0); 530 if (TextUtils.isEmpty(partialName)) { 531 partialName = structuredName.getString(1); 532 } 533 return partialName; 534 } finally { 535 structuredName.close(); 536 } 537 } 538 539 private static final String getProfileDisplayName(Context context) { 540 final ContentResolver cr = context.getContentResolver(); 541 final Cursor profile = cr.query(Profile.CONTENT_URI, 542 new String[] {Profile.DISPLAY_NAME}, null, null, null); 543 if (profile == null) return null; 544 545 try { 546 if (!profile.moveToFirst()) { 547 return null; 548 } 549 return profile.getString(0); 550 } finally { 551 profile.close(); 552 } 553 } 554 555 /** Not global warming, it's global change warning. */ 556 public static Dialog buildGlobalChangeWarningDialog(final Context context, int titleResId, 557 final Runnable positiveAction) { 558 final AlertDialog.Builder builder = new AlertDialog.Builder(context); 559 builder.setTitle(titleResId); 560 builder.setMessage(R.string.global_change_warning); 561 builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { 562 @Override 563 public void onClick(DialogInterface dialog, int which) { 564 positiveAction.run(); 565 } 566 }); 567 builder.setNegativeButton(android.R.string.cancel, null); 568 569 return builder.create(); 570 } 571 572 public static boolean hasMultipleUsers(Context context) { 573 return ((UserManager) context.getSystemService(Context.USER_SERVICE)) 574 .getUsers().size() > 1; 575 } 576 577 /** 578 * Start a new instance of the activity, showing only the given fragment. 579 * When launched in this mode, the given preference fragment will be instantiated and fill the 580 * entire activity. 581 * 582 * @param context The context. 583 * @param fragmentName The name of the fragment to display. 584 * @param args Optional arguments to supply to the fragment. 585 * @param resultTo Option fragment that should receive the result of the activity launch. 586 * @param resultRequestCode If resultTo is non-null, this is the request code in which 587 * to report the result. 588 * @param titleResId resource id for the String to display for the title of this set 589 * of preferences. 590 * @param title String to display for the title of this set of preferences. 591 */ 592 public static void startWithFragment(Context context, String fragmentName, Bundle args, 593 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title) { 594 startWithFragment(context, fragmentName, args, resultTo, resultRequestCode, 595 titleResId, title, false /* not a shortcut */); 596 } 597 598 public static void startWithFragment(Context context, String fragmentName, Bundle args, 599 Fragment resultTo, int resultRequestCode, int titleResId, CharSequence title, 600 boolean isShortcut) { 601 Intent intent = onBuildStartFragmentIntent(context, fragmentName, args, titleResId, 602 title, isShortcut); 603 if (resultTo == null) { 604 context.startActivity(intent); 605 } else { 606 resultTo.startActivityForResult(intent, resultRequestCode); 607 } 608 } 609 610 /** 611 * Build an Intent to launch a new activity showing the selected fragment. 612 * The implementation constructs an Intent that re-launches the current activity with the 613 * appropriate arguments to display the fragment. 614 * 615 * 616 * @param context The Context. 617 * @param fragmentName The name of the fragment to display. 618 * @param args Optional arguments to supply to the fragment. 619 * @param titleResId Optional title resource id to show for this item. 620 * @param title Optional title to show for this item. 621 * @param isShortcut tell if this is a Launcher Shortcut or not 622 * @return Returns an Intent that can be launched to display the given 623 * fragment. 624 */ 625 public static Intent onBuildStartFragmentIntent(Context context, String fragmentName, 626 Bundle args, int titleResId, CharSequence title, boolean isShortcut) { 627 Intent intent = new Intent(Intent.ACTION_MAIN); 628 intent.setClass(context, SubSettings.class); 629 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT, fragmentName); 630 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_ARGUMENTS, args); 631 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE_RESID, titleResId); 632 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_TITLE, title); 633 intent.putExtra(SettingsActivity.EXTRA_SHOW_FRAGMENT_AS_SHORTCUT, isShortcut); 634 return intent; 635 } 636 637 /** 638 * Returns the managed profile of the current user or null if none found. 639 */ 640 public static UserHandle getManagedProfile(UserManager userManager) { 641 List<UserHandle> userProfiles = userManager.getUserProfiles(); 642 final int count = userProfiles.size(); 643 for (int i = 0; i < count; i++) { 644 final UserHandle profile = userProfiles.get(i); 645 if (profile.getIdentifier() == userManager.getUserHandle()) { 646 continue; 647 } 648 final UserInfo userInfo = userManager.getUserInfo(profile.getIdentifier()); 649 if (userInfo.isManagedProfile()) { 650 return profile; 651 } 652 } 653 return null; 654 } 655 656 /** 657 * Returns true if the current profile is a managed one. 658 */ 659 public static boolean isManagedProfile(UserManager userManager) { 660 UserInfo currentUser = userManager.getUserInfo(userManager.getUserHandle()); 661 return currentUser.isManagedProfile(); 662 } 663 664 /** 665 * Creates a {@link UserSpinnerAdapter} if there is more than one profile on the device. 666 * 667 * <p> The adapter can be used to populate a spinner that switches between the Settings 668 * app on the different profiles. 669 * 670 * @return a {@link UserSpinnerAdapter} or null if there is only one profile. 671 */ 672 public static UserSpinnerAdapter createUserSpinnerAdapter(UserManager userManager, 673 Context context) { 674 List<UserHandle> userProfiles = userManager.getUserProfiles(); 675 if (userProfiles.size() < 2) { 676 return null; 677 } 678 679 UserHandle myUserHandle = new UserHandle(UserHandle.myUserId()); 680 // The first option should be the current profile 681 userProfiles.remove(myUserHandle); 682 userProfiles.add(0, myUserHandle); 683 684 ArrayList<UserDetails> userDetails = new ArrayList<UserDetails>(userProfiles.size()); 685 final int count = userProfiles.size(); 686 for (int i = 0; i < count; i++) { 687 userDetails.add(new UserDetails(userProfiles.get(i), userManager, context)); 688 } 689 return new UserSpinnerAdapter(context, userDetails); 690 } 691 692 /** 693 * Returns the target user for a Settings activity. 694 * 695 * The target user can be either the current user, the user that launched this activity or 696 * the user contained as an extra in the arguments or intent extras. 697 * 698 * Note: This is secure in the sense that it only returns a target user different to the current 699 * one if the app launching this activity is the Settings app itself, running in the same user 700 * or in one that is in the same profile group, or if the user id is provided by the system. 701 */ 702 public static UserHandle getSecureTargetUser(IBinder activityToken, 703 UserManager um, @Nullable Bundle arguments, @Nullable Bundle intentExtras) { 704 UserHandle currentUser = new UserHandle(UserHandle.myUserId()); 705 IActivityManager am = ActivityManagerNative.getDefault(); 706 try { 707 String launchedFromPackage = am.getLaunchedFromPackage(activityToken); 708 boolean launchedFromSettingsApp = SETTINGS_PACKAGE_NAME.equals(launchedFromPackage); 709 710 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId( 711 am.getLaunchedFromUid(activityToken))); 712 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) { 713 // Check it's secure 714 if (isProfileOf(um, launchedFromUser)) { 715 return launchedFromUser; 716 } 717 } 718 UserHandle extrasUser = intentExtras != null 719 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null; 720 if (extrasUser != null && !extrasUser.equals(currentUser)) { 721 // Check it's secure 722 if (launchedFromSettingsApp && isProfileOf(um, extrasUser)) { 723 return extrasUser; 724 } 725 } 726 UserHandle argumentsUser = arguments != null 727 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null; 728 if (argumentsUser != null && !argumentsUser.equals(currentUser)) { 729 // Check it's secure 730 if (launchedFromSettingsApp && isProfileOf(um, argumentsUser)) { 731 return argumentsUser; 732 } 733 } 734 } catch (RemoteException e) { 735 // Should not happen 736 Log.v(TAG, "Could not talk to activity manager.", e); 737 } 738 return currentUser; 739 } 740 741 /** 742 * Returns the target user for a Settings activity. 743 * 744 * The target user can be either the current user, the user that launched this activity or 745 * the user contained as an extra in the arguments or intent extras. 746 * 747 * You should use {@link #getSecureTargetUser(IBinder, UserManager, Bundle, Bundle)} if 748 * possible. 749 * 750 * @see #getInsecureTargetUser(IBinder, Bundle, Bundle) 751 */ 752 public static UserHandle getInsecureTargetUser(IBinder activityToken, @Nullable Bundle arguments, 753 @Nullable Bundle intentExtras) { 754 UserHandle currentUser = new UserHandle(UserHandle.myUserId()); 755 IActivityManager am = ActivityManagerNative.getDefault(); 756 try { 757 UserHandle launchedFromUser = new UserHandle(UserHandle.getUserId( 758 am.getLaunchedFromUid(activityToken))); 759 if (launchedFromUser != null && !launchedFromUser.equals(currentUser)) { 760 return launchedFromUser; 761 } 762 UserHandle extrasUser = intentExtras != null 763 ? (UserHandle) intentExtras.getParcelable(EXTRA_USER) : null; 764 if (extrasUser != null && !extrasUser.equals(currentUser)) { 765 return extrasUser; 766 } 767 UserHandle argumentsUser = arguments != null 768 ? (UserHandle) arguments.getParcelable(EXTRA_USER) : null; 769 if (argumentsUser != null && !argumentsUser.equals(currentUser)) { 770 return argumentsUser; 771 } 772 } catch (RemoteException e) { 773 // Should not happen 774 Log.v(TAG, "Could not talk to activity manager.", e); 775 return null; 776 } 777 return currentUser; 778 } 779 780 /** 781 * Returns true if the user provided is in the same profiles group as the current user. 782 */ 783 private static boolean isProfileOf(UserManager um, UserHandle otherUser) { 784 if (um == null || otherUser == null) return false; 785 return (UserHandle.myUserId() == otherUser.getIdentifier()) 786 || um.getUserProfiles().contains(otherUser); 787 } 788 789 /** 790 * Creates a dialog to confirm with the user if it's ok to remove the user 791 * and delete all the data. 792 * 793 * @param context a Context object 794 * @param removingUserId The userId of the user to remove 795 * @param onConfirmListener Callback object for positive action 796 * @return the created Dialog 797 */ 798 public static Dialog createRemoveConfirmationDialog(Context context, int removingUserId, 799 DialogInterface.OnClickListener onConfirmListener) { 800 UserManager um = (UserManager) context.getSystemService(Context.USER_SERVICE); 801 UserInfo userInfo = um.getUserInfo(removingUserId); 802 int titleResId; 803 int messageResId; 804 if (UserHandle.myUserId() == removingUserId) { 805 titleResId = R.string.user_confirm_remove_self_title; 806 messageResId = R.string.user_confirm_remove_self_message; 807 } else if (userInfo.isRestricted()) { 808 titleResId = R.string.user_profile_confirm_remove_title; 809 messageResId = R.string.user_profile_confirm_remove_message; 810 } else if (userInfo.isManagedProfile()) { 811 titleResId = R.string.work_profile_confirm_remove_title; 812 messageResId = R.string.work_profile_confirm_remove_message; 813 } else { 814 titleResId = R.string.user_confirm_remove_title; 815 messageResId = R.string.user_confirm_remove_message; 816 } 817 Dialog dlg = new AlertDialog.Builder(context) 818 .setTitle(titleResId) 819 .setMessage(messageResId) 820 .setPositiveButton(R.string.user_delete_button, 821 onConfirmListener) 822 .setNegativeButton(android.R.string.cancel, null) 823 .create(); 824 return dlg; 825 } 826 827 /** 828 * Returns whether or not this device is able to be OEM unlocked. 829 */ 830 static boolean isOemUnlockEnabled(Context context) { 831 PersistentDataBlockManager manager =(PersistentDataBlockManager) 832 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE); 833 return manager.getOemUnlockEnabled(); 834 } 835 836 /** 837 * Allows enabling or disabling OEM unlock on this device. OEM unlocked 838 * devices allow users to flash other OSes to them. 839 */ 840 static void setOemUnlockEnabled(Context context, boolean enabled) { 841 PersistentDataBlockManager manager =(PersistentDataBlockManager) 842 context.getSystemService(Context.PERSISTENT_DATA_BLOCK_SERVICE); 843 manager.setOemUnlockEnabled(enabled); 844 } 845 846 /** 847 * Returns a circular icon for a user. 848 */ 849 public static Drawable getUserIcon(Context context, UserManager um, UserInfo user) { 850 if (user.iconPath == null) return null; 851 Bitmap icon = um.getUserIcon(user.id); 852 if (icon == null) return null; 853 return CircleFramedDrawable.getInstance(context, icon); 854 } 855 856 /** 857 * Return whether or not the user should have a SIM Cards option in Settings. 858 * TODO: Change back to returning true if count is greater than one after testing. 859 * TODO: See bug 16533525. 860 */ 861 public static boolean showSimCardTile(Context context) { 862 final TelephonyManager tm = 863 (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 864 865 // TODO: Uncomment to re-enable SimSettings. 866 // return tm.getSimCount() > 0; 867 return false; 868 } 869 870 /** 871 * Determine whether a package is a "system package", in which case certain things (like 872 * disabling notifications or disabling the package altogether) should be disallowed. 873 */ 874 public static boolean isSystemPackage(PackageManager pm, PackageInfo pkg) { 875 if (sSystemSignature == null) { 876 sSystemSignature = new Signature[]{ getSystemSignature(pm) }; 877 } 878 return sSystemSignature[0] != null && sSystemSignature[0].equals(getFirstSignature(pkg)); 879 } 880 881 private static Signature[] sSystemSignature; 882 883 private static Signature getFirstSignature(PackageInfo pkg) { 884 if (pkg != null && pkg.signatures != null && pkg.signatures.length > 0) { 885 return pkg.signatures[0]; 886 } 887 return null; 888 } 889 890 private static Signature getSystemSignature(PackageManager pm) { 891 try { 892 final PackageInfo sys = pm.getPackageInfo("android", PackageManager.GET_SIGNATURES); 893 return getFirstSignature(sys); 894 } catch (NameNotFoundException e) { 895 } 896 return null; 897 } 898 899 /** 900 * Returns elapsed time for the given millis, in the following format: 901 * 2d 5h 40m 29s 902 * @param context the application context 903 * @param millis the elapsed time in milli seconds 904 * @param withSeconds include seconds? 905 * @return the formatted elapsed time 906 */ 907 public static String formatElapsedTime(Context context, double millis, boolean withSeconds) { 908 StringBuilder sb = new StringBuilder(); 909 int seconds = (int) Math.floor(millis / 1000); 910 if (!withSeconds) { 911 // Round up. 912 seconds += 30; 913 } 914 915 int days = 0, hours = 0, minutes = 0; 916 if (seconds >= SECONDS_PER_DAY) { 917 days = seconds / SECONDS_PER_DAY; 918 seconds -= days * SECONDS_PER_DAY; 919 } 920 if (seconds >= SECONDS_PER_HOUR) { 921 hours = seconds / SECONDS_PER_HOUR; 922 seconds -= hours * SECONDS_PER_HOUR; 923 } 924 if (seconds >= SECONDS_PER_MINUTE) { 925 minutes = seconds / SECONDS_PER_MINUTE; 926 seconds -= minutes * SECONDS_PER_MINUTE; 927 } 928 if (withSeconds) { 929 if (days > 0) { 930 sb.append(context.getString(R.string.battery_history_days, 931 days, hours, minutes, seconds)); 932 } else if (hours > 0) { 933 sb.append(context.getString(R.string.battery_history_hours, 934 hours, minutes, seconds)); 935 } else if (minutes > 0) { 936 sb.append(context.getString(R.string.battery_history_minutes, minutes, seconds)); 937 } else { 938 sb.append(context.getString(R.string.battery_history_seconds, seconds)); 939 } 940 } else { 941 if (days > 0) { 942 sb.append(context.getString(R.string.battery_history_days_no_seconds, 943 days, hours, minutes)); 944 } else if (hours > 0) { 945 sb.append(context.getString(R.string.battery_history_hours_no_seconds, 946 hours, minutes)); 947 } else { 948 sb.append(context.getString(R.string.battery_history_minutes_no_seconds, minutes)); 949 } 950 } 951 return sb.toString(); 952 } 953} 954