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