Resources.java revision 7b9c912f536925ac6ec43935d6e97506851b33d6
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy 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, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.content.res; 18 19import com.android.internal.util.XmlUtils; 20 21import org.xmlpull.v1.XmlPullParser; 22import org.xmlpull.v1.XmlPullParserException; 23 24import android.animation.Animator; 25import android.animation.StateListAnimator; 26import android.annotation.AnimRes; 27import android.annotation.AnyRes; 28import android.annotation.ArrayRes; 29import android.annotation.BoolRes; 30import android.annotation.ColorRes; 31import android.annotation.DimenRes; 32import android.annotation.DrawableRes; 33import android.annotation.FractionRes; 34import android.annotation.IntegerRes; 35import android.annotation.LayoutRes; 36import android.annotation.NonNull; 37import android.annotation.Nullable; 38import android.annotation.PluralsRes; 39import android.annotation.RawRes; 40import android.annotation.StringRes; 41import android.annotation.XmlRes; 42import android.content.pm.ActivityInfo; 43import android.content.res.ColorStateList.ColorStateListFactory; 44import android.graphics.Movie; 45import android.graphics.drawable.ColorDrawable; 46import android.graphics.drawable.Drawable; 47import android.graphics.drawable.Drawable.ConstantState; 48import android.os.Build; 49import android.os.Bundle; 50import android.os.IBinder; 51import android.os.Trace; 52import android.util.ArrayMap; 53import android.util.AttributeSet; 54import android.util.DisplayMetrics; 55import android.util.Log; 56import android.util.LongSparseArray; 57import android.util.Pools.SynchronizedPool; 58import android.util.Slog; 59import android.util.TypedValue; 60import android.view.ViewDebug; 61 62import java.io.IOException; 63import java.io.InputStream; 64import java.lang.ref.WeakReference; 65import java.util.Locale; 66 67import libcore.icu.NativePluralRules; 68 69/** 70 * Class for accessing an application's resources. This sits on top of the 71 * asset manager of the application (accessible through {@link #getAssets}) and 72 * provides a high-level API for getting typed data from the assets. 73 * 74 * <p>The Android resource system keeps track of all non-code assets associated with an 75 * application. You can use this class to access your application's resources. You can generally 76 * acquire the {@link android.content.res.Resources} instance associated with your application 77 * with {@link android.content.Context#getResources getResources()}.</p> 78 * 79 * <p>The Android SDK tools compile your application's resources into the application binary 80 * at build time. To use a resource, you must install it correctly in the source tree (inside 81 * your project's {@code res/} directory) and build your application. As part of the build 82 * process, the SDK tools generate symbols for each resource, which you can use in your application 83 * code to access the resources.</p> 84 * 85 * <p>Using application resources makes it easy to update various characteristics of your 86 * application without modifying code, and—by providing sets of alternative 87 * resources—enables you to optimize your application for a variety of device configurations 88 * (such as for different languages and screen sizes). This is an important aspect of developing 89 * Android applications that are compatible on different types of devices.</p> 90 * 91 * <p>For more information about using resources, see the documentation about <a 92 * href="{@docRoot}guide/topics/resources/index.html">Application Resources</a>.</p> 93 */ 94public class Resources { 95 static final String TAG = "Resources"; 96 97 private static final boolean DEBUG_LOAD = false; 98 private static final boolean DEBUG_CONFIG = false; 99 private static final boolean TRACE_FOR_PRELOAD = false; 100 private static final boolean TRACE_FOR_MISS_PRELOAD = false; 101 102 private static final int LAYOUT_DIR_CONFIG = ActivityInfo.activityInfoConfigToNative( 103 ActivityInfo.CONFIG_LAYOUT_DIRECTION); 104 105 private static final int ID_OTHER = 0x01000004; 106 107 private static final Object sSync = new Object(); 108 109 // Information about preloaded resources. Note that they are not 110 // protected by a lock, because while preloading in zygote we are all 111 // single-threaded, and after that these are immutable. 112 private static final LongSparseArray<ConstantState>[] sPreloadedDrawables; 113 private static final LongSparseArray<ConstantState> sPreloadedColorDrawables 114 = new LongSparseArray<ConstantState>(); 115 private static final LongSparseArray<ColorStateListFactory> sPreloadedColorStateLists 116 = new LongSparseArray<ColorStateListFactory>(); 117 118 // Pool of TypedArrays targeted to this Resources object. 119 final SynchronizedPool<TypedArray> mTypedArrayPool = new SynchronizedPool<TypedArray>(5); 120 121 // Used by BridgeResources in layoutlib 122 static Resources mSystem = null; 123 124 private static boolean sPreloaded; 125 private static int sPreloadedDensity; 126 127 // These are protected by mAccessLock. 128 private final Object mAccessLock = new Object(); 129 private final Configuration mTmpConfig = new Configuration(); 130 private final ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> mDrawableCache = 131 new ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>>(); 132 private final ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> mColorDrawableCache = 133 new ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>>(); 134 private final ConfigurationBoundResourceCache<ColorStateList> mColorStateListCache = 135 new ConfigurationBoundResourceCache<ColorStateList>(this); 136 private final ConfigurationBoundResourceCache<Animator> mAnimatorCache = 137 new ConfigurationBoundResourceCache<Animator>(this); 138 private final ConfigurationBoundResourceCache<StateListAnimator> mStateListAnimatorCache = 139 new ConfigurationBoundResourceCache<StateListAnimator>(this); 140 141 private TypedValue mTmpValue = new TypedValue(); 142 private boolean mPreloading; 143 144 private TypedArray mCachedStyledAttributes = null; 145 146 private int mLastCachedXmlBlockIndex = -1; 147 private final int[] mCachedXmlBlockIds = { 0, 0, 0, 0 }; 148 private final XmlBlock[] mCachedXmlBlocks = new XmlBlock[4]; 149 150 final AssetManager mAssets; 151 final DisplayMetrics mMetrics = new DisplayMetrics(); 152 153 private final Configuration mConfiguration = new Configuration(); 154 private NativePluralRules mPluralRule; 155 156 private CompatibilityInfo mCompatibilityInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO; 157 158 static { 159 sPreloadedDrawables = new LongSparseArray[2]; 160 sPreloadedDrawables[0] = new LongSparseArray<ConstantState>(); 161 sPreloadedDrawables[1] = new LongSparseArray<ConstantState>(); 162 } 163 164 /** 165 * Returns the most appropriate default theme for the specified target SDK version. 166 * <ul> 167 * <li>Below API 11: Gingerbread 168 * <li>APIs 11 thru 14: Holo 169 * <li>APIs 14 thru XX: Device default dark 170 * <li>API XX and above: Device default light with dark action bar 171 * </ul> 172 * 173 * @param curTheme The current theme, or 0 if not specified. 174 * @param targetSdkVersion The target SDK version. 175 * @return A theme resource identifier 176 * @hide 177 */ 178 public static int selectDefaultTheme(int curTheme, int targetSdkVersion) { 179 return selectSystemTheme(curTheme, targetSdkVersion, 180 com.android.internal.R.style.Theme, 181 com.android.internal.R.style.Theme_Holo, 182 com.android.internal.R.style.Theme_DeviceDefault, 183 com.android.internal.R.style.Theme_DeviceDefault_Light_DarkActionBar); 184 } 185 186 /** @hide */ 187 public static int selectSystemTheme(int curTheme, int targetSdkVersion, int orig, int holo, 188 int dark, int deviceDefault) { 189 if (curTheme != 0) { 190 return curTheme; 191 } 192 if (targetSdkVersion < Build.VERSION_CODES.HONEYCOMB) { 193 return orig; 194 } 195 if (targetSdkVersion < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { 196 return holo; 197 } 198 if (targetSdkVersion < Build.VERSION_CODES.CUR_DEVELOPMENT) { 199 return dark; 200 } 201 return deviceDefault; 202 } 203 204 /** 205 * Used by AnimatorInflater. 206 * 207 * @hide 208 */ 209 public ConfigurationBoundResourceCache<Animator> getAnimatorCache() { 210 return mAnimatorCache; 211 } 212 213 /** 214 * Used by AnimatorInflater. 215 * 216 * @hide 217 */ 218 public ConfigurationBoundResourceCache<StateListAnimator> getStateListAnimatorCache() { 219 return mStateListAnimatorCache; 220 } 221 222 /** 223 * This exception is thrown by the resource APIs when a requested resource 224 * can not be found. 225 */ 226 public static class NotFoundException extends RuntimeException { 227 public NotFoundException() { 228 } 229 230 public NotFoundException(String name) { 231 super(name); 232 } 233 } 234 235 /** 236 * Create a new Resources object on top of an existing set of assets in an 237 * AssetManager. 238 * 239 * @param assets Previously created AssetManager. 240 * @param metrics Current display metrics to consider when 241 * selecting/computing resource values. 242 * @param config Desired device configuration to consider when 243 * selecting/computing resource values (optional). 244 */ 245 public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config) { 246 this(assets, metrics, config, CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO); 247 } 248 249 /** 250 * Creates a new Resources object with CompatibilityInfo. 251 * 252 * @param assets Previously created AssetManager. 253 * @param metrics Current display metrics to consider when 254 * selecting/computing resource values. 255 * @param config Desired device configuration to consider when 256 * selecting/computing resource values (optional). 257 * @param compatInfo this resource's compatibility info. Must not be null. 258 * @hide 259 */ 260 public Resources(AssetManager assets, DisplayMetrics metrics, Configuration config, 261 CompatibilityInfo compatInfo) { 262 mAssets = assets; 263 mMetrics.setToDefaults(); 264 if (compatInfo != null) { 265 mCompatibilityInfo = compatInfo; 266 } 267 updateConfiguration(config, metrics); 268 assets.ensureStringBlocks(); 269 } 270 271 /** 272 * Return a global shared Resources object that provides access to only 273 * system resources (no application resources), and is not configured for 274 * the current screen (can not use dimension units, does not change based 275 * on orientation, etc). 276 */ 277 public static Resources getSystem() { 278 synchronized (sSync) { 279 Resources ret = mSystem; 280 if (ret == null) { 281 ret = new Resources(); 282 mSystem = ret; 283 } 284 285 return ret; 286 } 287 } 288 289 /** 290 * Return the string value associated with a particular resource ID. The 291 * returned object will be a String if this is a plain string; it will be 292 * some other type of CharSequence if it is styled. 293 * {@more} 294 * 295 * @param id The desired resource identifier, as generated by the aapt 296 * tool. This integer encodes the package, type, and resource 297 * entry. The value 0 is an invalid identifier. 298 * 299 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 300 * 301 * @return CharSequence The string data associated with the resource, plus 302 * possibly styled text information. 303 */ 304 public CharSequence getText(@StringRes int id) throws NotFoundException { 305 CharSequence res = mAssets.getResourceText(id); 306 if (res != null) { 307 return res; 308 } 309 throw new NotFoundException("String resource ID #0x" 310 + Integer.toHexString(id)); 311 } 312 313 /** 314 * Returns the character sequence necessary for grammatically correct pluralization 315 * of the given resource ID for the given quantity. 316 * Note that the character sequence is selected based solely on grammatical necessity, 317 * and that such rules differ between languages. Do not assume you know which string 318 * will be returned for a given quantity. See 319 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a> 320 * for more detail. 321 * 322 * @param id The desired resource identifier, as generated by the aapt 323 * tool. This integer encodes the package, type, and resource 324 * entry. The value 0 is an invalid identifier. 325 * @param quantity The number used to get the correct string for the current language's 326 * plural rules. 327 * 328 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 329 * 330 * @return CharSequence The string data associated with the resource, plus 331 * possibly styled text information. 332 */ 333 public CharSequence getQuantityText(@PluralsRes int id, int quantity) 334 throws NotFoundException { 335 NativePluralRules rule = getPluralRule(); 336 CharSequence res = mAssets.getResourceBagText(id, 337 attrForQuantityCode(rule.quantityForInt(quantity))); 338 if (res != null) { 339 return res; 340 } 341 res = mAssets.getResourceBagText(id, ID_OTHER); 342 if (res != null) { 343 return res; 344 } 345 throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id) 346 + " quantity=" + quantity 347 + " item=" + stringForQuantityCode(rule.quantityForInt(quantity))); 348 } 349 350 private NativePluralRules getPluralRule() { 351 synchronized (sSync) { 352 if (mPluralRule == null) { 353 mPluralRule = NativePluralRules.forLocale(mConfiguration.locale); 354 } 355 return mPluralRule; 356 } 357 } 358 359 private static int attrForQuantityCode(int quantityCode) { 360 switch (quantityCode) { 361 case NativePluralRules.ZERO: return 0x01000005; 362 case NativePluralRules.ONE: return 0x01000006; 363 case NativePluralRules.TWO: return 0x01000007; 364 case NativePluralRules.FEW: return 0x01000008; 365 case NativePluralRules.MANY: return 0x01000009; 366 default: return ID_OTHER; 367 } 368 } 369 370 private static String stringForQuantityCode(int quantityCode) { 371 switch (quantityCode) { 372 case NativePluralRules.ZERO: return "zero"; 373 case NativePluralRules.ONE: return "one"; 374 case NativePluralRules.TWO: return "two"; 375 case NativePluralRules.FEW: return "few"; 376 case NativePluralRules.MANY: return "many"; 377 default: return "other"; 378 } 379 } 380 381 /** 382 * Return the string value associated with a particular resource ID. It 383 * will be stripped of any styled text information. 384 * {@more} 385 * 386 * @param id The desired resource identifier, as generated by the aapt 387 * tool. This integer encodes the package, type, and resource 388 * entry. The value 0 is an invalid identifier. 389 * 390 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 391 * 392 * @return String The string data associated with the resource, 393 * stripped of styled text information. 394 */ 395 public String getString(@StringRes int id) throws NotFoundException { 396 CharSequence res = getText(id); 397 if (res != null) { 398 return res.toString(); 399 } 400 throw new NotFoundException("String resource ID #0x" 401 + Integer.toHexString(id)); 402 } 403 404 405 /** 406 * Return the string value associated with a particular resource ID, 407 * substituting the format arguments as defined in {@link java.util.Formatter} 408 * and {@link java.lang.String#format}. It will be stripped of any styled text 409 * information. 410 * {@more} 411 * 412 * @param id The desired resource identifier, as generated by the aapt 413 * tool. This integer encodes the package, type, and resource 414 * entry. The value 0 is an invalid identifier. 415 * 416 * @param formatArgs The format arguments that will be used for substitution. 417 * 418 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 419 * 420 * @return String The string data associated with the resource, 421 * stripped of styled text information. 422 */ 423 public String getString(@StringRes int id, Object... formatArgs) 424 throws NotFoundException { 425 String raw = getString(id); 426 return String.format(mConfiguration.locale, raw, formatArgs); 427 } 428 429 /** 430 * Formats the string necessary for grammatically correct pluralization 431 * of the given resource ID for the given quantity, using the given arguments. 432 * Note that the string is selected based solely on grammatical necessity, 433 * and that such rules differ between languages. Do not assume you know which string 434 * will be returned for a given quantity. See 435 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a> 436 * for more detail. 437 * 438 * <p>Substitution of format arguments works as if using 439 * {@link java.util.Formatter} and {@link java.lang.String#format}. 440 * The resulting string will be stripped of any styled text information. 441 * 442 * @param id The desired resource identifier, as generated by the aapt 443 * tool. This integer encodes the package, type, and resource 444 * entry. The value 0 is an invalid identifier. 445 * @param quantity The number used to get the correct string for the current language's 446 * plural rules. 447 * @param formatArgs The format arguments that will be used for substitution. 448 * 449 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 450 * 451 * @return String The string data associated with the resource, 452 * stripped of styled text information. 453 */ 454 public String getQuantityString(@PluralsRes int id, int quantity, Object... formatArgs) 455 throws NotFoundException { 456 String raw = getQuantityText(id, quantity).toString(); 457 return String.format(mConfiguration.locale, raw, formatArgs); 458 } 459 460 /** 461 * Returns the string necessary for grammatically correct pluralization 462 * of the given resource ID for the given quantity. 463 * Note that the string is selected based solely on grammatical necessity, 464 * and that such rules differ between languages. Do not assume you know which string 465 * will be returned for a given quantity. See 466 * <a href="{@docRoot}guide/topics/resources/string-resource.html#Plurals">String Resources</a> 467 * for more detail. 468 * 469 * @param id The desired resource identifier, as generated by the aapt 470 * tool. This integer encodes the package, type, and resource 471 * entry. The value 0 is an invalid identifier. 472 * @param quantity The number used to get the correct string for the current language's 473 * plural rules. 474 * 475 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 476 * 477 * @return String The string data associated with the resource, 478 * stripped of styled text information. 479 */ 480 public String getQuantityString(@PluralsRes int id, int quantity) 481 throws NotFoundException { 482 return getQuantityText(id, quantity).toString(); 483 } 484 485 /** 486 * Return the string value associated with a particular resource ID. The 487 * returned object will be a String if this is a plain string; it will be 488 * some other type of CharSequence if it is styled. 489 * 490 * @param id The desired resource identifier, as generated by the aapt 491 * tool. This integer encodes the package, type, and resource 492 * entry. The value 0 is an invalid identifier. 493 * 494 * @param def The default CharSequence to return. 495 * 496 * @return CharSequence The string data associated with the resource, plus 497 * possibly styled text information, or def if id is 0 or not found. 498 */ 499 public CharSequence getText(@StringRes int id, CharSequence def) { 500 CharSequence res = id != 0 ? mAssets.getResourceText(id) : null; 501 return res != null ? res : def; 502 } 503 504 /** 505 * Return the styled text array associated with a particular resource ID. 506 * 507 * @param id The desired resource identifier, as generated by the aapt 508 * tool. This integer encodes the package, type, and resource 509 * entry. The value 0 is an invalid identifier. 510 * 511 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 512 * 513 * @return The styled text array associated with the resource. 514 */ 515 public CharSequence[] getTextArray(@ArrayRes int id) throws NotFoundException { 516 CharSequence[] res = mAssets.getResourceTextArray(id); 517 if (res != null) { 518 return res; 519 } 520 throw new NotFoundException("Text array resource ID #0x" 521 + Integer.toHexString(id)); 522 } 523 524 /** 525 * Return the string array associated with a particular resource ID. 526 * 527 * @param id The desired resource identifier, as generated by the aapt 528 * tool. This integer encodes the package, type, and resource 529 * entry. The value 0 is an invalid identifier. 530 * 531 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 532 * 533 * @return The string array associated with the resource. 534 */ 535 public String[] getStringArray(@ArrayRes int id) 536 throws NotFoundException { 537 String[] res = mAssets.getResourceStringArray(id); 538 if (res != null) { 539 return res; 540 } 541 throw new NotFoundException("String array resource ID #0x" 542 + Integer.toHexString(id)); 543 } 544 545 /** 546 * Return the int array associated with a particular resource ID. 547 * 548 * @param id The desired resource identifier, as generated by the aapt 549 * tool. This integer encodes the package, type, and resource 550 * entry. The value 0 is an invalid identifier. 551 * 552 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 553 * 554 * @return The int array associated with the resource. 555 */ 556 public int[] getIntArray(@ArrayRes int id) throws NotFoundException { 557 int[] res = mAssets.getArrayIntResource(id); 558 if (res != null) { 559 return res; 560 } 561 throw new NotFoundException("Int array resource ID #0x" 562 + Integer.toHexString(id)); 563 } 564 565 /** 566 * Return an array of heterogeneous values. 567 * 568 * @param id The desired resource identifier, as generated by the aapt 569 * tool. This integer encodes the package, type, and resource 570 * entry. The value 0 is an invalid identifier. 571 * 572 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 573 * 574 * @return Returns a TypedArray holding an array of the array values. 575 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 576 * when done with it. 577 */ 578 public TypedArray obtainTypedArray(@ArrayRes int id) 579 throws NotFoundException { 580 int len = mAssets.getArraySize(id); 581 if (len < 0) { 582 throw new NotFoundException("Array resource ID #0x" 583 + Integer.toHexString(id)); 584 } 585 586 TypedArray array = TypedArray.obtain(this, len); 587 array.mLength = mAssets.retrieveArray(id, array.mData); 588 array.mIndices[0] = 0; 589 590 return array; 591 } 592 593 /** 594 * Retrieve a dimensional for a particular resource ID. Unit 595 * conversions are based on the current {@link DisplayMetrics} associated 596 * with the resources. 597 * 598 * @param id The desired resource identifier, as generated by the aapt 599 * tool. This integer encodes the package, type, and resource 600 * entry. The value 0 is an invalid identifier. 601 * 602 * @return Resource dimension value multiplied by the appropriate 603 * metric. 604 * 605 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 606 * 607 * @see #getDimensionPixelOffset 608 * @see #getDimensionPixelSize 609 */ 610 public float getDimension(@DimenRes int id) throws NotFoundException { 611 synchronized (mAccessLock) { 612 TypedValue value = mTmpValue; 613 if (value == null) { 614 mTmpValue = value = new TypedValue(); 615 } 616 getValue(id, value, true); 617 if (value.type == TypedValue.TYPE_DIMENSION) { 618 return TypedValue.complexToDimension(value.data, mMetrics); 619 } 620 throw new NotFoundException( 621 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 622 + Integer.toHexString(value.type) + " is not valid"); 623 } 624 } 625 626 /** 627 * Retrieve a dimensional for a particular resource ID for use 628 * as an offset in raw pixels. This is the same as 629 * {@link #getDimension}, except the returned value is converted to 630 * integer pixels for you. An offset conversion involves simply 631 * truncating the base value to an integer. 632 * 633 * @param id The desired resource identifier, as generated by the aapt 634 * tool. This integer encodes the package, type, and resource 635 * entry. The value 0 is an invalid identifier. 636 * 637 * @return Resource dimension value multiplied by the appropriate 638 * metric and truncated to integer pixels. 639 * 640 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 641 * 642 * @see #getDimension 643 * @see #getDimensionPixelSize 644 */ 645 public int getDimensionPixelOffset(@DimenRes int id) throws NotFoundException { 646 synchronized (mAccessLock) { 647 TypedValue value = mTmpValue; 648 if (value == null) { 649 mTmpValue = value = new TypedValue(); 650 } 651 getValue(id, value, true); 652 if (value.type == TypedValue.TYPE_DIMENSION) { 653 return TypedValue.complexToDimensionPixelOffset( 654 value.data, mMetrics); 655 } 656 throw new NotFoundException( 657 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 658 + Integer.toHexString(value.type) + " is not valid"); 659 } 660 } 661 662 /** 663 * Retrieve a dimensional for a particular resource ID for use 664 * as a size in raw pixels. This is the same as 665 * {@link #getDimension}, except the returned value is converted to 666 * integer pixels for use as a size. A size conversion involves 667 * rounding the base value, and ensuring that a non-zero base value 668 * is at least one pixel in size. 669 * 670 * @param id The desired resource identifier, as generated by the aapt 671 * tool. This integer encodes the package, type, and resource 672 * entry. The value 0 is an invalid identifier. 673 * 674 * @return Resource dimension value multiplied by the appropriate 675 * metric and truncated to integer pixels. 676 * 677 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 678 * 679 * @see #getDimension 680 * @see #getDimensionPixelOffset 681 */ 682 public int getDimensionPixelSize(@DimenRes int id) throws NotFoundException { 683 synchronized (mAccessLock) { 684 TypedValue value = mTmpValue; 685 if (value == null) { 686 mTmpValue = value = new TypedValue(); 687 } 688 getValue(id, value, true); 689 if (value.type == TypedValue.TYPE_DIMENSION) { 690 return TypedValue.complexToDimensionPixelSize( 691 value.data, mMetrics); 692 } 693 throw new NotFoundException( 694 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 695 + Integer.toHexString(value.type) + " is not valid"); 696 } 697 } 698 699 /** 700 * Retrieve a fractional unit for a particular resource ID. 701 * 702 * @param id The desired resource identifier, as generated by the aapt 703 * tool. This integer encodes the package, type, and resource 704 * entry. The value 0 is an invalid identifier. 705 * @param base The base value of this fraction. In other words, a 706 * standard fraction is multiplied by this value. 707 * @param pbase The parent base value of this fraction. In other 708 * words, a parent fraction (nn%p) is multiplied by this 709 * value. 710 * 711 * @return Attribute fractional value multiplied by the appropriate 712 * base value. 713 * 714 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 715 */ 716 public float getFraction(@FractionRes int id, int base, int pbase) { 717 synchronized (mAccessLock) { 718 TypedValue value = mTmpValue; 719 if (value == null) { 720 mTmpValue = value = new TypedValue(); 721 } 722 getValue(id, value, true); 723 if (value.type == TypedValue.TYPE_FRACTION) { 724 return TypedValue.complexToFraction(value.data, base, pbase); 725 } 726 throw new NotFoundException( 727 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 728 + Integer.toHexString(value.type) + " is not valid"); 729 } 730 } 731 732 /** 733 * Return a drawable object associated with a particular resource ID. 734 * Various types of objects will be returned depending on the underlying 735 * resource -- for example, a solid color, PNG image, scalable image, etc. 736 * The Drawable API hides these implementation details. 737 * 738 * <p class="note"><strong>Note:</strong> Prior to 739 * {@link android.os.Build.VERSION_CODES#JELLY_BEAN}, this function 740 * would not correctly retrieve the final configuration density when 741 * the resource ID passed here is an alias to another Drawable resource. 742 * This means that if the density configuration of the alias resource 743 * is different than the actual resource, the density of the returned 744 * Drawable would be incorrect, resulting in bad scaling. To work 745 * around this, you can instead retrieve the Drawable through 746 * {@link TypedArray#getDrawable TypedArray.getDrawable}. Use 747 * {@link android.content.Context#obtainStyledAttributes(int[]) 748 * Context.obtainStyledAttributes} with 749 * an array containing the resource ID of interest to create the TypedArray.</p> 750 * 751 * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use 752 * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)} 753 * or {@link #getDrawable(int, Theme)} passing the desired theme.</p> 754 * 755 * @param id The desired resource identifier, as generated by the aapt 756 * tool. This integer encodes the package, type, and resource 757 * entry. The value 0 is an invalid identifier. 758 * @return Drawable An object that can be used to draw this resource. 759 * @throws NotFoundException Throws NotFoundException if the given ID does 760 * not exist. 761 * @see #getDrawable(int, Theme) 762 * @deprecated Use {@link #getDrawable(int, Theme)} instead. 763 */ 764 @Deprecated 765 @Nullable 766 public Drawable getDrawable(@DrawableRes int id) throws NotFoundException { 767 final Drawable d = getDrawable(id, null); 768 if (d != null && d.canApplyTheme()) { 769 Log.w(TAG, "Drawable " + getResourceName(id) + " has unresolved theme " 770 + "attributes! Consider using Resources.getDrawable(int, Theme) or " 771 + "Context.getDrawable(int).", new RuntimeException()); 772 } 773 return d; 774 } 775 776 /** 777 * Return a drawable object associated with a particular resource ID and 778 * styled for the specified theme. Various types of objects will be 779 * returned depending on the underlying resource -- for example, a solid 780 * color, PNG image, scalable image, etc. 781 * 782 * @param id The desired resource identifier, as generated by the aapt 783 * tool. This integer encodes the package, type, and resource 784 * entry. The value 0 is an invalid identifier. 785 * @param theme The theme used to style the drawable attributes, may be {@code null}. 786 * @return Drawable An object that can be used to draw this resource. 787 * @throws NotFoundException Throws NotFoundException if the given ID does 788 * not exist. 789 */ 790 @Nullable 791 public Drawable getDrawable(@DrawableRes int id, @Nullable Theme theme) throws NotFoundException { 792 TypedValue value; 793 synchronized (mAccessLock) { 794 value = mTmpValue; 795 if (value == null) { 796 value = new TypedValue(); 797 } else { 798 mTmpValue = null; 799 } 800 getValue(id, value, true); 801 } 802 final Drawable res = loadDrawable(value, id, theme); 803 synchronized (mAccessLock) { 804 if (mTmpValue == null) { 805 mTmpValue = value; 806 } 807 } 808 return res; 809 } 810 811 /** 812 * Return a drawable object associated with a particular resource ID for the 813 * given screen density in DPI. This will set the drawable's density to be 814 * the device's density multiplied by the ratio of actual drawable density 815 * to requested density. This allows the drawable to be scaled up to the 816 * correct size if needed. Various types of objects will be returned 817 * depending on the underlying resource -- for example, a solid color, PNG 818 * image, scalable image, etc. The Drawable API hides these implementation 819 * details. 820 * 821 * <p class="note"><strong>Note:</strong> To obtain a themed drawable, use 822 * {@link android.content.Context#getDrawable(int) Context.getDrawable(int)} 823 * or {@link #getDrawableForDensity(int, int, Theme)} passing the desired 824 * theme.</p> 825 * 826 * @param id The desired resource identifier, as generated by the aapt tool. 827 * This integer encodes the package, type, and resource entry. 828 * The value 0 is an invalid identifier. 829 * @param density the desired screen density indicated by the resource as 830 * found in {@link DisplayMetrics}. 831 * @return Drawable An object that can be used to draw this resource. 832 * @throws NotFoundException Throws NotFoundException if the given ID does 833 * not exist. 834 * @see #getDrawableForDensity(int, int, Theme) 835 * @deprecated Use {@link #getDrawableForDensity(int, int, Theme)} instead. 836 */ 837 @Deprecated 838 @Nullable 839 public Drawable getDrawableForDensity(@DrawableRes int id, int density) throws NotFoundException { 840 return getDrawableForDensity(id, density, null); 841 } 842 843 /** 844 * Return a drawable object associated with a particular resource ID for the 845 * given screen density in DPI and styled for the specified theme. 846 * 847 * @param id The desired resource identifier, as generated by the aapt tool. 848 * This integer encodes the package, type, and resource entry. 849 * The value 0 is an invalid identifier. 850 * @param density The desired screen density indicated by the resource as 851 * found in {@link DisplayMetrics}. 852 * @param theme The theme used to style the drawable attributes, may be {@code null}. 853 * @return Drawable An object that can be used to draw this resource. 854 * @throws NotFoundException Throws NotFoundException if the given ID does 855 * not exist. 856 */ 857 @Nullable 858 public Drawable getDrawableForDensity(@DrawableRes int id, int density, @Nullable Theme theme) { 859 TypedValue value; 860 synchronized (mAccessLock) { 861 value = mTmpValue; 862 if (value == null) { 863 value = new TypedValue(); 864 } else { 865 mTmpValue = null; 866 } 867 getValueForDensity(id, density, value, true); 868 869 /* 870 * Pretend the requested density is actually the display density. If 871 * the drawable returned is not the requested density, then force it 872 * to be scaled later by dividing its density by the ratio of 873 * requested density to actual device density. Drawables that have 874 * undefined density or no density don't need to be handled here. 875 */ 876 if (value.density > 0 && value.density != TypedValue.DENSITY_NONE) { 877 if (value.density == density) { 878 value.density = mMetrics.densityDpi; 879 } else { 880 value.density = (value.density * mMetrics.densityDpi) / density; 881 } 882 } 883 } 884 885 final Drawable res = loadDrawable(value, id, theme); 886 synchronized (mAccessLock) { 887 if (mTmpValue == null) { 888 mTmpValue = value; 889 } 890 } 891 return res; 892 } 893 894 /** 895 * Return a movie object associated with the particular resource ID. 896 * @param id The desired resource identifier, as generated by the aapt 897 * tool. This integer encodes the package, type, and resource 898 * entry. The value 0 is an invalid identifier. 899 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 900 * 901 */ 902 public Movie getMovie(@RawRes int id) throws NotFoundException { 903 InputStream is = openRawResource(id); 904 Movie movie = Movie.decodeStream(is); 905 try { 906 is.close(); 907 } 908 catch (java.io.IOException e) { 909 // don't care, since the return value is valid 910 } 911 return movie; 912 } 913 914 /** 915 * Returns a color integer associated with a particular resource ID. If the 916 * resource holds a complex {@link ColorStateList}, then the default color 917 * from the set is returned. 918 * 919 * @param id The desired resource identifier, as generated by the aapt 920 * tool. This integer encodes the package, type, and resource 921 * entry. The value 0 is an invalid identifier. 922 * 923 * @throws NotFoundException Throws NotFoundException if the given ID does 924 * not exist. 925 * 926 * @return A single color value in the form 0xAARRGGBB. 927 * @deprecated Use {@link #getColor(int, Theme)} instead. 928 */ 929 public int getColor(@ColorRes int id) throws NotFoundException { 930 return getColor(id, null); 931 } 932 933 /** 934 * Returns a themed color integer associated with a particular resource ID. 935 * If the resource holds a complex {@link ColorStateList}, then the default 936 * color from the set is returned. 937 * 938 * @param id The desired resource identifier, as generated by the aapt 939 * tool. This integer encodes the package, type, and resource 940 * entry. The value 0 is an invalid identifier. 941 * @param theme The theme used to style the color attributes, may be 942 * {@code null}. 943 * 944 * @throws NotFoundException Throws NotFoundException if the given ID does 945 * not exist. 946 * 947 * @return A single color value in the form 0xAARRGGBB. 948 */ 949 public int getColor(@ColorRes int id, @Nullable Theme theme) throws NotFoundException { 950 TypedValue value; 951 synchronized (mAccessLock) { 952 value = mTmpValue; 953 if (value == null) { 954 value = new TypedValue(); 955 } 956 getValue(id, value, true); 957 if (value.type >= TypedValue.TYPE_FIRST_INT 958 && value.type <= TypedValue.TYPE_LAST_INT) { 959 mTmpValue = value; 960 return value.data; 961 } else if (value.type != TypedValue.TYPE_STRING) { 962 throw new NotFoundException( 963 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 964 + Integer.toHexString(value.type) + " is not valid"); 965 } 966 mTmpValue = null; 967 } 968 969 final ColorStateList csl = loadColorStateList(value, id, theme); 970 synchronized (mAccessLock) { 971 if (mTmpValue == null) { 972 mTmpValue = value; 973 } 974 } 975 976 return csl.getDefaultColor(); 977 } 978 979 /** 980 * Returns a color state list associated with a particular resource ID. The 981 * resource may contain either a single raw color value or a complex 982 * {@link ColorStateList} holding multiple possible colors. 983 * 984 * @param id The desired resource identifier of a {@link ColorStateList}, 985 * as generated by the aapt tool. This integer encodes the 986 * package, type, and resource entry. The value 0 is an invalid 987 * identifier. 988 * 989 * @throws NotFoundException Throws NotFoundException if the given ID does 990 * not exist. 991 * 992 * @return A ColorStateList object containing either a single solid color 993 * or multiple colors that can be selected based on a state. 994 * @deprecated Use {@link #getColorStateList(int, Theme)} instead. 995 */ 996 @Nullable 997 public ColorStateList getColorStateList(@ColorRes int id) throws NotFoundException { 998 final ColorStateList csl = getColorStateList(id, null); 999 if (csl != null && csl.canApplyTheme()) { 1000 Log.w(TAG, "ColorStateList " + getResourceName(id) + " has " 1001 + "unresolved theme attributes! Consider using " 1002 + "Resources.getColorStateList(int, Theme) or " 1003 + "Context.getColorStateList(int).", new RuntimeException()); 1004 } 1005 return csl; 1006 } 1007 1008 /** 1009 * Returns a themed color state list associated with a particular resource 1010 * ID. The resource may contain either a single raw color value or a 1011 * complex {@link ColorStateList} holding multiple possible colors. 1012 * 1013 * @param id The desired resource identifier of a {@link ColorStateList}, 1014 * as generated by the aapt tool. This integer encodes the 1015 * package, type, and resource entry. The value 0 is an invalid 1016 * identifier. 1017 * @param theme The theme used to style the color attributes, may be 1018 * {@code null}. 1019 * 1020 * @throws NotFoundException Throws NotFoundException if the given ID does 1021 * not exist. 1022 * 1023 * @return A themed ColorStateList object containing either a single solid 1024 * color or multiple colors that can be selected based on a state. 1025 */ 1026 @Nullable 1027 public ColorStateList getColorStateList(@ColorRes int id, @Nullable Theme theme) 1028 throws NotFoundException { 1029 TypedValue value; 1030 synchronized (mAccessLock) { 1031 value = mTmpValue; 1032 if (value == null) { 1033 value = new TypedValue(); 1034 } else { 1035 mTmpValue = null; 1036 } 1037 getValue(id, value, true); 1038 } 1039 1040 final ColorStateList res = loadColorStateList(value, id, theme); 1041 synchronized (mAccessLock) { 1042 if (mTmpValue == null) { 1043 mTmpValue = value; 1044 } 1045 } 1046 1047 return res; 1048 } 1049 1050 1051 1052 /** 1053 * Return a boolean associated with a particular resource ID. This can be 1054 * used with any integral resource value, and will return true if it is 1055 * non-zero. 1056 * 1057 * @param id The desired resource identifier, as generated by the aapt 1058 * tool. This integer encodes the package, type, and resource 1059 * entry. The value 0 is an invalid identifier. 1060 * 1061 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1062 * 1063 * @return Returns the boolean value contained in the resource. 1064 */ 1065 public boolean getBoolean(@BoolRes int id) throws NotFoundException { 1066 synchronized (mAccessLock) { 1067 TypedValue value = mTmpValue; 1068 if (value == null) { 1069 mTmpValue = value = new TypedValue(); 1070 } 1071 getValue(id, value, true); 1072 if (value.type >= TypedValue.TYPE_FIRST_INT 1073 && value.type <= TypedValue.TYPE_LAST_INT) { 1074 return value.data != 0; 1075 } 1076 throw new NotFoundException( 1077 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 1078 + Integer.toHexString(value.type) + " is not valid"); 1079 } 1080 } 1081 1082 /** 1083 * Return an integer associated with a particular resource ID. 1084 * 1085 * @param id The desired resource identifier, as generated by the aapt 1086 * tool. This integer encodes the package, type, and resource 1087 * entry. The value 0 is an invalid identifier. 1088 * 1089 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1090 * 1091 * @return Returns the integer value contained in the resource. 1092 */ 1093 public int getInteger(@IntegerRes int id) throws NotFoundException { 1094 synchronized (mAccessLock) { 1095 TypedValue value = mTmpValue; 1096 if (value == null) { 1097 mTmpValue = value = new TypedValue(); 1098 } 1099 getValue(id, value, true); 1100 if (value.type >= TypedValue.TYPE_FIRST_INT 1101 && value.type <= TypedValue.TYPE_LAST_INT) { 1102 return value.data; 1103 } 1104 throw new NotFoundException( 1105 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 1106 + Integer.toHexString(value.type) + " is not valid"); 1107 } 1108 } 1109 1110 /** 1111 * Retrieve a floating-point value for a particular resource ID. 1112 * 1113 * @param id The desired resource identifier, as generated by the aapt 1114 * tool. This integer encodes the package, type, and resource 1115 * entry. The value 0 is an invalid identifier. 1116 * 1117 * @return Returns the floating-point value contained in the resource. 1118 * 1119 * @throws NotFoundException Throws NotFoundException if the given ID does 1120 * not exist or is not a floating-point value. 1121 * @hide Pending API council approval. 1122 */ 1123 public float getFloat(int id) { 1124 synchronized (mAccessLock) { 1125 TypedValue value = mTmpValue; 1126 if (value == null) { 1127 mTmpValue = value = new TypedValue(); 1128 } 1129 getValue(id, value, true); 1130 if (value.type == TypedValue.TYPE_FLOAT) { 1131 return value.getFloat(); 1132 } 1133 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id) + " type #0x" 1134 + Integer.toHexString(value.type) + " is not valid"); 1135 } 1136 } 1137 1138 /** 1139 * Return an XmlResourceParser through which you can read a view layout 1140 * description for the given resource ID. This parser has limited 1141 * functionality -- in particular, you can't change its input, and only 1142 * the high-level events are available. 1143 * 1144 * <p>This function is really a simple wrapper for calling 1145 * {@link #getXml} with a layout resource. 1146 * 1147 * @param id The desired resource identifier, as generated by the aapt 1148 * tool. This integer encodes the package, type, and resource 1149 * entry. The value 0 is an invalid identifier. 1150 * 1151 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1152 * 1153 * @return A new parser object through which you can read 1154 * the XML data. 1155 * 1156 * @see #getXml 1157 */ 1158 public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException { 1159 return loadXmlResourceParser(id, "layout"); 1160 } 1161 1162 /** 1163 * Return an XmlResourceParser through which you can read an animation 1164 * description for the given resource ID. This parser has limited 1165 * functionality -- in particular, you can't change its input, and only 1166 * the high-level events are available. 1167 * 1168 * <p>This function is really a simple wrapper for calling 1169 * {@link #getXml} with an animation resource. 1170 * 1171 * @param id The desired resource identifier, as generated by the aapt 1172 * tool. This integer encodes the package, type, and resource 1173 * entry. The value 0 is an invalid identifier. 1174 * 1175 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1176 * 1177 * @return A new parser object through which you can read 1178 * the XML data. 1179 * 1180 * @see #getXml 1181 */ 1182 public XmlResourceParser getAnimation(@AnimRes int id) throws NotFoundException { 1183 return loadXmlResourceParser(id, "anim"); 1184 } 1185 1186 /** 1187 * Return an XmlResourceParser through which you can read a generic XML 1188 * resource for the given resource ID. 1189 * 1190 * <p>The XmlPullParser implementation returned here has some limited 1191 * functionality. In particular, you can't change its input, and only 1192 * high-level parsing events are available (since the document was 1193 * pre-parsed for you at build time, which involved merging text and 1194 * stripping comments). 1195 * 1196 * @param id The desired resource identifier, as generated by the aapt 1197 * tool. This integer encodes the package, type, and resource 1198 * entry. The value 0 is an invalid identifier. 1199 * 1200 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1201 * 1202 * @return A new parser object through which you can read 1203 * the XML data. 1204 * 1205 * @see android.util.AttributeSet 1206 */ 1207 public XmlResourceParser getXml(@XmlRes int id) throws NotFoundException { 1208 return loadXmlResourceParser(id, "xml"); 1209 } 1210 1211 /** 1212 * Open a data stream for reading a raw resource. This can only be used 1213 * with resources whose value is the name of an asset files -- that is, it can be 1214 * used to open drawable, sound, and raw resources; it will fail on string 1215 * and color resources. 1216 * 1217 * @param id The resource identifier to open, as generated by the appt 1218 * tool. 1219 * 1220 * @return InputStream Access to the resource data. 1221 * 1222 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1223 * 1224 */ 1225 public InputStream openRawResource(@RawRes int id) throws NotFoundException { 1226 TypedValue value; 1227 synchronized (mAccessLock) { 1228 value = mTmpValue; 1229 if (value == null) { 1230 value = new TypedValue(); 1231 } else { 1232 mTmpValue = null; 1233 } 1234 } 1235 InputStream res = openRawResource(id, value); 1236 synchronized (mAccessLock) { 1237 if (mTmpValue == null) { 1238 mTmpValue = value; 1239 } 1240 } 1241 return res; 1242 } 1243 1244 /** 1245 * Open a data stream for reading a raw resource. This can only be used 1246 * with resources whose value is the name of an asset file -- that is, it can be 1247 * used to open drawable, sound, and raw resources; it will fail on string 1248 * and color resources. 1249 * 1250 * @param id The resource identifier to open, as generated by the appt tool. 1251 * @param value The TypedValue object to hold the resource information. 1252 * 1253 * @return InputStream Access to the resource data. 1254 * 1255 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1256 */ 1257 public InputStream openRawResource(@RawRes int id, TypedValue value) 1258 throws NotFoundException { 1259 getValue(id, value, true); 1260 1261 try { 1262 return mAssets.openNonAsset(value.assetCookie, value.string.toString(), 1263 AssetManager.ACCESS_STREAMING); 1264 } catch (Exception e) { 1265 NotFoundException rnf = new NotFoundException("File " + value.string.toString() + 1266 " from drawable resource ID #0x" + Integer.toHexString(id)); 1267 rnf.initCause(e); 1268 throw rnf; 1269 } 1270 } 1271 1272 /** 1273 * Open a file descriptor for reading a raw resource. This can only be used 1274 * with resources whose value is the name of an asset files -- that is, it can be 1275 * used to open drawable, sound, and raw resources; it will fail on string 1276 * and color resources. 1277 * 1278 * <p>This function only works for resources that are stored in the package 1279 * as uncompressed data, which typically includes things like mp3 files 1280 * and png images. 1281 * 1282 * @param id The resource identifier to open, as generated by the appt 1283 * tool. 1284 * 1285 * @return AssetFileDescriptor A new file descriptor you can use to read 1286 * the resource. This includes the file descriptor itself, as well as the 1287 * offset and length of data where the resource appears in the file. A 1288 * null is returned if the file exists but is compressed. 1289 * 1290 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1291 * 1292 */ 1293 public AssetFileDescriptor openRawResourceFd(@RawRes int id) 1294 throws NotFoundException { 1295 TypedValue value; 1296 synchronized (mAccessLock) { 1297 value = mTmpValue; 1298 if (value == null) { 1299 value = new TypedValue(); 1300 } else { 1301 mTmpValue = null; 1302 } 1303 getValue(id, value, true); 1304 } 1305 try { 1306 return mAssets.openNonAssetFd( 1307 value.assetCookie, value.string.toString()); 1308 } catch (Exception e) { 1309 NotFoundException rnf = new NotFoundException( 1310 "File " + value.string.toString() 1311 + " from drawable resource ID #0x" 1312 + Integer.toHexString(id)); 1313 rnf.initCause(e); 1314 throw rnf; 1315 } finally { 1316 synchronized (mAccessLock) { 1317 if (mTmpValue == null) { 1318 mTmpValue = value; 1319 } 1320 } 1321 } 1322 } 1323 1324 /** 1325 * Return the raw data associated with a particular resource ID. 1326 * 1327 * @param id The desired resource identifier, as generated by the aapt 1328 * tool. This integer encodes the package, type, and resource 1329 * entry. The value 0 is an invalid identifier. 1330 * @param outValue Object in which to place the resource data. 1331 * @param resolveRefs If true, a resource that is a reference to another 1332 * resource will be followed so that you receive the 1333 * actual final resource data. If false, the TypedValue 1334 * will be filled in with the reference itself. 1335 * 1336 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1337 * 1338 */ 1339 public void getValue(@AnyRes int id, TypedValue outValue, boolean resolveRefs) 1340 throws NotFoundException { 1341 boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs); 1342 if (found) { 1343 return; 1344 } 1345 throw new NotFoundException("Resource ID #0x" 1346 + Integer.toHexString(id)); 1347 } 1348 1349 /** 1350 * Get the raw value associated with a resource with associated density. 1351 * 1352 * @param id resource identifier 1353 * @param density density in DPI 1354 * @param resolveRefs If true, a resource that is a reference to another 1355 * resource will be followed so that you receive the actual final 1356 * resource data. If false, the TypedValue will be filled in with 1357 * the reference itself. 1358 * @throws NotFoundException Throws NotFoundException if the given ID does 1359 * not exist. 1360 * @see #getValue(String, TypedValue, boolean) 1361 */ 1362 public void getValueForDensity(@AnyRes int id, int density, TypedValue outValue, 1363 boolean resolveRefs) throws NotFoundException { 1364 boolean found = mAssets.getResourceValue(id, density, outValue, resolveRefs); 1365 if (found) { 1366 return; 1367 } 1368 throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)); 1369 } 1370 1371 /** 1372 * Return the raw data associated with a particular resource ID. 1373 * See getIdentifier() for information on how names are mapped to resource 1374 * IDs, and getString(int) for information on how string resources are 1375 * retrieved. 1376 * 1377 * <p>Note: use of this function is discouraged. It is much more 1378 * efficient to retrieve resources by identifier than by name. 1379 * 1380 * @param name The name of the desired resource. This is passed to 1381 * getIdentifier() with a default type of "string". 1382 * @param outValue Object in which to place the resource data. 1383 * @param resolveRefs If true, a resource that is a reference to another 1384 * resource will be followed so that you receive the 1385 * actual final resource data. If false, the TypedValue 1386 * will be filled in with the reference itself. 1387 * 1388 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1389 * 1390 */ 1391 public void getValue(String name, TypedValue outValue, boolean resolveRefs) 1392 throws NotFoundException { 1393 int id = getIdentifier(name, "string", null); 1394 if (id != 0) { 1395 getValue(id, outValue, resolveRefs); 1396 return; 1397 } 1398 throw new NotFoundException("String resource name " + name); 1399 } 1400 1401 /** 1402 * This class holds the current attribute values for a particular theme. 1403 * In other words, a Theme is a set of values for resource attributes; 1404 * these are used in conjunction with {@link TypedArray} 1405 * to resolve the final value for an attribute. 1406 * 1407 * <p>The Theme's attributes come into play in two ways: (1) a styled 1408 * attribute can explicit reference a value in the theme through the 1409 * "?themeAttribute" syntax; (2) if no value has been defined for a 1410 * particular styled attribute, as a last resort we will try to find that 1411 * attribute's value in the Theme. 1412 * 1413 * <p>You will normally use the {@link #obtainStyledAttributes} APIs to 1414 * retrieve XML attributes with style and theme information applied. 1415 */ 1416 public final class Theme { 1417 /** 1418 * Place new attribute values into the theme. The style resource 1419 * specified by <var>resid</var> will be retrieved from this Theme's 1420 * resources, its values placed into the Theme object. 1421 * 1422 * <p>The semantics of this function depends on the <var>force</var> 1423 * argument: If false, only values that are not already defined in 1424 * the theme will be copied from the system resource; otherwise, if 1425 * any of the style's attributes are already defined in the theme, the 1426 * current values in the theme will be overwritten. 1427 * 1428 * @param resId The resource ID of a style resource from which to 1429 * obtain attribute values. 1430 * @param force If true, values in the style resource will always be 1431 * used in the theme; otherwise, they will only be used 1432 * if not already defined in the theme. 1433 */ 1434 public void applyStyle(int resId, boolean force) { 1435 AssetManager.applyThemeStyle(mTheme, resId, force); 1436 1437 mThemeResId = resId; 1438 mKey += Integer.toHexString(resId) + (force ? "! " : " "); 1439 } 1440 1441 /** 1442 * Set this theme to hold the same contents as the theme 1443 * <var>other</var>. If both of these themes are from the same 1444 * Resources object, they will be identical after this function 1445 * returns. If they are from different Resources, only the resources 1446 * they have in common will be set in this theme. 1447 * 1448 * @param other The existing Theme to copy from. 1449 */ 1450 public void setTo(Theme other) { 1451 AssetManager.copyTheme(mTheme, other.mTheme); 1452 1453 mThemeResId = other.mThemeResId; 1454 mKey = other.mKey; 1455 } 1456 1457 /** 1458 * Return a TypedArray holding the values defined by 1459 * <var>Theme</var> which are listed in <var>attrs</var>. 1460 * 1461 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done 1462 * with the array. 1463 * 1464 * @param attrs The desired attributes. 1465 * 1466 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1467 * 1468 * @return Returns a TypedArray holding an array of the attribute values. 1469 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1470 * when done with it. 1471 * 1472 * @see Resources#obtainAttributes 1473 * @see #obtainStyledAttributes(int, int[]) 1474 * @see #obtainStyledAttributes(AttributeSet, int[], int, int) 1475 */ 1476 public TypedArray obtainStyledAttributes(int[] attrs) { 1477 final int len = attrs.length; 1478 final TypedArray array = TypedArray.obtain(Resources.this, len); 1479 array.mTheme = this; 1480 AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, array.mData, array.mIndices); 1481 return array; 1482 } 1483 1484 /** 1485 * Return a TypedArray holding the values defined by the style 1486 * resource <var>resid</var> which are listed in <var>attrs</var>. 1487 * 1488 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done 1489 * with the array. 1490 * 1491 * @param resid The desired style resource. 1492 * @param attrs The desired attributes in the style. 1493 * 1494 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1495 * 1496 * @return Returns a TypedArray holding an array of the attribute values. 1497 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1498 * when done with it. 1499 * 1500 * @see Resources#obtainAttributes 1501 * @see #obtainStyledAttributes(int[]) 1502 * @see #obtainStyledAttributes(AttributeSet, int[], int, int) 1503 */ 1504 public TypedArray obtainStyledAttributes(int resid, int[] attrs) throws NotFoundException { 1505 final int len = attrs.length; 1506 final TypedArray array = TypedArray.obtain(Resources.this, len); 1507 array.mTheme = this; 1508 if (false) { 1509 int[] data = array.mData; 1510 1511 System.out.println("**********************************************************"); 1512 System.out.println("**********************************************************"); 1513 System.out.println("**********************************************************"); 1514 System.out.println("Attributes:"); 1515 String s = " Attrs:"; 1516 int i; 1517 for (i=0; i<attrs.length; i++) { 1518 s = s + " 0x" + Integer.toHexString(attrs[i]); 1519 } 1520 System.out.println(s); 1521 s = " Found:"; 1522 TypedValue value = new TypedValue(); 1523 for (i=0; i<attrs.length; i++) { 1524 int d = i*AssetManager.STYLE_NUM_ENTRIES; 1525 value.type = data[d+AssetManager.STYLE_TYPE]; 1526 value.data = data[d+AssetManager.STYLE_DATA]; 1527 value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE]; 1528 value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID]; 1529 s = s + " 0x" + Integer.toHexString(attrs[i]) 1530 + "=" + value; 1531 } 1532 System.out.println(s); 1533 } 1534 AssetManager.applyStyle(mTheme, 0, resid, 0, attrs, array.mData, array.mIndices); 1535 return array; 1536 } 1537 1538 /** 1539 * Return a TypedArray holding the attribute values in 1540 * <var>set</var> 1541 * that are listed in <var>attrs</var>. In addition, if the given 1542 * AttributeSet specifies a style class (through the "style" attribute), 1543 * that style will be applied on top of the base attributes it defines. 1544 * 1545 * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done 1546 * with the array. 1547 * 1548 * <p>When determining the final value of a particular attribute, there 1549 * are four inputs that come into play:</p> 1550 * 1551 * <ol> 1552 * <li> Any attribute values in the given AttributeSet. 1553 * <li> The style resource specified in the AttributeSet (named 1554 * "style"). 1555 * <li> The default style specified by <var>defStyleAttr</var> and 1556 * <var>defStyleRes</var> 1557 * <li> The base values in this theme. 1558 * </ol> 1559 * 1560 * <p>Each of these inputs is considered in-order, with the first listed 1561 * taking precedence over the following ones. In other words, if in the 1562 * AttributeSet you have supplied <code><Button 1563 * textColor="#ff000000"></code>, then the button's text will 1564 * <em>always</em> be black, regardless of what is specified in any of 1565 * the styles. 1566 * 1567 * @param set The base set of attribute values. May be null. 1568 * @param attrs The desired attributes to be retrieved. 1569 * @param defStyleAttr An attribute in the current theme that contains a 1570 * reference to a style resource that supplies 1571 * defaults values for the TypedArray. Can be 1572 * 0 to not look for defaults. 1573 * @param defStyleRes A resource identifier of a style resource that 1574 * supplies default values for the TypedArray, 1575 * used only if defStyleAttr is 0 or can not be found 1576 * in the theme. Can be 0 to not look for defaults. 1577 * 1578 * @return Returns a TypedArray holding an array of the attribute values. 1579 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1580 * when done with it. 1581 * 1582 * @see Resources#obtainAttributes 1583 * @see #obtainStyledAttributes(int[]) 1584 * @see #obtainStyledAttributes(int, int[]) 1585 */ 1586 public TypedArray obtainStyledAttributes(AttributeSet set, 1587 int[] attrs, int defStyleAttr, int defStyleRes) { 1588 final int len = attrs.length; 1589 final TypedArray array = TypedArray.obtain(Resources.this, len); 1590 1591 // XXX note that for now we only work with compiled XML files. 1592 // To support generic XML files we will need to manually parse 1593 // out the attributes from the XML file (applying type information 1594 // contained in the resources and such). 1595 final XmlBlock.Parser parser = (XmlBlock.Parser)set; 1596 AssetManager.applyStyle(mTheme, defStyleAttr, defStyleRes, 1597 parser != null ? parser.mParseState : 0, attrs, array.mData, array.mIndices); 1598 1599 array.mTheme = this; 1600 array.mXml = parser; 1601 1602 if (false) { 1603 int[] data = array.mData; 1604 1605 System.out.println("Attributes:"); 1606 String s = " Attrs:"; 1607 int i; 1608 for (i=0; i<set.getAttributeCount(); i++) { 1609 s = s + " " + set.getAttributeName(i); 1610 int id = set.getAttributeNameResource(i); 1611 if (id != 0) { 1612 s = s + "(0x" + Integer.toHexString(id) + ")"; 1613 } 1614 s = s + "=" + set.getAttributeValue(i); 1615 } 1616 System.out.println(s); 1617 s = " Found:"; 1618 TypedValue value = new TypedValue(); 1619 for (i=0; i<attrs.length; i++) { 1620 int d = i*AssetManager.STYLE_NUM_ENTRIES; 1621 value.type = data[d+AssetManager.STYLE_TYPE]; 1622 value.data = data[d+AssetManager.STYLE_DATA]; 1623 value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE]; 1624 value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID]; 1625 s = s + " 0x" + Integer.toHexString(attrs[i]) 1626 + "=" + value; 1627 } 1628 System.out.println(s); 1629 } 1630 1631 return array; 1632 } 1633 1634 /** 1635 * Retrieve the values for a set of attributes in the Theme. The 1636 * contents of the typed array are ultimately filled in by 1637 * {@link Resources#getValue}. 1638 * 1639 * @param values The base set of attribute values, must be equal in 1640 * length to {@code attrs}. All values must be of type 1641 * {@link TypedValue#TYPE_ATTRIBUTE}. 1642 * @param attrs The desired attributes to be retrieved. 1643 * @return Returns a TypedArray holding an array of the attribute 1644 * values. Be sure to call {@link TypedArray#recycle()} 1645 * when done with it. 1646 * @hide 1647 */ 1648 @NonNull 1649 public TypedArray resolveAttributes(@NonNull int[] values, @NonNull int[] attrs) { 1650 final int len = attrs.length; 1651 if (values == null || len != values.length) { 1652 throw new IllegalArgumentException( 1653 "Base attribute values must the same length as attrs"); 1654 } 1655 1656 final TypedArray array = TypedArray.obtain(Resources.this, len); 1657 AssetManager.resolveAttrs(mTheme, 0, 0, values, attrs, array.mData, array.mIndices); 1658 array.mTheme = this; 1659 array.mXml = null; 1660 1661 return array; 1662 } 1663 1664 /** 1665 * Retrieve the value of an attribute in the Theme. The contents of 1666 * <var>outValue</var> are ultimately filled in by 1667 * {@link Resources#getValue}. 1668 * 1669 * @param resid The resource identifier of the desired theme 1670 * attribute. 1671 * @param outValue Filled in with the ultimate resource value supplied 1672 * by the attribute. 1673 * @param resolveRefs If true, resource references will be walked; if 1674 * false, <var>outValue</var> may be a 1675 * TYPE_REFERENCE. In either case, it will never 1676 * be a TYPE_ATTRIBUTE. 1677 * 1678 * @return boolean Returns true if the attribute was found and 1679 * <var>outValue</var> is valid, else false. 1680 */ 1681 public boolean resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs) { 1682 boolean got = mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs); 1683 if (false) { 1684 System.out.println( 1685 "resolveAttribute #" + Integer.toHexString(resid) 1686 + " got=" + got + ", type=0x" + Integer.toHexString(outValue.type) 1687 + ", data=0x" + Integer.toHexString(outValue.data)); 1688 } 1689 return got; 1690 } 1691 1692 /** 1693 * Gets all of the attribute ids associated with this {@link Theme}. For debugging only. 1694 * 1695 * @return The int array containing attribute ids associated with this {@link Theme}. 1696 * @hide 1697 */ 1698 public int[] getAllAttributes() { 1699 return mAssets.getStyleAttributes(getAppliedStyleResId()); 1700 } 1701 1702 /** 1703 * Returns the resources to which this theme belongs. 1704 * 1705 * @return Resources to which this theme belongs. 1706 */ 1707 public Resources getResources() { 1708 return Resources.this; 1709 } 1710 1711 /** 1712 * Return a drawable object associated with a particular resource ID 1713 * and styled for the Theme. 1714 * 1715 * @param id The desired resource identifier, as generated by the aapt 1716 * tool. This integer encodes the package, type, and resource 1717 * entry. The value 0 is an invalid identifier. 1718 * @return Drawable An object that can be used to draw this resource. 1719 * @throws NotFoundException Throws NotFoundException if the given ID 1720 * does not exist. 1721 */ 1722 public Drawable getDrawable(@DrawableRes int id) throws NotFoundException { 1723 return Resources.this.getDrawable(id, this); 1724 } 1725 1726 /** 1727 * Print contents of this theme out to the log. For debugging only. 1728 * 1729 * @param priority The log priority to use. 1730 * @param tag The log tag to use. 1731 * @param prefix Text to prefix each line printed. 1732 */ 1733 public void dump(int priority, String tag, String prefix) { 1734 AssetManager.dumpTheme(mTheme, priority, tag, prefix); 1735 } 1736 1737 @Override 1738 protected void finalize() throws Throwable { 1739 super.finalize(); 1740 mAssets.releaseTheme(mTheme); 1741 } 1742 1743 /*package*/ Theme() { 1744 mAssets = Resources.this.mAssets; 1745 mTheme = mAssets.createTheme(); 1746 } 1747 1748 @SuppressWarnings("hiding") 1749 private final AssetManager mAssets; 1750 private final long mTheme; 1751 1752 /** Resource identifier for the theme. */ 1753 private int mThemeResId = 0; 1754 1755 /** Unique key for the series of styles applied to this theme. */ 1756 private String mKey = ""; 1757 1758 // Needed by layoutlib. 1759 /*package*/ long getNativeTheme() { 1760 return mTheme; 1761 } 1762 1763 /*package*/ int getAppliedStyleResId() { 1764 return mThemeResId; 1765 } 1766 1767 /*package*/ String getKey() { 1768 return mKey; 1769 } 1770 1771 private String getResourceNameFromHexString(String hexString) { 1772 return getResourceName(Integer.parseInt(hexString, 16)); 1773 } 1774 1775 /** 1776 * Parses {@link #mKey} and returns a String array that holds pairs of adjacent Theme data: 1777 * resource name followed by whether or not it was forced, as specified by 1778 * {@link #applyStyle(int, boolean)}. 1779 * 1780 * @hide 1781 */ 1782 @ViewDebug.ExportedProperty(category = "theme", hasAdjacentMapping = true) 1783 public String[] getTheme() { 1784 String[] themeData = mKey.split(" "); 1785 String[] themes = new String[themeData.length * 2]; 1786 String theme; 1787 boolean forced; 1788 1789 for (int i = 0, j = themeData.length - 1; i < themes.length; i += 2, --j) { 1790 theme = themeData[j]; 1791 forced = theme.endsWith("!"); 1792 themes[i] = forced ? 1793 getResourceNameFromHexString(theme.substring(0, theme.length() - 1)) : 1794 getResourceNameFromHexString(theme); 1795 themes[i + 1] = forced ? "forced" : "not forced"; 1796 } 1797 return themes; 1798 } 1799 } 1800 1801 /** 1802 * Generate a new Theme object for this set of Resources. It initially 1803 * starts out empty. 1804 * 1805 * @return Theme The newly created Theme container. 1806 */ 1807 public final Theme newTheme() { 1808 return new Theme(); 1809 } 1810 1811 /** 1812 * Retrieve a set of basic attribute values from an AttributeSet, not 1813 * performing styling of them using a theme and/or style resources. 1814 * 1815 * @param set The current attribute values to retrieve. 1816 * @param attrs The specific attributes to be retrieved. 1817 * @return Returns a TypedArray holding an array of the attribute values. 1818 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1819 * when done with it. 1820 * 1821 * @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int) 1822 */ 1823 public TypedArray obtainAttributes(AttributeSet set, int[] attrs) { 1824 int len = attrs.length; 1825 TypedArray array = TypedArray.obtain(this, len); 1826 1827 // XXX note that for now we only work with compiled XML files. 1828 // To support generic XML files we will need to manually parse 1829 // out the attributes from the XML file (applying type information 1830 // contained in the resources and such). 1831 XmlBlock.Parser parser = (XmlBlock.Parser)set; 1832 mAssets.retrieveAttributes(parser.mParseState, attrs, 1833 array.mData, array.mIndices); 1834 1835 array.mXml = parser; 1836 1837 return array; 1838 } 1839 1840 /** 1841 * Store the newly updated configuration. 1842 */ 1843 public void updateConfiguration(Configuration config, 1844 DisplayMetrics metrics) { 1845 updateConfiguration(config, metrics, null); 1846 } 1847 1848 /** 1849 * @hide 1850 */ 1851 public void updateConfiguration(Configuration config, 1852 DisplayMetrics metrics, CompatibilityInfo compat) { 1853 synchronized (mAccessLock) { 1854 if (false) { 1855 Slog.i(TAG, "**** Updating config of " + this + ": old config is " 1856 + mConfiguration + " old compat is " + mCompatibilityInfo); 1857 Slog.i(TAG, "**** Updating config of " + this + ": new config is " 1858 + config + " new compat is " + compat); 1859 } 1860 if (compat != null) { 1861 mCompatibilityInfo = compat; 1862 } 1863 if (metrics != null) { 1864 mMetrics.setTo(metrics); 1865 } 1866 // NOTE: We should re-arrange this code to create a Display 1867 // with the CompatibilityInfo that is used everywhere we deal 1868 // with the display in relation to this app, rather than 1869 // doing the conversion here. This impl should be okay because 1870 // we make sure to return a compatible display in the places 1871 // where there are public APIs to retrieve the display... but 1872 // it would be cleaner and more maintainble to just be 1873 // consistently dealing with a compatible display everywhere in 1874 // the framework. 1875 mCompatibilityInfo.applyToDisplayMetrics(mMetrics); 1876 1877 int configChanges = calcConfigChanges(config); 1878 if (mConfiguration.locale == null) { 1879 mConfiguration.locale = Locale.getDefault(); 1880 mConfiguration.setLayoutDirection(mConfiguration.locale); 1881 } 1882 if (mConfiguration.densityDpi != Configuration.DENSITY_DPI_UNDEFINED) { 1883 mMetrics.densityDpi = mConfiguration.densityDpi; 1884 mMetrics.density = mConfiguration.densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE; 1885 } 1886 mMetrics.scaledDensity = mMetrics.density * mConfiguration.fontScale; 1887 1888 String locale = null; 1889 if (mConfiguration.locale != null) { 1890 locale = adjustLanguageTag(mConfiguration.locale.toLanguageTag()); 1891 } 1892 int width, height; 1893 if (mMetrics.widthPixels >= mMetrics.heightPixels) { 1894 width = mMetrics.widthPixels; 1895 height = mMetrics.heightPixels; 1896 } else { 1897 //noinspection SuspiciousNameCombination 1898 width = mMetrics.heightPixels; 1899 //noinspection SuspiciousNameCombination 1900 height = mMetrics.widthPixels; 1901 } 1902 int keyboardHidden = mConfiguration.keyboardHidden; 1903 if (keyboardHidden == Configuration.KEYBOARDHIDDEN_NO 1904 && mConfiguration.hardKeyboardHidden 1905 == Configuration.HARDKEYBOARDHIDDEN_YES) { 1906 keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT; 1907 } 1908 mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc, 1909 locale, mConfiguration.orientation, 1910 mConfiguration.touchscreen, 1911 mConfiguration.densityDpi, mConfiguration.keyboard, 1912 keyboardHidden, mConfiguration.navigation, width, height, 1913 mConfiguration.smallestScreenWidthDp, 1914 mConfiguration.screenWidthDp, mConfiguration.screenHeightDp, 1915 mConfiguration.screenLayout, mConfiguration.uiMode, 1916 Build.VERSION.RESOURCES_SDK_INT); 1917 1918 if (DEBUG_CONFIG) { 1919 Slog.i(TAG, "**** Updating config of " + this + ": final config is " + mConfiguration 1920 + " final compat is " + mCompatibilityInfo); 1921 } 1922 1923 clearDrawableCachesLocked(mDrawableCache, configChanges); 1924 clearDrawableCachesLocked(mColorDrawableCache, configChanges); 1925 mColorStateListCache.onConfigurationChange(configChanges); 1926 mAnimatorCache.onConfigurationChange(configChanges); 1927 mStateListAnimatorCache.onConfigurationChange(configChanges); 1928 1929 flushLayoutCache(); 1930 } 1931 synchronized (sSync) { 1932 if (mPluralRule != null) { 1933 mPluralRule = NativePluralRules.forLocale(config.locale); 1934 } 1935 } 1936 } 1937 1938 /** 1939 * Called by ConfigurationBoundResourceCacheTest via reflection. 1940 */ 1941 private int calcConfigChanges(Configuration config) { 1942 int configChanges = 0xfffffff; 1943 if (config != null) { 1944 mTmpConfig.setTo(config); 1945 int density = config.densityDpi; 1946 if (density == Configuration.DENSITY_DPI_UNDEFINED) { 1947 density = mMetrics.noncompatDensityDpi; 1948 } 1949 1950 mCompatibilityInfo.applyToConfiguration(density, mTmpConfig); 1951 1952 if (mTmpConfig.locale == null) { 1953 mTmpConfig.locale = Locale.getDefault(); 1954 mTmpConfig.setLayoutDirection(mTmpConfig.locale); 1955 } 1956 configChanges = mConfiguration.updateFrom(mTmpConfig); 1957 configChanges = ActivityInfo.activityInfoConfigToNative(configChanges); 1958 } 1959 return configChanges; 1960 } 1961 1962 private void clearDrawableCachesLocked( 1963 ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> caches, 1964 int configChanges) { 1965 final int N = caches.size(); 1966 for (int i = 0; i < N; i++) { 1967 clearDrawableCacheLocked(caches.valueAt(i), configChanges); 1968 } 1969 } 1970 1971 private void clearDrawableCacheLocked( 1972 LongSparseArray<WeakReference<ConstantState>> cache, int configChanges) { 1973 if (DEBUG_CONFIG) { 1974 Log.d(TAG, "Cleaning up drawables config changes: 0x" 1975 + Integer.toHexString(configChanges)); 1976 } 1977 final int N = cache.size(); 1978 for (int i = 0; i < N; i++) { 1979 final WeakReference<ConstantState> ref = cache.valueAt(i); 1980 if (ref != null) { 1981 final ConstantState cs = ref.get(); 1982 if (cs != null) { 1983 if (Configuration.needNewResources( 1984 configChanges, cs.getChangingConfigurations())) { 1985 if (DEBUG_CONFIG) { 1986 Log.d(TAG, "FLUSHING #0x" 1987 + Long.toHexString(cache.keyAt(i)) 1988 + " / " + cs + " with changes: 0x" 1989 + Integer.toHexString(cs.getChangingConfigurations())); 1990 } 1991 cache.setValueAt(i, null); 1992 } else if (DEBUG_CONFIG) { 1993 Log.d(TAG, "(Keeping #0x" 1994 + Long.toHexString(cache.keyAt(i)) 1995 + " / " + cs + " with changes: 0x" 1996 + Integer.toHexString(cs.getChangingConfigurations()) 1997 + ")"); 1998 } 1999 } 2000 } 2001 } 2002 } 2003 2004 /** 2005 * {@code Locale.toLanguageTag} will transform the obsolete (and deprecated) 2006 * language codes "in", "ji" and "iw" to "id", "yi" and "he" respectively. 2007 * 2008 * All released versions of android prior to "L" used the deprecated language 2009 * tags, so we will need to support them for backwards compatibility. 2010 * 2011 * Note that this conversion needs to take place *after* the call to 2012 * {@code toLanguageTag} because that will convert all the deprecated codes to 2013 * the new ones, even if they're set manually. 2014 */ 2015 private static String adjustLanguageTag(String languageTag) { 2016 final int separator = languageTag.indexOf('-'); 2017 final String language; 2018 final String remainder; 2019 2020 if (separator == -1) { 2021 language = languageTag; 2022 remainder = ""; 2023 } else { 2024 language = languageTag.substring(0, separator); 2025 remainder = languageTag.substring(separator); 2026 } 2027 2028 return Locale.adjustLanguageCode(language) + remainder; 2029 } 2030 2031 /** 2032 * Update the system resources configuration if they have previously 2033 * been initialized. 2034 * 2035 * @hide 2036 */ 2037 public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics, 2038 CompatibilityInfo compat) { 2039 if (mSystem != null) { 2040 mSystem.updateConfiguration(config, metrics, compat); 2041 //Log.i(TAG, "Updated system resources " + mSystem 2042 // + ": " + mSystem.getConfiguration()); 2043 } 2044 } 2045 2046 /** 2047 * Return the current display metrics that are in effect for this resource 2048 * object. The returned object should be treated as read-only. 2049 * 2050 * @return The resource's current display metrics. 2051 */ 2052 public DisplayMetrics getDisplayMetrics() { 2053 if (DEBUG_CONFIG) Slog.v(TAG, "Returning DisplayMetrics: " + mMetrics.widthPixels 2054 + "x" + mMetrics.heightPixels + " " + mMetrics.density); 2055 return mMetrics; 2056 } 2057 2058 /** 2059 * Return the current configuration that is in effect for this resource 2060 * object. The returned object should be treated as read-only. 2061 * 2062 * @return The resource's current configuration. 2063 */ 2064 public Configuration getConfiguration() { 2065 return mConfiguration; 2066 } 2067 2068 /** 2069 * Return the compatibility mode information for the application. 2070 * The returned object should be treated as read-only. 2071 * 2072 * @return compatibility info. 2073 * @hide 2074 */ 2075 public CompatibilityInfo getCompatibilityInfo() { 2076 return mCompatibilityInfo; 2077 } 2078 2079 /** 2080 * This is just for testing. 2081 * @hide 2082 */ 2083 public void setCompatibilityInfo(CompatibilityInfo ci) { 2084 if (ci != null) { 2085 mCompatibilityInfo = ci; 2086 updateConfiguration(mConfiguration, mMetrics); 2087 } 2088 } 2089 2090 /** 2091 * Return a resource identifier for the given resource name. A fully 2092 * qualified resource name is of the form "package:type/entry". The first 2093 * two components (package and type) are optional if defType and 2094 * defPackage, respectively, are specified here. 2095 * 2096 * <p>Note: use of this function is discouraged. It is much more 2097 * efficient to retrieve resources by identifier than by name. 2098 * 2099 * @param name The name of the desired resource. 2100 * @param defType Optional default resource type to find, if "type/" is 2101 * not included in the name. Can be null to require an 2102 * explicit type. 2103 * @param defPackage Optional default package to find, if "package:" is 2104 * not included in the name. Can be null to require an 2105 * explicit package. 2106 * 2107 * @return int The associated resource identifier. Returns 0 if no such 2108 * resource was found. (0 is not a valid resource ID.) 2109 */ 2110 public int getIdentifier(String name, String defType, String defPackage) { 2111 if (name == null) { 2112 throw new NullPointerException("name is null"); 2113 } 2114 try { 2115 return Integer.parseInt(name); 2116 } catch (Exception e) { 2117 // Ignore 2118 } 2119 return mAssets.getResourceIdentifier(name, defType, defPackage); 2120 } 2121 2122 /** 2123 * Return true if given resource identifier includes a package. 2124 * 2125 * @hide 2126 */ 2127 public static boolean resourceHasPackage(@AnyRes int resid) { 2128 return (resid >>> 24) != 0; 2129 } 2130 2131 /** 2132 * Return the full name for a given resource identifier. This name is 2133 * a single string of the form "package:type/entry". 2134 * 2135 * @param resid The resource identifier whose name is to be retrieved. 2136 * 2137 * @return A string holding the name of the resource. 2138 * 2139 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 2140 * 2141 * @see #getResourcePackageName 2142 * @see #getResourceTypeName 2143 * @see #getResourceEntryName 2144 */ 2145 public String getResourceName(@AnyRes int resid) throws NotFoundException { 2146 String str = mAssets.getResourceName(resid); 2147 if (str != null) return str; 2148 throw new NotFoundException("Unable to find resource ID #0x" 2149 + Integer.toHexString(resid)); 2150 } 2151 2152 /** 2153 * Return the package name for a given resource identifier. 2154 * 2155 * @param resid The resource identifier whose package name is to be 2156 * retrieved. 2157 * 2158 * @return A string holding the package name of the resource. 2159 * 2160 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 2161 * 2162 * @see #getResourceName 2163 */ 2164 public String getResourcePackageName(@AnyRes int resid) throws NotFoundException { 2165 String str = mAssets.getResourcePackageName(resid); 2166 if (str != null) return str; 2167 throw new NotFoundException("Unable to find resource ID #0x" 2168 + Integer.toHexString(resid)); 2169 } 2170 2171 /** 2172 * Return the type name for a given resource identifier. 2173 * 2174 * @param resid The resource identifier whose type name is to be 2175 * retrieved. 2176 * 2177 * @return A string holding the type name of the resource. 2178 * 2179 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 2180 * 2181 * @see #getResourceName 2182 */ 2183 public String getResourceTypeName(@AnyRes int resid) throws NotFoundException { 2184 String str = mAssets.getResourceTypeName(resid); 2185 if (str != null) return str; 2186 throw new NotFoundException("Unable to find resource ID #0x" 2187 + Integer.toHexString(resid)); 2188 } 2189 2190 /** 2191 * Return the entry name for a given resource identifier. 2192 * 2193 * @param resid The resource identifier whose entry name is to be 2194 * retrieved. 2195 * 2196 * @return A string holding the entry name of the resource. 2197 * 2198 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 2199 * 2200 * @see #getResourceName 2201 */ 2202 public String getResourceEntryName(@AnyRes int resid) throws NotFoundException { 2203 String str = mAssets.getResourceEntryName(resid); 2204 if (str != null) return str; 2205 throw new NotFoundException("Unable to find resource ID #0x" 2206 + Integer.toHexString(resid)); 2207 } 2208 2209 /** 2210 * Parse a series of {@link android.R.styleable#Extra <extra>} tags from 2211 * an XML file. You call this when you are at the parent tag of the 2212 * extra tags, and it will return once all of the child tags have been parsed. 2213 * This will call {@link #parseBundleExtra} for each extra tag encountered. 2214 * 2215 * @param parser The parser from which to retrieve the extras. 2216 * @param outBundle A Bundle in which to place all parsed extras. 2217 * @throws XmlPullParserException 2218 * @throws IOException 2219 */ 2220 public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle) 2221 throws XmlPullParserException, IOException { 2222 int outerDepth = parser.getDepth(); 2223 int type; 2224 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 2225 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 2226 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 2227 continue; 2228 } 2229 2230 String nodeName = parser.getName(); 2231 if (nodeName.equals("extra")) { 2232 parseBundleExtra("extra", parser, outBundle); 2233 XmlUtils.skipCurrentTag(parser); 2234 2235 } else { 2236 XmlUtils.skipCurrentTag(parser); 2237 } 2238 } 2239 } 2240 2241 /** 2242 * Parse a name/value pair out of an XML tag holding that data. The 2243 * AttributeSet must be holding the data defined by 2244 * {@link android.R.styleable#Extra}. The following value types are supported: 2245 * <ul> 2246 * <li> {@link TypedValue#TYPE_STRING}: 2247 * {@link Bundle#putCharSequence Bundle.putCharSequence()} 2248 * <li> {@link TypedValue#TYPE_INT_BOOLEAN}: 2249 * {@link Bundle#putCharSequence Bundle.putBoolean()} 2250 * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}: 2251 * {@link Bundle#putCharSequence Bundle.putBoolean()} 2252 * <li> {@link TypedValue#TYPE_FLOAT}: 2253 * {@link Bundle#putCharSequence Bundle.putFloat()} 2254 * </ul> 2255 * 2256 * @param tagName The name of the tag these attributes come from; this is 2257 * only used for reporting error messages. 2258 * @param attrs The attributes from which to retrieve the name/value pair. 2259 * @param outBundle The Bundle in which to place the parsed value. 2260 * @throws XmlPullParserException If the attributes are not valid. 2261 */ 2262 public void parseBundleExtra(String tagName, AttributeSet attrs, 2263 Bundle outBundle) throws XmlPullParserException { 2264 TypedArray sa = obtainAttributes(attrs, 2265 com.android.internal.R.styleable.Extra); 2266 2267 String name = sa.getString( 2268 com.android.internal.R.styleable.Extra_name); 2269 if (name == null) { 2270 sa.recycle(); 2271 throw new XmlPullParserException("<" + tagName 2272 + "> requires an android:name attribute at " 2273 + attrs.getPositionDescription()); 2274 } 2275 2276 TypedValue v = sa.peekValue( 2277 com.android.internal.R.styleable.Extra_value); 2278 if (v != null) { 2279 if (v.type == TypedValue.TYPE_STRING) { 2280 CharSequence cs = v.coerceToString(); 2281 outBundle.putCharSequence(name, cs); 2282 } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) { 2283 outBundle.putBoolean(name, v.data != 0); 2284 } else if (v.type >= TypedValue.TYPE_FIRST_INT 2285 && v.type <= TypedValue.TYPE_LAST_INT) { 2286 outBundle.putInt(name, v.data); 2287 } else if (v.type == TypedValue.TYPE_FLOAT) { 2288 outBundle.putFloat(name, v.getFloat()); 2289 } else { 2290 sa.recycle(); 2291 throw new XmlPullParserException("<" + tagName 2292 + "> only supports string, integer, float, color, and boolean at " 2293 + attrs.getPositionDescription()); 2294 } 2295 } else { 2296 sa.recycle(); 2297 throw new XmlPullParserException("<" + tagName 2298 + "> requires an android:value or android:resource attribute at " 2299 + attrs.getPositionDescription()); 2300 } 2301 2302 sa.recycle(); 2303 } 2304 2305 /** 2306 * Retrieve underlying AssetManager storage for these resources. 2307 */ 2308 public final AssetManager getAssets() { 2309 return mAssets; 2310 } 2311 2312 /** 2313 * Call this to remove all cached loaded layout resources from the 2314 * Resources object. Only intended for use with performance testing 2315 * tools. 2316 */ 2317 public final void flushLayoutCache() { 2318 synchronized (mCachedXmlBlockIds) { 2319 // First see if this block is in our cache. 2320 final int num = mCachedXmlBlockIds.length; 2321 for (int i=0; i<num; i++) { 2322 mCachedXmlBlockIds[i] = -0; 2323 XmlBlock oldBlock = mCachedXmlBlocks[i]; 2324 if (oldBlock != null) { 2325 oldBlock.close(); 2326 } 2327 mCachedXmlBlocks[i] = null; 2328 } 2329 } 2330 } 2331 2332 /** 2333 * Start preloading of resource data using this Resources object. Only 2334 * for use by the zygote process for loading common system resources. 2335 * {@hide} 2336 */ 2337 public final void startPreloading() { 2338 synchronized (sSync) { 2339 if (sPreloaded) { 2340 throw new IllegalStateException("Resources already preloaded"); 2341 } 2342 sPreloaded = true; 2343 mPreloading = true; 2344 sPreloadedDensity = DisplayMetrics.DENSITY_DEVICE; 2345 mConfiguration.densityDpi = sPreloadedDensity; 2346 updateConfiguration(null, null); 2347 } 2348 } 2349 2350 /** 2351 * Called by zygote when it is done preloading resources, to change back 2352 * to normal Resources operation. 2353 */ 2354 public final void finishPreloading() { 2355 if (mPreloading) { 2356 mPreloading = false; 2357 flushLayoutCache(); 2358 } 2359 } 2360 2361 /** 2362 * @hide 2363 */ 2364 public LongSparseArray<ConstantState> getPreloadedDrawables() { 2365 return sPreloadedDrawables[0]; 2366 } 2367 2368 private boolean verifyPreloadConfig(int changingConfigurations, int allowVarying, 2369 int resourceId, String name) { 2370 // We allow preloading of resources even if they vary by font scale (which 2371 // doesn't impact resource selection) or density (which we handle specially by 2372 // simply turning off all preloading), as well as any other configs specified 2373 // by the caller. 2374 if (((changingConfigurations&~(ActivityInfo.CONFIG_FONT_SCALE | 2375 ActivityInfo.CONFIG_DENSITY)) & ~allowVarying) != 0) { 2376 String resName; 2377 try { 2378 resName = getResourceName(resourceId); 2379 } catch (NotFoundException e) { 2380 resName = "?"; 2381 } 2382 // This should never happen in production, so we should log a 2383 // warning even if we're not debugging. 2384 Log.w(TAG, "Preloaded " + name + " resource #0x" 2385 + Integer.toHexString(resourceId) 2386 + " (" + resName + ") that varies with configuration!!"); 2387 return false; 2388 } 2389 if (TRACE_FOR_PRELOAD) { 2390 String resName; 2391 try { 2392 resName = getResourceName(resourceId); 2393 } catch (NotFoundException e) { 2394 resName = "?"; 2395 } 2396 Log.w(TAG, "Preloading " + name + " resource #0x" 2397 + Integer.toHexString(resourceId) 2398 + " (" + resName + ")"); 2399 } 2400 return true; 2401 } 2402 2403 /*package*/ Drawable loadDrawable(TypedValue value, int id, Theme theme) throws NotFoundException { 2404 if (TRACE_FOR_PRELOAD) { 2405 // Log only framework resources 2406 if ((id >>> 24) == 0x1) { 2407 final String name = getResourceName(id); 2408 if (name != null) { 2409 Log.d("PreloadDrawable", name); 2410 } 2411 } 2412 } 2413 2414 final boolean isColorDrawable; 2415 final ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> caches; 2416 final long key; 2417 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT 2418 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) { 2419 isColorDrawable = true; 2420 caches = mColorDrawableCache; 2421 key = value.data; 2422 } else { 2423 isColorDrawable = false; 2424 caches = mDrawableCache; 2425 key = (((long) value.assetCookie) << 32) | value.data; 2426 } 2427 2428 // First, check whether we have a cached version of this drawable 2429 // that was inflated against the specified theme. 2430 if (!mPreloading) { 2431 final Drawable cachedDrawable = getCachedDrawable(caches, key, theme); 2432 if (cachedDrawable != null) { 2433 return cachedDrawable; 2434 } 2435 } 2436 2437 // Next, check preloaded drawables. These are unthemed but may have 2438 // themeable attributes. 2439 final ConstantState cs; 2440 if (isColorDrawable) { 2441 cs = sPreloadedColorDrawables.get(key); 2442 } else { 2443 cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key); 2444 } 2445 2446 final Drawable dr; 2447 if (cs != null) { 2448 final Drawable clonedDr = cs.newDrawable(this); 2449 if (theme != null) { 2450 dr = clonedDr.mutate(); 2451 dr.applyTheme(theme); 2452 dr.clearMutated(); 2453 } else { 2454 dr = clonedDr; 2455 } 2456 } else if (isColorDrawable) { 2457 dr = new ColorDrawable(value.data); 2458 } else { 2459 dr = loadDrawableForCookie(value, id, theme); 2460 } 2461 2462 // If we were able to obtain a drawable, store it in the appropriate 2463 // cache (either preload or themed). 2464 if (dr != null) { 2465 dr.setChangingConfigurations(value.changingConfigurations); 2466 cacheDrawable(value, theme, isColorDrawable, caches, key, dr); 2467 } 2468 2469 return dr; 2470 } 2471 2472 private void cacheDrawable(TypedValue value, Theme theme, boolean isColorDrawable, 2473 ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> caches, 2474 long key, Drawable dr) { 2475 final ConstantState cs = dr.getConstantState(); 2476 if (cs == null) { 2477 return; 2478 } 2479 2480 if (mPreloading) { 2481 // Preloaded drawables never have a theme, but may be themeable. 2482 final int changingConfigs = cs.getChangingConfigurations(); 2483 if (isColorDrawable) { 2484 if (verifyPreloadConfig(changingConfigs, 0, value.resourceId, "drawable")) { 2485 sPreloadedColorDrawables.put(key, cs); 2486 } 2487 } else { 2488 if (verifyPreloadConfig( 2489 changingConfigs, LAYOUT_DIR_CONFIG, value.resourceId, "drawable")) { 2490 if ((changingConfigs & LAYOUT_DIR_CONFIG) == 0) { 2491 // If this resource does not vary based on layout direction, 2492 // we can put it in all of the preload maps. 2493 sPreloadedDrawables[0].put(key, cs); 2494 sPreloadedDrawables[1].put(key, cs); 2495 } else { 2496 // Otherwise, only in the layout dir we loaded it for. 2497 sPreloadedDrawables[mConfiguration.getLayoutDirection()].put(key, cs); 2498 } 2499 } 2500 } 2501 } else { 2502 synchronized (mAccessLock) { 2503 final String themeKey = theme == null ? "" : theme.mKey; 2504 LongSparseArray<WeakReference<ConstantState>> themedCache = caches.get(themeKey); 2505 if (themedCache == null) { 2506 // Clean out the caches before we add more. This shouldn't 2507 // happen very often. 2508 pruneCaches(caches); 2509 themedCache = new LongSparseArray<WeakReference<ConstantState>>(1); 2510 caches.put(themeKey, themedCache); 2511 } 2512 themedCache.put(key, new WeakReference<ConstantState>(cs)); 2513 } 2514 } 2515 } 2516 2517 /** 2518 * Prunes empty caches from the cache map. 2519 * 2520 * @param caches The map of caches to prune. 2521 */ 2522 private void pruneCaches(ArrayMap<String, 2523 LongSparseArray<WeakReference<ConstantState>>> caches) { 2524 final int N = caches.size(); 2525 for (int i = N - 1; i >= 0; i--) { 2526 final LongSparseArray<WeakReference<ConstantState>> cache = caches.valueAt(i); 2527 if (pruneCache(cache)) { 2528 caches.removeAt(i); 2529 } 2530 } 2531 } 2532 2533 /** 2534 * Prunes obsolete weak references from a cache, returning {@code true} if 2535 * the cache is empty and should be removed. 2536 * 2537 * @param cache The cache of weak references to prune. 2538 * @return {@code true} if the cache is empty and should be removed. 2539 */ 2540 private boolean pruneCache(LongSparseArray<WeakReference<ConstantState>> cache) { 2541 final int N = cache.size(); 2542 for (int i = N - 1; i >= 0; i--) { 2543 final WeakReference entry = cache.valueAt(i); 2544 if (entry == null || entry.get() == null) { 2545 cache.removeAt(i); 2546 } 2547 } 2548 return cache.size() == 0; 2549 } 2550 2551 /** 2552 * Loads a drawable from XML or resources stream. 2553 */ 2554 private Drawable loadDrawableForCookie(TypedValue value, int id, Theme theme) { 2555 if (value.string == null) { 2556 throw new NotFoundException("Resource \"" + getResourceName(id) + "\" (" 2557 + Integer.toHexString(id) + ") is not a Drawable (color or path): " + value); 2558 } 2559 2560 final String file = value.string.toString(); 2561 2562 if (TRACE_FOR_MISS_PRELOAD) { 2563 // Log only framework resources 2564 if ((id >>> 24) == 0x1) { 2565 final String name = getResourceName(id); 2566 if (name != null) { 2567 Log.d(TAG, "Loading framework drawable #" + Integer.toHexString(id) 2568 + ": " + name + " at " + file); 2569 } 2570 } 2571 } 2572 2573 if (DEBUG_LOAD) { 2574 Log.v(TAG, "Loading drawable for cookie " + value.assetCookie + ": " + file); 2575 } 2576 2577 final Drawable dr; 2578 2579 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file); 2580 try { 2581 if (file.endsWith(".xml")) { 2582 final XmlResourceParser rp = loadXmlResourceParser( 2583 file, id, value.assetCookie, "drawable"); 2584 dr = Drawable.createFromXml(this, rp, theme); 2585 rp.close(); 2586 } else { 2587 final InputStream is = mAssets.openNonAsset( 2588 value.assetCookie, file, AssetManager.ACCESS_STREAMING); 2589 dr = Drawable.createFromResourceStream(this, value, is, file, null); 2590 is.close(); 2591 } 2592 } catch (Exception e) { 2593 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 2594 final NotFoundException rnf = new NotFoundException( 2595 "File " + file + " from drawable resource ID #0x" + Integer.toHexString(id)); 2596 rnf.initCause(e); 2597 throw rnf; 2598 } 2599 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 2600 2601 return dr; 2602 } 2603 2604 private Drawable getCachedDrawable( 2605 ArrayMap<String, LongSparseArray<WeakReference<ConstantState>>> caches, 2606 long key, Theme theme) { 2607 synchronized (mAccessLock) { 2608 final String themeKey = theme != null ? theme.mKey : ""; 2609 final LongSparseArray<WeakReference<ConstantState>> themedCache = caches.get(themeKey); 2610 if (themedCache != null) { 2611 final Drawable themedDrawable = getCachedDrawableLocked(themedCache, key); 2612 if (themedDrawable != null) { 2613 return themedDrawable; 2614 } 2615 } 2616 2617 // No cached drawable, we'll need to create a new one. 2618 return null; 2619 } 2620 } 2621 2622 private ConstantState getConstantStateLocked( 2623 LongSparseArray<WeakReference<ConstantState>> drawableCache, long key) { 2624 final WeakReference<ConstantState> wr = drawableCache.get(key); 2625 if (wr != null) { // we have the key 2626 final ConstantState entry = wr.get(); 2627 if (entry != null) { 2628 //Log.i(TAG, "Returning cached drawable @ #" + 2629 // Integer.toHexString(((Integer)key).intValue()) 2630 // + " in " + this + ": " + entry); 2631 return entry; 2632 } else { // our entry has been purged 2633 drawableCache.delete(key); 2634 } 2635 } 2636 return null; 2637 } 2638 2639 private Drawable getCachedDrawableLocked( 2640 LongSparseArray<WeakReference<ConstantState>> drawableCache, long key) { 2641 final ConstantState entry = getConstantStateLocked(drawableCache, key); 2642 if (entry != null) { 2643 return entry.newDrawable(this); 2644 } 2645 return null; 2646 } 2647 2648 @Nullable 2649 ColorStateList loadColorStateList(TypedValue value, int id, Theme theme) 2650 throws NotFoundException { 2651 if (TRACE_FOR_PRELOAD) { 2652 // Log only framework resources 2653 if ((id >>> 24) == 0x1) { 2654 final String name = getResourceName(id); 2655 if (name != null) android.util.Log.d("PreloadColorStateList", name); 2656 } 2657 } 2658 2659 final long key = (((long) value.assetCookie) << 32) | value.data; 2660 2661 ColorStateList csl; 2662 2663 // Handle inline color definitions. 2664 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT 2665 && value.type <= TypedValue.TYPE_LAST_COLOR_INT) { 2666 final ColorStateListFactory factory = sPreloadedColorStateLists.get(key); 2667 if (factory != null) { 2668 return factory.newInstance(); 2669 } 2670 2671 csl = ColorStateList.valueOf(value.data); 2672 2673 if (mPreloading) { 2674 if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId, 2675 "color")) { 2676 sPreloadedColorStateLists.put(key, csl.getFactory()); 2677 } 2678 } 2679 2680 return csl; 2681 } 2682 2683 final ConfigurationBoundResourceCache<ColorStateList> cache = mColorStateListCache; 2684 2685 csl = cache.get(key, theme); 2686 if (csl != null) { 2687 return csl; 2688 } 2689 2690 final ColorStateListFactory factory = sPreloadedColorStateLists.get(key); 2691 if (factory != null) { 2692 csl = factory.newInstance(this, theme); 2693 } 2694 2695 if (csl == null) { 2696 csl = loadColorStateListForCookie(value, id, theme); 2697 } 2698 2699 if (csl != null) { 2700 if (mPreloading) { 2701 if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId, 2702 "color")) { 2703 sPreloadedColorStateLists.put(key, csl.getFactory()); 2704 } 2705 } else { 2706 cache.put(key, theme, csl.getFactory()); 2707 } 2708 } 2709 2710 return csl; 2711 } 2712 2713 private ColorStateList loadColorStateListForCookie(TypedValue value, int id, Theme theme) { 2714 if (value.string == null) { 2715 throw new UnsupportedOperationException( 2716 "Can't convert to color state list: type=0x" + value.type); 2717 } 2718 2719 final String file = value.string.toString(); 2720 2721 if (TRACE_FOR_MISS_PRELOAD) { 2722 // Log only framework resources 2723 if ((id >>> 24) == 0x1) { 2724 final String name = getResourceName(id); 2725 if (name != null) { 2726 Log.d(TAG, "Loading framework color state list #" + Integer.toHexString(id) 2727 + ": " + name + " at " + file); 2728 } 2729 } 2730 } 2731 2732 if (DEBUG_LOAD) { 2733 Log.v(TAG, "Loading color state list for cookie " + value.assetCookie + ": " + file); 2734 } 2735 2736 final ColorStateList csl; 2737 2738 Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file); 2739 if (file.endsWith(".xml")) { 2740 try { 2741 final XmlResourceParser rp = loadXmlResourceParser( 2742 file, id, value.assetCookie, "colorstatelist"); 2743 csl = ColorStateList.createFromXml(this, rp, theme); 2744 rp.close(); 2745 } catch (Exception e) { 2746 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 2747 final NotFoundException rnf = new NotFoundException( 2748 "File " + file + " from color state list resource ID #0x" 2749 + Integer.toHexString(id)); 2750 rnf.initCause(e); 2751 throw rnf; 2752 } 2753 } else { 2754 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 2755 throw new NotFoundException( 2756 "File " + file + " from drawable resource ID #0x" 2757 + Integer.toHexString(id) + ": .xml extension required"); 2758 } 2759 Trace.traceEnd(Trace.TRACE_TAG_RESOURCES); 2760 2761 return csl; 2762 } 2763 2764 /*package*/ XmlResourceParser loadXmlResourceParser(int id, String type) 2765 throws NotFoundException { 2766 synchronized (mAccessLock) { 2767 TypedValue value = mTmpValue; 2768 if (value == null) { 2769 mTmpValue = value = new TypedValue(); 2770 } 2771 getValue(id, value, true); 2772 if (value.type == TypedValue.TYPE_STRING) { 2773 return loadXmlResourceParser(value.string.toString(), id, 2774 value.assetCookie, type); 2775 } 2776 throw new NotFoundException( 2777 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 2778 + Integer.toHexString(value.type) + " is not valid"); 2779 } 2780 } 2781 2782 /*package*/ XmlResourceParser loadXmlResourceParser(String file, int id, 2783 int assetCookie, String type) throws NotFoundException { 2784 if (id != 0) { 2785 try { 2786 // These may be compiled... 2787 synchronized (mCachedXmlBlockIds) { 2788 // First see if this block is in our cache. 2789 final int num = mCachedXmlBlockIds.length; 2790 for (int i=0; i<num; i++) { 2791 if (mCachedXmlBlockIds[i] == id) { 2792 //System.out.println("**** REUSING XML BLOCK! id=" 2793 // + id + ", index=" + i); 2794 return mCachedXmlBlocks[i].newParser(); 2795 } 2796 } 2797 2798 // Not in the cache, create a new block and put it at 2799 // the next slot in the cache. 2800 XmlBlock block = mAssets.openXmlBlockAsset( 2801 assetCookie, file); 2802 if (block != null) { 2803 int pos = mLastCachedXmlBlockIndex+1; 2804 if (pos >= num) pos = 0; 2805 mLastCachedXmlBlockIndex = pos; 2806 XmlBlock oldBlock = mCachedXmlBlocks[pos]; 2807 if (oldBlock != null) { 2808 oldBlock.close(); 2809 } 2810 mCachedXmlBlockIds[pos] = id; 2811 mCachedXmlBlocks[pos] = block; 2812 //System.out.println("**** CACHING NEW XML BLOCK! id=" 2813 // + id + ", index=" + pos); 2814 return block.newParser(); 2815 } 2816 } 2817 } catch (Exception e) { 2818 NotFoundException rnf = new NotFoundException( 2819 "File " + file + " from xml type " + type + " resource ID #0x" 2820 + Integer.toHexString(id)); 2821 rnf.initCause(e); 2822 throw rnf; 2823 } 2824 } 2825 2826 throw new NotFoundException( 2827 "File " + file + " from xml type " + type + " resource ID #0x" 2828 + Integer.toHexString(id)); 2829 } 2830 2831 /*package*/ void recycleCachedStyledAttributes(TypedArray attrs) { 2832 synchronized (mAccessLock) { 2833 final TypedArray cached = mCachedStyledAttributes; 2834 if (cached == null || cached.mData.length < attrs.mData.length) { 2835 mCachedStyledAttributes = attrs; 2836 } 2837 } 2838 } 2839 2840 /** 2841 * Obtains styled attributes from the theme, if available, or unstyled 2842 * resources if the theme is null. 2843 * 2844 * @hide 2845 */ 2846 public static TypedArray obtainAttributes( 2847 Resources res, Theme theme, AttributeSet set, int[] attrs) { 2848 if (theme == null) { 2849 return res.obtainAttributes(set, attrs); 2850 } 2851 return theme.obtainStyledAttributes(set, attrs, 0, 0); 2852 } 2853 2854 private Resources() { 2855 mAssets = AssetManager.getSystem(); 2856 // NOTE: Intentionally leaving this uninitialized (all values set 2857 // to zero), so that anyone who tries to do something that requires 2858 // metrics will get a very wrong value. 2859 mConfiguration.setToDefaults(); 2860 mMetrics.setToDefaults(); 2861 updateConfiguration(null, null); 2862 mAssets.ensureStringBlocks(); 2863 } 2864} 2865