Resources.java revision a8675f67e33bc7337d148358783b0fd138b501ff
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.content.res; 18 19 20import com.android.internal.util.XmlUtils; 21 22import org.xmlpull.v1.XmlPullParser; 23import org.xmlpull.v1.XmlPullParserException; 24 25import android.content.pm.ApplicationInfo; 26import android.graphics.Movie; 27import android.graphics.drawable.Drawable; 28import android.graphics.drawable.ColorDrawable; 29import android.os.Bundle; 30import android.os.SystemProperties; 31import android.util.AttributeSet; 32import android.util.DisplayMetrics; 33import android.util.Log; 34import android.util.SparseArray; 35import android.util.TypedValue; 36import android.util.LongSparseArray; 37import android.view.Display; 38 39import java.io.IOException; 40import java.io.InputStream; 41import java.lang.ref.WeakReference; 42 43/** 44 * Class for accessing an application's resources. This sits on top of the 45 * asset manager of the application (accessible through getAssets()) and 46 * provides a higher-level API for getting typed data from the assets. 47 */ 48public class Resources { 49 static final String TAG = "Resources"; 50 private static final boolean DEBUG_LOAD = false; 51 private static final boolean DEBUG_CONFIG = false; 52 private static final boolean TRACE_FOR_PRELOAD = false; 53 54 private static final int sSdkVersion = SystemProperties.getInt( 55 "ro.build.version.sdk", 0); 56 private static final Object mSync = new Object(); 57 private static Resources mSystem = null; 58 59 // Information about preloaded resources. Note that they are not 60 // protected by a lock, because while preloading in zygote we are all 61 // single-threaded, and after that these are immutable. 62 private static final LongSparseArray<Drawable.ConstantState> sPreloadedDrawables 63 = new LongSparseArray<Drawable.ConstantState>(); 64 private static final SparseArray<ColorStateList> mPreloadedColorStateLists 65 = new SparseArray<ColorStateList>(); 66 private static boolean mPreloaded; 67 68 private final LongSparseArray<Drawable.ConstantState> mPreloadedDrawables; 69 70 /*package*/ final TypedValue mTmpValue = new TypedValue(); 71 72 // These are protected by the mTmpValue lock. 73 private final LongSparseArray<WeakReference<Drawable.ConstantState> > mDrawableCache 74 = new LongSparseArray<WeakReference<Drawable.ConstantState> >(); 75 private final SparseArray<WeakReference<ColorStateList> > mColorStateListCache 76 = new SparseArray<WeakReference<ColorStateList> >(); 77 private boolean mPreloading; 78 79 /*package*/ TypedArray mCachedStyledAttributes = null; 80 81 private int mLastCachedXmlBlockIndex = -1; 82 private final int[] mCachedXmlBlockIds = { 0, 0, 0, 0 }; 83 private final XmlBlock[] mCachedXmlBlocks = new XmlBlock[4]; 84 85 /*package*/ final AssetManager mAssets; 86 private final Configuration mConfiguration = new Configuration(); 87 /*package*/ final DisplayMetrics mMetrics = new DisplayMetrics(); 88 PluralRules mPluralRule; 89 90 private CompatibilityInfo mCompatibilityInfo; 91 private Display mDefaultDisplay; 92 93 private static final LongSparseArray<Object> EMPTY_ARRAY = new LongSparseArray<Object>() { 94 @Override 95 public void put(long k, Object o) { 96 throw new UnsupportedOperationException(); 97 } 98 @Override 99 public void append(long k, Object o) { 100 throw new UnsupportedOperationException(); 101 } 102 }; 103 104 @SuppressWarnings("unchecked") 105 private static <T> LongSparseArray<T> emptySparseArray() { 106 return (LongSparseArray<T>) EMPTY_ARRAY; 107 } 108 109 /** 110 * This exception is thrown by the resource APIs when a requested resource 111 * can not be found. 112 */ 113 public static class NotFoundException extends RuntimeException { 114 public NotFoundException() { 115 } 116 117 public NotFoundException(String name) { 118 super(name); 119 } 120 } 121 122 /** 123 * Create a new Resources object on top of an existing set of assets in an 124 * AssetManager. 125 * 126 * @param assets Previously created AssetManager. 127 * @param metrics Current display metrics to consider when 128 * selecting/computing resource values. 129 * @param config Desired device configuration to consider when 130 * selecting/computing resource values (optional). 131 */ 132 public Resources(AssetManager assets, DisplayMetrics metrics, 133 Configuration config) { 134 this(assets, metrics, config, (CompatibilityInfo) null); 135 } 136 137 /** 138 * Creates a new Resources object with CompatibilityInfo. 139 * 140 * @param assets Previously created AssetManager. 141 * @param metrics Current display metrics to consider when 142 * selecting/computing resource values. 143 * @param config Desired device configuration to consider when 144 * selecting/computing resource values (optional). 145 * @param compInfo this resource's compatibility info. It will use the default compatibility 146 * info when it's null. 147 * @hide 148 */ 149 public Resources(AssetManager assets, DisplayMetrics metrics, 150 Configuration config, CompatibilityInfo compInfo) { 151 mAssets = assets; 152 mMetrics.setToDefaults(); 153 if (compInfo == null) { 154 mCompatibilityInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO; 155 } else { 156 mCompatibilityInfo = compInfo; 157 } 158 updateConfiguration(config, metrics); 159 assets.ensureStringBlocks(); 160 if (mCompatibilityInfo.isScalingRequired()) { 161 mPreloadedDrawables = emptySparseArray(); 162 } else { 163 mPreloadedDrawables = sPreloadedDrawables; 164 } 165 } 166 167 /** 168 * Return a global shared Resources object that provides access to only 169 * system resources (no application resources), and is not configured for 170 * the current screen (can not use dimension units, does not change based 171 * on orientation, etc). 172 */ 173 public static Resources getSystem() { 174 synchronized (mSync) { 175 Resources ret = mSystem; 176 if (ret == null) { 177 ret = new Resources(); 178 mSystem = ret; 179 } 180 181 return ret; 182 } 183 } 184 185 /** 186 * Return the string value associated with a particular resource ID. The 187 * returned object will be a String if this is a plain string; it will be 188 * some other type of CharSequence if it is styled. 189 * {@more} 190 * 191 * @param id The desired resource identifier, as generated by the aapt 192 * tool. This integer encodes the package, type, and resource 193 * entry. The value 0 is an invalid identifier. 194 * 195 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 196 * 197 * @return CharSequence The string data associated with the resource, plus 198 * possibly styled text information. 199 */ 200 public CharSequence getText(int id) throws NotFoundException { 201 CharSequence res = mAssets.getResourceText(id); 202 if (res != null) { 203 return res; 204 } 205 throw new NotFoundException("String resource ID #0x" 206 + Integer.toHexString(id)); 207 } 208 209 /** 210 * @param id The desired resource identifier, as generated by the aapt 211 * tool. This integer encodes the package, type, and resource 212 * entry. The value 0 is an invalid identifier. 213 * 214 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 215 * 216 * @return CharSequence The string data associated with the resource, plus 217 * possibly styled text information. 218 */ 219 public CharSequence getQuantityText(int id, int quantity) throws NotFoundException { 220 PluralRules rule = getPluralRule(); 221 CharSequence res = mAssets.getResourceBagText(id, rule.attrForNumber(quantity)); 222 if (res != null) { 223 return res; 224 } 225 res = mAssets.getResourceBagText(id, PluralRules.ID_OTHER); 226 if (res != null) { 227 return res; 228 } 229 throw new NotFoundException("Plural resource ID #0x" + Integer.toHexString(id) 230 + " quantity=" + quantity 231 + " item=" + PluralRules.stringForQuantity(rule.quantityForNumber(quantity))); 232 } 233 234 private PluralRules getPluralRule() { 235 synchronized (mSync) { 236 if (mPluralRule == null) { 237 mPluralRule = PluralRules.ruleForLocale(mConfiguration.locale); 238 } 239 return mPluralRule; 240 } 241 } 242 243 /** 244 * Return the string value associated with a particular resource ID. It 245 * will be stripped of any styled text information. 246 * {@more} 247 * 248 * @param id The desired resource identifier, as generated by the aapt 249 * tool. This integer encodes the package, type, and resource 250 * entry. The value 0 is an invalid identifier. 251 * 252 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 253 * 254 * @return String The string data associated with the resource, 255 * stripped of styled text information. 256 */ 257 public String getString(int id) throws NotFoundException { 258 CharSequence res = getText(id); 259 if (res != null) { 260 return res.toString(); 261 } 262 throw new NotFoundException("String resource ID #0x" 263 + Integer.toHexString(id)); 264 } 265 266 267 /** 268 * Return the string value associated with a particular resource ID, 269 * substituting the format arguments as defined in {@link java.util.Formatter} 270 * and {@link java.lang.String#format}. It will be stripped of any styled text 271 * information. 272 * {@more} 273 * 274 * @param id The desired resource identifier, as generated by the aapt 275 * tool. This integer encodes the package, type, and resource 276 * entry. The value 0 is an invalid identifier. 277 * 278 * @param formatArgs The format arguments that will be used for substitution. 279 * 280 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 281 * 282 * @return String The string data associated with the resource, 283 * stripped of styled text information. 284 */ 285 public String getString(int id, Object... formatArgs) throws NotFoundException { 286 String raw = getString(id); 287 return String.format(mConfiguration.locale, raw, formatArgs); 288 } 289 290 /** 291 * Return the string value associated with a particular resource ID for a particular 292 * numerical quantity, substituting the format arguments as defined in 293 * {@link java.util.Formatter} and {@link java.lang.String#format}. It will be 294 * stripped of any styled text information. 295 * {@more} 296 * 297 * @param id The desired resource identifier, as generated by the aapt 298 * tool. This integer encodes the package, type, and resource 299 * entry. The value 0 is an invalid identifier. 300 * @param quantity The number used to get the correct string for the current language's 301 * plural rules. 302 * @param formatArgs The format arguments that will be used for substitution. 303 * 304 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 305 * 306 * @return String The string data associated with the resource, 307 * stripped of styled text information. 308 */ 309 public String getQuantityString(int id, int quantity, Object... formatArgs) 310 throws NotFoundException { 311 String raw = getQuantityText(id, quantity).toString(); 312 return String.format(mConfiguration.locale, raw, formatArgs); 313 } 314 315 /** 316 * Return the string value associated with a particular resource ID for a particular 317 * numerical quantity. 318 * 319 * @param id The desired resource identifier, as generated by the aapt 320 * tool. This integer encodes the package, type, and resource 321 * entry. The value 0 is an invalid identifier. 322 * @param quantity The number used to get the correct string for the current language's 323 * plural rules. 324 * 325 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 326 * 327 * @return String The string data associated with the resource, 328 * stripped of styled text information. 329 */ 330 public String getQuantityString(int id, int quantity) throws NotFoundException { 331 return getQuantityText(id, quantity).toString(); 332 } 333 334 /** 335 * Return the string value associated with a particular resource ID. The 336 * returned object will be a String if this is a plain string; it will be 337 * some other type of CharSequence if it is styled. 338 * 339 * @param id The desired resource identifier, as generated by the aapt 340 * tool. This integer encodes the package, type, and resource 341 * entry. The value 0 is an invalid identifier. 342 * 343 * @param def The default CharSequence to return. 344 * 345 * @return CharSequence The string data associated with the resource, plus 346 * possibly styled text information, or def if id is 0 or not found. 347 */ 348 public CharSequence getText(int id, CharSequence def) { 349 CharSequence res = id != 0 ? mAssets.getResourceText(id) : null; 350 return res != null ? res : def; 351 } 352 353 /** 354 * Return the styled text array associated with a particular resource ID. 355 * 356 * @param id The desired resource identifier, as generated by the aapt 357 * tool. This integer encodes the package, type, and resource 358 * entry. The value 0 is an invalid identifier. 359 * 360 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 361 * 362 * @return The styled text array associated with the resource. 363 */ 364 public CharSequence[] getTextArray(int id) throws NotFoundException { 365 CharSequence[] res = mAssets.getResourceTextArray(id); 366 if (res != null) { 367 return res; 368 } 369 throw new NotFoundException("Text array resource ID #0x" 370 + Integer.toHexString(id)); 371 } 372 373 /** 374 * Return the string array associated with a particular resource ID. 375 * 376 * @param id The desired resource identifier, as generated by the aapt 377 * tool. This integer encodes the package, type, and resource 378 * entry. The value 0 is an invalid identifier. 379 * 380 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 381 * 382 * @return The string array associated with the resource. 383 */ 384 public String[] getStringArray(int id) throws NotFoundException { 385 String[] res = mAssets.getResourceStringArray(id); 386 if (res != null) { 387 return res; 388 } 389 throw new NotFoundException("String array resource ID #0x" 390 + Integer.toHexString(id)); 391 } 392 393 /** 394 * Return the int array associated with a particular resource ID. 395 * 396 * @param id The desired resource identifier, as generated by the aapt 397 * tool. This integer encodes the package, type, and resource 398 * entry. The value 0 is an invalid identifier. 399 * 400 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 401 * 402 * @return The int array associated with the resource. 403 */ 404 public int[] getIntArray(int id) throws NotFoundException { 405 int[] res = mAssets.getArrayIntResource(id); 406 if (res != null) { 407 return res; 408 } 409 throw new NotFoundException("Int array resource ID #0x" 410 + Integer.toHexString(id)); 411 } 412 413 /** 414 * Return an array of heterogeneous values. 415 * 416 * @param id The desired resource identifier, as generated by the aapt 417 * tool. This integer encodes the package, type, and resource 418 * entry. The value 0 is an invalid identifier. 419 * 420 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 421 * 422 * @return Returns a TypedArray holding an array of the array values. 423 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 424 * when done with it. 425 */ 426 public TypedArray obtainTypedArray(int id) throws NotFoundException { 427 int len = mAssets.getArraySize(id); 428 if (len < 0) { 429 throw new NotFoundException("Array resource ID #0x" 430 + Integer.toHexString(id)); 431 } 432 433 TypedArray array = getCachedStyledAttributes(len); 434 array.mLength = mAssets.retrieveArray(id, array.mData); 435 array.mIndices[0] = 0; 436 437 return array; 438 } 439 440 /** 441 * Retrieve a dimensional for a particular resource ID. Unit 442 * conversions are based on the current {@link DisplayMetrics} associated 443 * with the resources. 444 * 445 * @param id The desired resource identifier, as generated by the aapt 446 * tool. This integer encodes the package, type, and resource 447 * entry. The value 0 is an invalid identifier. 448 * 449 * @return Resource dimension value multiplied by the appropriate 450 * metric. 451 * 452 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 453 * 454 * @see #getDimensionPixelOffset 455 * @see #getDimensionPixelSize 456 */ 457 public float getDimension(int id) throws NotFoundException { 458 synchronized (mTmpValue) { 459 TypedValue value = mTmpValue; 460 getValue(id, value, true); 461 if (value.type == TypedValue.TYPE_DIMENSION) { 462 return TypedValue.complexToDimension(value.data, mMetrics); 463 } 464 throw new NotFoundException( 465 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 466 + Integer.toHexString(value.type) + " is not valid"); 467 } 468 } 469 470 /** 471 * Retrieve a dimensional for a particular resource ID for use 472 * as an offset in raw pixels. This is the same as 473 * {@link #getDimension}, except the returned value is converted to 474 * integer pixels for you. An offset conversion involves simply 475 * truncating the base value to an integer. 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 * @return Resource dimension value multiplied by the appropriate 482 * metric and truncated to integer pixels. 483 * 484 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 485 * 486 * @see #getDimension 487 * @see #getDimensionPixelSize 488 */ 489 public int getDimensionPixelOffset(int id) throws NotFoundException { 490 synchronized (mTmpValue) { 491 TypedValue value = mTmpValue; 492 getValue(id, value, true); 493 if (value.type == TypedValue.TYPE_DIMENSION) { 494 return TypedValue.complexToDimensionPixelOffset( 495 value.data, mMetrics); 496 } 497 throw new NotFoundException( 498 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 499 + Integer.toHexString(value.type) + " is not valid"); 500 } 501 } 502 503 /** 504 * Retrieve a dimensional for a particular resource ID for use 505 * as a size in raw pixels. This is the same as 506 * {@link #getDimension}, except the returned value is converted to 507 * integer pixels for use as a size. A size conversion involves 508 * rounding the base value, and ensuring that a non-zero base value 509 * is at least one pixel in size. 510 * 511 * @param id The desired resource identifier, as generated by the aapt 512 * tool. This integer encodes the package, type, and resource 513 * entry. The value 0 is an invalid identifier. 514 * 515 * @return Resource dimension value multiplied by the appropriate 516 * metric and truncated to integer pixels. 517 * 518 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 519 * 520 * @see #getDimension 521 * @see #getDimensionPixelOffset 522 */ 523 public int getDimensionPixelSize(int id) throws NotFoundException { 524 synchronized (mTmpValue) { 525 TypedValue value = mTmpValue; 526 getValue(id, value, true); 527 if (value.type == TypedValue.TYPE_DIMENSION) { 528 return TypedValue.complexToDimensionPixelSize( 529 value.data, mMetrics); 530 } 531 throw new NotFoundException( 532 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 533 + Integer.toHexString(value.type) + " is not valid"); 534 } 535 } 536 537 /** 538 * Retrieve a fractional unit for a particular resource ID. 539 * 540 * @param id The desired resource identifier, as generated by the aapt 541 * tool. This integer encodes the package, type, and resource 542 * entry. The value 0 is an invalid identifier. 543 * @param base The base value of this fraction. In other words, a 544 * standard fraction is multiplied by this value. 545 * @param pbase The parent base value of this fraction. In other 546 * words, a parent fraction (nn%p) is multiplied by this 547 * value. 548 * 549 * @return Attribute fractional value multiplied by the appropriate 550 * base value. 551 * 552 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 553 */ 554 public float getFraction(int id, int base, int pbase) { 555 synchronized (mTmpValue) { 556 TypedValue value = mTmpValue; 557 getValue(id, value, true); 558 if (value.type == TypedValue.TYPE_FRACTION) { 559 return TypedValue.complexToFraction(value.data, base, pbase); 560 } 561 throw new NotFoundException( 562 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 563 + Integer.toHexString(value.type) + " is not valid"); 564 } 565 } 566 567 /** 568 * Return a drawable object associated with a particular resource ID. 569 * Various types of objects will be returned depending on the underlying 570 * resource -- for example, a solid color, PNG image, scalable image, etc. 571 * The Drawable API hides these implementation details. 572 * 573 * @param id The desired resource identifier, as generated by the aapt 574 * tool. This integer encodes the package, type, and resource 575 * entry. The value 0 is an invalid identifier. 576 * 577 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 578 * 579 * @return Drawable An object that can be used to draw this resource. 580 */ 581 public Drawable getDrawable(int id) throws NotFoundException { 582 synchronized (mTmpValue) { 583 TypedValue value = mTmpValue; 584 getValue(id, value, true); 585 return loadDrawable(value, id); 586 } 587 } 588 589 /** 590 * Return a movie object associated with the particular resource ID. 591 * @param id The desired resource identifier, as generated by the aapt 592 * tool. This integer encodes the package, type, and resource 593 * entry. The value 0 is an invalid identifier. 594 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 595 * 596 */ 597 public Movie getMovie(int id) throws NotFoundException { 598 InputStream is = openRawResource(id); 599 Movie movie = Movie.decodeStream(is); 600 try { 601 is.close(); 602 } 603 catch (java.io.IOException e) { 604 // don't care, since the return value is valid 605 } 606 return movie; 607 } 608 609 /** 610 * Return a color integer associated with a particular resource ID. 611 * If the resource holds a complex 612 * {@link android.content.res.ColorStateList}, then the default color from 613 * the set is returned. 614 * 615 * @param id The desired resource identifier, as generated by the aapt 616 * tool. This integer encodes the package, type, and resource 617 * entry. The value 0 is an invalid identifier. 618 * 619 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 620 * 621 * @return Returns a single color value in the form 0xAARRGGBB. 622 */ 623 public int getColor(int id) throws NotFoundException { 624 synchronized (mTmpValue) { 625 TypedValue value = mTmpValue; 626 getValue(id, value, true); 627 if (value.type >= TypedValue.TYPE_FIRST_INT 628 && value.type <= TypedValue.TYPE_LAST_INT) { 629 return value.data; 630 } else if (value.type == TypedValue.TYPE_STRING) { 631 ColorStateList csl = loadColorStateList(mTmpValue, id); 632 return csl.getDefaultColor(); 633 } 634 throw new NotFoundException( 635 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 636 + Integer.toHexString(value.type) + " is not valid"); 637 } 638 } 639 640 /** 641 * Return a color state list associated with a particular resource ID. The 642 * resource may contain either a single raw color value, or a complex 643 * {@link android.content.res.ColorStateList} holding multiple possible colors. 644 * 645 * @param id The desired resource identifier of a {@link ColorStateList}, 646 * as generated by the aapt tool. This integer encodes the package, type, and resource 647 * entry. The value 0 is an invalid identifier. 648 * 649 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 650 * 651 * @return Returns a ColorStateList object containing either a single 652 * solid color or multiple colors that can be selected based on a state. 653 */ 654 public ColorStateList getColorStateList(int id) throws NotFoundException { 655 synchronized (mTmpValue) { 656 TypedValue value = mTmpValue; 657 getValue(id, value, true); 658 return loadColorStateList(value, id); 659 } 660 } 661 662 /** 663 * Return a boolean associated with a particular resource ID. This can be 664 * used with any integral resource value, and will return true if it is 665 * non-zero. 666 * 667 * @param id The desired resource identifier, as generated by the aapt 668 * tool. This integer encodes the package, type, and resource 669 * entry. The value 0 is an invalid identifier. 670 * 671 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 672 * 673 * @return Returns the boolean value contained in the resource. 674 */ 675 public boolean getBoolean(int id) throws NotFoundException { 676 synchronized (mTmpValue) { 677 TypedValue value = mTmpValue; 678 getValue(id, value, true); 679 if (value.type >= TypedValue.TYPE_FIRST_INT 680 && value.type <= TypedValue.TYPE_LAST_INT) { 681 return value.data != 0; 682 } 683 throw new NotFoundException( 684 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 685 + Integer.toHexString(value.type) + " is not valid"); 686 } 687 } 688 689 /** 690 * Return an integer 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 Returns the integer value contained in the resource. 699 */ 700 public int getInteger(int id) throws NotFoundException { 701 synchronized (mTmpValue) { 702 TypedValue value = mTmpValue; 703 getValue(id, value, true); 704 if (value.type >= TypedValue.TYPE_FIRST_INT 705 && value.type <= TypedValue.TYPE_LAST_INT) { 706 return value.data; 707 } 708 throw new NotFoundException( 709 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 710 + Integer.toHexString(value.type) + " is not valid"); 711 } 712 } 713 714 /** 715 * Return an XmlResourceParser through which you can read a view layout 716 * description for the given resource ID. This parser has limited 717 * functionality -- in particular, you can't change its input, and only 718 * the high-level events are available. 719 * 720 * <p>This function is really a simple wrapper for calling 721 * {@link #getXml} with a layout resource. 722 * 723 * @param id The desired resource identifier, as generated by the aapt 724 * tool. This integer encodes the package, type, and resource 725 * entry. The value 0 is an invalid identifier. 726 * 727 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 728 * 729 * @return A new parser object through which you can read 730 * the XML data. 731 * 732 * @see #getXml 733 */ 734 public XmlResourceParser getLayout(int id) throws NotFoundException { 735 return loadXmlResourceParser(id, "layout"); 736 } 737 738 /** 739 * Return an XmlResourceParser through which you can read an animation 740 * description for the given resource ID. This parser has limited 741 * functionality -- in particular, you can't change its input, and only 742 * the high-level events are available. 743 * 744 * <p>This function is really a simple wrapper for calling 745 * {@link #getXml} with an animation resource. 746 * 747 * @param id The desired resource identifier, as generated by the aapt 748 * tool. This integer encodes the package, type, and resource 749 * entry. The value 0 is an invalid identifier. 750 * 751 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 752 * 753 * @return A new parser object through which you can read 754 * the XML data. 755 * 756 * @see #getXml 757 */ 758 public XmlResourceParser getAnimation(int id) throws NotFoundException { 759 return loadXmlResourceParser(id, "anim"); 760 } 761 762 /** 763 * Return an XmlResourceParser through which you can read a generic XML 764 * resource for the given resource ID. 765 * 766 * <p>The XmlPullParser implementation returned here has some limited 767 * functionality. In particular, you can't change its input, and only 768 * high-level parsing events are available (since the document was 769 * pre-parsed for you at build time, which involved merging text and 770 * stripping comments). 771 * 772 * @param id The desired resource identifier, as generated by the aapt 773 * tool. This integer encodes the package, type, and resource 774 * entry. The value 0 is an invalid identifier. 775 * 776 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 777 * 778 * @return A new parser object through which you can read 779 * the XML data. 780 * 781 * @see android.util.AttributeSet 782 */ 783 public XmlResourceParser getXml(int id) throws NotFoundException { 784 return loadXmlResourceParser(id, "xml"); 785 } 786 787 /** 788 * Open a data stream for reading a raw resource. This can only be used 789 * with resources whose value is the name of an asset files -- that is, it can be 790 * used to open drawable, sound, and raw resources; it will fail on string 791 * and color resources. 792 * 793 * @param id The resource identifier to open, as generated by the appt 794 * tool. 795 * 796 * @return InputStream Access to the resource data. 797 * 798 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 799 * 800 */ 801 public InputStream openRawResource(int id) throws NotFoundException { 802 synchronized (mTmpValue) { 803 return openRawResource(id, mTmpValue); 804 } 805 } 806 807 /** 808 * Open a data stream for reading a raw resource. This can only be used 809 * with resources whose value is the name of an asset file -- that is, it can be 810 * used to open drawable, sound, and raw resources; it will fail on string 811 * and color resources. 812 * 813 * @param id The resource identifier to open, as generated by the appt tool. 814 * @param value The TypedValue object to hold the resource information. 815 * 816 * @return InputStream Access to the resource data. 817 * 818 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 819 */ 820 public InputStream openRawResource(int id, TypedValue value) throws NotFoundException { 821 getValue(id, value, true); 822 823 try { 824 return mAssets.openNonAsset(value.assetCookie, value.string.toString(), 825 AssetManager.ACCESS_STREAMING); 826 } catch (Exception e) { 827 NotFoundException rnf = new NotFoundException("File " + value.string.toString() + 828 " from drawable resource ID #0x" + Integer.toHexString(id)); 829 rnf.initCause(e); 830 throw rnf; 831 } 832 } 833 834 /** 835 * Open a file descriptor for reading a raw resource. This can only be used 836 * with resources whose value is the name of an asset files -- that is, it can be 837 * used to open drawable, sound, and raw resources; it will fail on string 838 * and color resources. 839 * 840 * <p>This function only works for resources that are stored in the package 841 * as uncompressed data, which typically includes things like mp3 files 842 * and png images. 843 * 844 * @param id The resource identifier to open, as generated by the appt 845 * tool. 846 * 847 * @return AssetFileDescriptor A new file descriptor you can use to read 848 * the resource. This includes the file descriptor itself, as well as the 849 * offset and length of data where the resource appears in the file. A 850 * null is returned if the file exists but is compressed. 851 * 852 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 853 * 854 */ 855 public AssetFileDescriptor openRawResourceFd(int id) throws NotFoundException { 856 synchronized (mTmpValue) { 857 TypedValue value = mTmpValue; 858 getValue(id, value, true); 859 860 try { 861 return mAssets.openNonAssetFd( 862 value.assetCookie, value.string.toString()); 863 } catch (Exception e) { 864 NotFoundException rnf = new NotFoundException( 865 "File " + value.string.toString() 866 + " from drawable resource ID #0x" 867 + Integer.toHexString(id)); 868 rnf.initCause(e); 869 throw rnf; 870 } 871 872 } 873 } 874 875 /** 876 * Return the raw data associated with a particular resource ID. 877 * 878 * @param id The desired resource identifier, as generated by the aapt 879 * tool. This integer encodes the package, type, and resource 880 * entry. The value 0 is an invalid identifier. 881 * @param outValue Object in which to place the resource data. 882 * @param resolveRefs If true, a resource that is a reference to another 883 * resource will be followed so that you receive the 884 * actual final resource data. If false, the TypedValue 885 * will be filled in with the reference itself. 886 * 887 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 888 * 889 */ 890 public void getValue(int id, TypedValue outValue, boolean resolveRefs) 891 throws NotFoundException { 892 boolean found = mAssets.getResourceValue(id, outValue, resolveRefs); 893 if (found) { 894 return; 895 } 896 throw new NotFoundException("Resource ID #0x" 897 + Integer.toHexString(id)); 898 } 899 900 /** 901 * Return the raw data associated with a particular resource ID. 902 * See getIdentifier() for information on how names are mapped to resource 903 * IDs, and getString(int) for information on how string resources are 904 * retrieved. 905 * 906 * <p>Note: use of this function is discouraged. It is much more 907 * efficient to retrieve resources by identifier than by name. 908 * 909 * @param name The name of the desired resource. This is passed to 910 * getIdentifier() with a default type of "string". 911 * @param outValue Object in which to place the resource data. 912 * @param resolveRefs If true, a resource that is a reference to another 913 * resource will be followed so that you receive the 914 * actual final resource data. If false, the TypedValue 915 * will be filled in with the reference itself. 916 * 917 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 918 * 919 */ 920 public void getValue(String name, TypedValue outValue, boolean resolveRefs) 921 throws NotFoundException { 922 int id = getIdentifier(name, "string", null); 923 if (id != 0) { 924 getValue(id, outValue, resolveRefs); 925 return; 926 } 927 throw new NotFoundException("String resource name " + name); 928 } 929 930 /** 931 * This class holds the current attribute values for a particular theme. 932 * In other words, a Theme is a set of values for resource attributes; 933 * these are used in conjunction with {@link TypedArray} 934 * to resolve the final value for an attribute. 935 * 936 * <p>The Theme's attributes come into play in two ways: (1) a styled 937 * attribute can explicit reference a value in the theme through the 938 * "?themeAttribute" syntax; (2) if no value has been defined for a 939 * particular styled attribute, as a last resort we will try to find that 940 * attribute's value in the Theme. 941 * 942 * <p>You will normally use the {@link #obtainStyledAttributes} APIs to 943 * retrieve XML attributes with style and theme information applied. 944 */ 945 public final class Theme { 946 /** 947 * Place new attribute values into the theme. The style resource 948 * specified by <var>resid</var> will be retrieved from this Theme's 949 * resources, its values placed into the Theme object. 950 * 951 * <p>The semantics of this function depends on the <var>force</var> 952 * argument: If false, only values that are not already defined in 953 * the theme will be copied from the system resource; otherwise, if 954 * any of the style's attributes are already defined in the theme, the 955 * current values in the theme will be overwritten. 956 * 957 * @param resid The resource ID of a style resource from which to 958 * obtain attribute values. 959 * @param force If true, values in the style resource will always be 960 * used in the theme; otherwise, they will only be used 961 * if not already defined in the theme. 962 */ 963 public void applyStyle(int resid, boolean force) { 964 AssetManager.applyThemeStyle(mTheme, resid, force); 965 } 966 967 /** 968 * Set this theme to hold the same contents as the theme 969 * <var>other</var>. If both of these themes are from the same 970 * Resources object, they will be identical after this function 971 * returns. If they are from different Resources, only the resources 972 * they have in common will be set in this theme. 973 * 974 * @param other The existing Theme to copy from. 975 */ 976 public void setTo(Theme other) { 977 AssetManager.copyTheme(mTheme, other.mTheme); 978 } 979 980 /** 981 * Return a StyledAttributes holding the values defined by 982 * <var>Theme</var> which are listed in <var>attrs</var>. 983 * 984 * <p>Be sure to call StyledAttributes.recycle() when you are done with 985 * the array. 986 * 987 * @param attrs The desired attributes. 988 * 989 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 990 * 991 * @return Returns a TypedArray holding an array of the attribute values. 992 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 993 * when done with it. 994 * 995 * @see Resources#obtainAttributes 996 * @see #obtainStyledAttributes(int, int[]) 997 * @see #obtainStyledAttributes(AttributeSet, int[], int, int) 998 */ 999 public TypedArray obtainStyledAttributes(int[] attrs) { 1000 int len = attrs.length; 1001 TypedArray array = getCachedStyledAttributes(len); 1002 array.mRsrcs = attrs; 1003 AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, 1004 array.mData, array.mIndices); 1005 return array; 1006 } 1007 1008 /** 1009 * Return a StyledAttributes holding the values defined by the style 1010 * resource <var>resid</var> which are listed in <var>attrs</var>. 1011 * 1012 * <p>Be sure to call StyledAttributes.recycle() when you are done with 1013 * the array. 1014 * 1015 * @param resid The desired style resource. 1016 * @param attrs The desired attributes in the style. 1017 * 1018 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1019 * 1020 * @return Returns a TypedArray holding an array of the attribute values. 1021 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1022 * when done with it. 1023 * 1024 * @see Resources#obtainAttributes 1025 * @see #obtainStyledAttributes(int[]) 1026 * @see #obtainStyledAttributes(AttributeSet, int[], int, int) 1027 */ 1028 public TypedArray obtainStyledAttributes(int resid, int[] attrs) 1029 throws NotFoundException { 1030 int len = attrs.length; 1031 TypedArray array = getCachedStyledAttributes(len); 1032 array.mRsrcs = attrs; 1033 1034 AssetManager.applyStyle(mTheme, 0, resid, 0, attrs, 1035 array.mData, array.mIndices); 1036 if (false) { 1037 int[] data = array.mData; 1038 1039 System.out.println("**********************************************************"); 1040 System.out.println("**********************************************************"); 1041 System.out.println("**********************************************************"); 1042 System.out.println("Attributes:"); 1043 String s = " Attrs:"; 1044 int i; 1045 for (i=0; i<attrs.length; i++) { 1046 s = s + " 0x" + Integer.toHexString(attrs[i]); 1047 } 1048 System.out.println(s); 1049 s = " Found:"; 1050 TypedValue value = new TypedValue(); 1051 for (i=0; i<attrs.length; i++) { 1052 int d = i*AssetManager.STYLE_NUM_ENTRIES; 1053 value.type = data[d+AssetManager.STYLE_TYPE]; 1054 value.data = data[d+AssetManager.STYLE_DATA]; 1055 value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE]; 1056 value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID]; 1057 s = s + " 0x" + Integer.toHexString(attrs[i]) 1058 + "=" + value; 1059 } 1060 System.out.println(s); 1061 } 1062 return array; 1063 } 1064 1065 /** 1066 * Return a StyledAttributes holding the attribute values in 1067 * <var>set</var> 1068 * that are listed in <var>attrs</var>. In addition, if the given 1069 * AttributeSet specifies a style class (through the "style" attribute), 1070 * that style will be applied on top of the base attributes it defines. 1071 * 1072 * <p>Be sure to call StyledAttributes.recycle() when you are done with 1073 * the array. 1074 * 1075 * <p>When determining the final value of a particular attribute, there 1076 * are four inputs that come into play:</p> 1077 * 1078 * <ol> 1079 * <li> Any attribute values in the given AttributeSet. 1080 * <li> The style resource specified in the AttributeSet (named 1081 * "style"). 1082 * <li> The default style specified by <var>defStyleAttr</var> and 1083 * <var>defStyleRes</var> 1084 * <li> The base values in this theme. 1085 * </ol> 1086 * 1087 * <p>Each of these inputs is considered in-order, with the first listed 1088 * taking precedence over the following ones. In other words, if in the 1089 * AttributeSet you have supplied <code><Button 1090 * textColor="#ff000000"></code>, then the button's text will 1091 * <em>always</em> be black, regardless of what is specified in any of 1092 * the styles. 1093 * 1094 * @param set The base set of attribute values. May be null. 1095 * @param attrs The desired attributes to be retrieved. 1096 * @param defStyleAttr An attribute in the current theme that contains a 1097 * reference to a style resource that supplies 1098 * defaults values for the StyledAttributes. Can be 1099 * 0 to not look for defaults. 1100 * @param defStyleRes A resource identifier of a style resource that 1101 * supplies default values for the StyledAttributes, 1102 * used only if defStyleAttr is 0 or can not be found 1103 * in the theme. Can be 0 to not look for defaults. 1104 * 1105 * @return Returns a TypedArray holding an array of the attribute values. 1106 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1107 * when done with it. 1108 * 1109 * @see Resources#obtainAttributes 1110 * @see #obtainStyledAttributes(int[]) 1111 * @see #obtainStyledAttributes(int, int[]) 1112 */ 1113 public TypedArray obtainStyledAttributes(AttributeSet set, 1114 int[] attrs, int defStyleAttr, int defStyleRes) { 1115 int len = attrs.length; 1116 TypedArray array = getCachedStyledAttributes(len); 1117 1118 // XXX note that for now we only work with compiled XML files. 1119 // To support generic XML files we will need to manually parse 1120 // out the attributes from the XML file (applying type information 1121 // contained in the resources and such). 1122 XmlBlock.Parser parser = (XmlBlock.Parser)set; 1123 AssetManager.applyStyle( 1124 mTheme, defStyleAttr, defStyleRes, 1125 parser != null ? parser.mParseState : 0, attrs, 1126 array.mData, array.mIndices); 1127 1128 array.mRsrcs = attrs; 1129 array.mXml = parser; 1130 1131 if (false) { 1132 int[] data = array.mData; 1133 1134 System.out.println("Attributes:"); 1135 String s = " Attrs:"; 1136 int i; 1137 for (i=0; i<set.getAttributeCount(); i++) { 1138 s = s + " " + set.getAttributeName(i); 1139 int id = set.getAttributeNameResource(i); 1140 if (id != 0) { 1141 s = s + "(0x" + Integer.toHexString(id) + ")"; 1142 } 1143 s = s + "=" + set.getAttributeValue(i); 1144 } 1145 System.out.println(s); 1146 s = " Found:"; 1147 TypedValue value = new TypedValue(); 1148 for (i=0; i<attrs.length; i++) { 1149 int d = i*AssetManager.STYLE_NUM_ENTRIES; 1150 value.type = data[d+AssetManager.STYLE_TYPE]; 1151 value.data = data[d+AssetManager.STYLE_DATA]; 1152 value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE]; 1153 value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID]; 1154 s = s + " 0x" + Integer.toHexString(attrs[i]) 1155 + "=" + value; 1156 } 1157 System.out.println(s); 1158 } 1159 1160 return array; 1161 } 1162 1163 /** 1164 * Retrieve the value of an attribute in the Theme. The contents of 1165 * <var>outValue</var> are ultimately filled in by 1166 * {@link Resources#getValue}. 1167 * 1168 * @param resid The resource identifier of the desired theme 1169 * attribute. 1170 * @param outValue Filled in with the ultimate resource value supplied 1171 * by the attribute. 1172 * @param resolveRefs If true, resource references will be walked; if 1173 * false, <var>outValue</var> may be a 1174 * TYPE_REFERENCE. In either case, it will never 1175 * be a TYPE_ATTRIBUTE. 1176 * 1177 * @return boolean Returns true if the attribute was found and 1178 * <var>outValue</var> is valid, else false. 1179 */ 1180 public boolean resolveAttribute(int resid, TypedValue outValue, 1181 boolean resolveRefs) { 1182 boolean got = mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs); 1183 if (false) { 1184 System.out.println( 1185 "resolveAttribute #" + Integer.toHexString(resid) 1186 + " got=" + got + ", type=0x" + Integer.toHexString(outValue.type) 1187 + ", data=0x" + Integer.toHexString(outValue.data)); 1188 } 1189 return got; 1190 } 1191 1192 /** 1193 * Print contents of this theme out to the log. For debugging only. 1194 * 1195 * @param priority The log priority to use. 1196 * @param tag The log tag to use. 1197 * @param prefix Text to prefix each line printed. 1198 */ 1199 public void dump(int priority, String tag, String prefix) { 1200 AssetManager.dumpTheme(mTheme, priority, tag, prefix); 1201 } 1202 1203 protected void finalize() throws Throwable { 1204 super.finalize(); 1205 mAssets.releaseTheme(mTheme); 1206 } 1207 1208 /*package*/ Theme() { 1209 mAssets = Resources.this.mAssets; 1210 mTheme = mAssets.createTheme(); 1211 } 1212 1213 private final AssetManager mAssets; 1214 private final int mTheme; 1215 } 1216 1217 /** 1218 * Generate a new Theme object for this set of Resources. It initially 1219 * starts out empty. 1220 * 1221 * @return Theme The newly created Theme container. 1222 */ 1223 public final Theme newTheme() { 1224 return new Theme(); 1225 } 1226 1227 /** 1228 * Retrieve a set of basic attribute values from an AttributeSet, not 1229 * performing styling of them using a theme and/or style resources. 1230 * 1231 * @param set The current attribute values to retrieve. 1232 * @param attrs The specific attributes to be retrieved. 1233 * @return Returns a TypedArray holding an array of the attribute values. 1234 * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} 1235 * when done with it. 1236 * 1237 * @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int) 1238 */ 1239 public TypedArray obtainAttributes(AttributeSet set, int[] attrs) { 1240 int len = attrs.length; 1241 TypedArray array = getCachedStyledAttributes(len); 1242 1243 // XXX note that for now we only work with compiled XML files. 1244 // To support generic XML files we will need to manually parse 1245 // out the attributes from the XML file (applying type information 1246 // contained in the resources and such). 1247 XmlBlock.Parser parser = (XmlBlock.Parser)set; 1248 mAssets.retrieveAttributes(parser.mParseState, attrs, 1249 array.mData, array.mIndices); 1250 1251 array.mRsrcs = attrs; 1252 array.mXml = parser; 1253 1254 return array; 1255 } 1256 1257 /** 1258 * Store the newly updated configuration. 1259 */ 1260 public void updateConfiguration(Configuration config, 1261 DisplayMetrics metrics) { 1262 synchronized (mTmpValue) { 1263 int configChanges = 0xfffffff; 1264 if (config != null) { 1265 configChanges = mConfiguration.updateFrom(config); 1266 } 1267 if (metrics != null) { 1268 mMetrics.setTo(metrics); 1269 mMetrics.updateMetrics(mCompatibilityInfo, 1270 mConfiguration.orientation, mConfiguration.screenLayout); 1271 } 1272 mMetrics.scaledDensity = mMetrics.density * mConfiguration.fontScale; 1273 1274 String locale = null; 1275 if (mConfiguration.locale != null) { 1276 locale = mConfiguration.locale.getLanguage(); 1277 if (mConfiguration.locale.getCountry() != null) { 1278 locale += "-" + mConfiguration.locale.getCountry(); 1279 } 1280 } 1281 int width, height; 1282 if (mMetrics.widthPixels >= mMetrics.heightPixels) { 1283 width = mMetrics.widthPixels; 1284 height = mMetrics.heightPixels; 1285 } else { 1286 //noinspection SuspiciousNameCombination 1287 width = mMetrics.heightPixels; 1288 //noinspection SuspiciousNameCombination 1289 height = mMetrics.widthPixels; 1290 } 1291 int keyboardHidden = mConfiguration.keyboardHidden; 1292 if (keyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO 1293 && mConfiguration.hardKeyboardHidden 1294 == Configuration.HARDKEYBOARDHIDDEN_YES) { 1295 keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT; 1296 } 1297 mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc, 1298 locale, mConfiguration.orientation, 1299 mConfiguration.touchscreen, 1300 (int)(mMetrics.density*160), mConfiguration.keyboard, 1301 keyboardHidden, mConfiguration.navigation, width, height, 1302 mConfiguration.screenLayout, sSdkVersion); 1303 int N = mDrawableCache.size(); 1304 if (DEBUG_CONFIG) { 1305 Log.d(TAG, "Cleaning up drawables config changes: 0x" 1306 + Integer.toHexString(configChanges)); 1307 } 1308 for (int i=0; i<N; i++) { 1309 WeakReference<Drawable.ConstantState> ref = mDrawableCache.valueAt(i); 1310 if (ref != null) { 1311 Drawable.ConstantState cs = ref.get(); 1312 if (cs != null) { 1313 if (Configuration.needNewResources( 1314 configChanges, cs.getChangingConfigurations())) { 1315 if (DEBUG_CONFIG) { 1316 Log.d(TAG, "FLUSHING #0x" 1317 + Long.toHexString(mDrawableCache.keyAt(i)) 1318 + " / " + cs + " with changes: 0x" 1319 + Integer.toHexString(cs.getChangingConfigurations())); 1320 } 1321 mDrawableCache.setValueAt(i, null); 1322 } else if (DEBUG_CONFIG) { 1323 Log.d(TAG, "(Keeping #0x" 1324 + Long.toHexString(mDrawableCache.keyAt(i)) 1325 + " / " + cs + " with changes: 0x" 1326 + Integer.toHexString(cs.getChangingConfigurations()) 1327 + ")"); 1328 } 1329 } 1330 } 1331 } 1332 mDrawableCache.clear(); 1333 mColorStateListCache.clear(); 1334 flushLayoutCache(); 1335 } 1336 synchronized (mSync) { 1337 if (mPluralRule != null) { 1338 mPluralRule = PluralRules.ruleForLocale(config.locale); 1339 } 1340 } 1341 } 1342 1343 /** 1344 * Update the system resources configuration if they have previously 1345 * been initialized. 1346 * 1347 * @hide 1348 */ 1349 public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics) { 1350 if (mSystem != null) { 1351 mSystem.updateConfiguration(config, metrics); 1352 //Log.i(TAG, "Updated system resources " + mSystem 1353 // + ": " + mSystem.getConfiguration()); 1354 } 1355 } 1356 1357 /** 1358 * Return the current display metrics that are in effect for this resource 1359 * object. The returned object should be treated as read-only. 1360 * 1361 * @return The resource's current display metrics. 1362 */ 1363 public DisplayMetrics getDisplayMetrics() { 1364 return mMetrics; 1365 } 1366 1367 /** 1368 * Return the current configuration that is in effect for this resource 1369 * object. The returned object should be treated as read-only. 1370 * 1371 * @return The resource's current configuration. 1372 */ 1373 public Configuration getConfiguration() { 1374 return mConfiguration; 1375 } 1376 1377 /** 1378 * Return the compatibility mode information for the application. 1379 * The returned object should be treated as read-only. 1380 * 1381 * @return compatibility info. null if the app does not require compatibility mode. 1382 * @hide 1383 */ 1384 public CompatibilityInfo getCompatibilityInfo() { 1385 return mCompatibilityInfo; 1386 } 1387 1388 /** 1389 * This is just for testing. 1390 * @hide 1391 */ 1392 public void setCompatibilityInfo(CompatibilityInfo ci) { 1393 mCompatibilityInfo = ci; 1394 updateConfiguration(mConfiguration, mMetrics); 1395 } 1396 1397 /** 1398 * Return a resource identifier for the given resource name. A fully 1399 * qualified resource name is of the form "package:type/entry". The first 1400 * two components (package and type) are optional if defType and 1401 * defPackage, respectively, are specified here. 1402 * 1403 * <p>Note: use of this function is discouraged. It is much more 1404 * efficient to retrieve resources by identifier than by name. 1405 * 1406 * @param name The name of the desired resource. 1407 * @param defType Optional default resource type to find, if "type/" is 1408 * not included in the name. Can be null to require an 1409 * explicit type. 1410 * @param defPackage Optional default package to find, if "package:" is 1411 * not included in the name. Can be null to require an 1412 * explicit package. 1413 * 1414 * @return int The associated resource identifier. Returns 0 if no such 1415 * resource was found. (0 is not a valid resource ID.) 1416 */ 1417 public int getIdentifier(String name, String defType, String defPackage) { 1418 try { 1419 return Integer.parseInt(name); 1420 } catch (Exception e) { 1421 // Ignore 1422 } 1423 return mAssets.getResourceIdentifier(name, defType, defPackage); 1424 } 1425 1426 /** 1427 * Return the full name for a given resource identifier. This name is 1428 * a single string of the form "package:type/entry". 1429 * 1430 * @param resid The resource identifier whose name is to be retrieved. 1431 * 1432 * @return A string holding the name of the resource. 1433 * 1434 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1435 * 1436 * @see #getResourcePackageName 1437 * @see #getResourceTypeName 1438 * @see #getResourceEntryName 1439 */ 1440 public String getResourceName(int resid) throws NotFoundException { 1441 String str = mAssets.getResourceName(resid); 1442 if (str != null) return str; 1443 throw new NotFoundException("Unable to find resource ID #0x" 1444 + Integer.toHexString(resid)); 1445 } 1446 1447 /** 1448 * Return the package name for a given resource identifier. 1449 * 1450 * @param resid The resource identifier whose package name is to be 1451 * retrieved. 1452 * 1453 * @return A string holding the package name of the resource. 1454 * 1455 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1456 * 1457 * @see #getResourceName 1458 */ 1459 public String getResourcePackageName(int resid) throws NotFoundException { 1460 String str = mAssets.getResourcePackageName(resid); 1461 if (str != null) return str; 1462 throw new NotFoundException("Unable to find resource ID #0x" 1463 + Integer.toHexString(resid)); 1464 } 1465 1466 /** 1467 * Return the type name for a given resource identifier. 1468 * 1469 * @param resid The resource identifier whose type name is to be 1470 * retrieved. 1471 * 1472 * @return A string holding the type name of the resource. 1473 * 1474 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1475 * 1476 * @see #getResourceName 1477 */ 1478 public String getResourceTypeName(int resid) throws NotFoundException { 1479 String str = mAssets.getResourceTypeName(resid); 1480 if (str != null) return str; 1481 throw new NotFoundException("Unable to find resource ID #0x" 1482 + Integer.toHexString(resid)); 1483 } 1484 1485 /** 1486 * Return the entry name for a given resource identifier. 1487 * 1488 * @param resid The resource identifier whose entry name is to be 1489 * retrieved. 1490 * 1491 * @return A string holding the entry name of the resource. 1492 * 1493 * @throws NotFoundException Throws NotFoundException if the given ID does not exist. 1494 * 1495 * @see #getResourceName 1496 */ 1497 public String getResourceEntryName(int resid) throws NotFoundException { 1498 String str = mAssets.getResourceEntryName(resid); 1499 if (str != null) return str; 1500 throw new NotFoundException("Unable to find resource ID #0x" 1501 + Integer.toHexString(resid)); 1502 } 1503 1504 /** 1505 * Parse a series of {@link android.R.styleable#Extra <extra>} tags from 1506 * an XML file. You call this when you are at the parent tag of the 1507 * extra tags, and it return once all of the child tags have been parsed. 1508 * This will call {@link #parseBundleExtra} for each extra tag encountered. 1509 * 1510 * @param parser The parser from which to retrieve the extras. 1511 * @param outBundle A Bundle in which to place all parsed extras. 1512 * @throws XmlPullParserException 1513 * @throws IOException 1514 */ 1515 public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle) 1516 throws XmlPullParserException, IOException { 1517 int outerDepth = parser.getDepth(); 1518 int type; 1519 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1520 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 1521 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 1522 continue; 1523 } 1524 1525 String nodeName = parser.getName(); 1526 if (nodeName.equals("extra")) { 1527 parseBundleExtra("extra", parser, outBundle); 1528 XmlUtils.skipCurrentTag(parser); 1529 1530 } else { 1531 XmlUtils.skipCurrentTag(parser); 1532 } 1533 } 1534 } 1535 1536 /** 1537 * Parse a name/value pair out of an XML tag holding that data. The 1538 * AttributeSet must be holding the data defined by 1539 * {@link android.R.styleable#Extra}. The following value types are supported: 1540 * <ul> 1541 * <li> {@link TypedValue#TYPE_STRING}: 1542 * {@link Bundle#putCharSequence Bundle.putCharSequence()} 1543 * <li> {@link TypedValue#TYPE_INT_BOOLEAN}: 1544 * {@link Bundle#putCharSequence Bundle.putBoolean()} 1545 * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}: 1546 * {@link Bundle#putCharSequence Bundle.putBoolean()} 1547 * <li> {@link TypedValue#TYPE_FLOAT}: 1548 * {@link Bundle#putCharSequence Bundle.putFloat()} 1549 * </ul> 1550 * 1551 * @param tagName The name of the tag these attributes come from; this is 1552 * only used for reporting error messages. 1553 * @param attrs The attributes from which to retrieve the name/value pair. 1554 * @param outBundle The Bundle in which to place the parsed value. 1555 * @throws XmlPullParserException If the attributes are not valid. 1556 */ 1557 public void parseBundleExtra(String tagName, AttributeSet attrs, 1558 Bundle outBundle) throws XmlPullParserException { 1559 TypedArray sa = obtainAttributes(attrs, 1560 com.android.internal.R.styleable.Extra); 1561 1562 String name = sa.getString( 1563 com.android.internal.R.styleable.Extra_name); 1564 if (name == null) { 1565 sa.recycle(); 1566 throw new XmlPullParserException("<" + tagName 1567 + "> requires an android:name attribute at " 1568 + attrs.getPositionDescription()); 1569 } 1570 1571 TypedValue v = sa.peekValue( 1572 com.android.internal.R.styleable.Extra_value); 1573 if (v != null) { 1574 if (v.type == TypedValue.TYPE_STRING) { 1575 CharSequence cs = v.coerceToString(); 1576 outBundle.putCharSequence(name, cs); 1577 } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) { 1578 outBundle.putBoolean(name, v.data != 0); 1579 } else if (v.type >= TypedValue.TYPE_FIRST_INT 1580 && v.type <= TypedValue.TYPE_LAST_INT) { 1581 outBundle.putInt(name, v.data); 1582 } else if (v.type == TypedValue.TYPE_FLOAT) { 1583 outBundle.putFloat(name, v.getFloat()); 1584 } else { 1585 sa.recycle(); 1586 throw new XmlPullParserException("<" + tagName 1587 + "> only supports string, integer, float, color, and boolean at " 1588 + attrs.getPositionDescription()); 1589 } 1590 } else { 1591 sa.recycle(); 1592 throw new XmlPullParserException("<" + tagName 1593 + "> requires an android:value or android:resource attribute at " 1594 + attrs.getPositionDescription()); 1595 } 1596 1597 sa.recycle(); 1598 } 1599 1600 /** 1601 * Retrieve underlying AssetManager storage for these resources. 1602 */ 1603 public final AssetManager getAssets() { 1604 return mAssets; 1605 } 1606 1607 /** 1608 * Call this to remove all cached loaded layout resources from the 1609 * Resources object. Only intended for use with performance testing 1610 * tools. 1611 */ 1612 public final void flushLayoutCache() { 1613 synchronized (mCachedXmlBlockIds) { 1614 // First see if this block is in our cache. 1615 final int num = mCachedXmlBlockIds.length; 1616 for (int i=0; i<num; i++) { 1617 mCachedXmlBlockIds[i] = -0; 1618 XmlBlock oldBlock = mCachedXmlBlocks[i]; 1619 if (oldBlock != null) { 1620 oldBlock.close(); 1621 } 1622 mCachedXmlBlocks[i] = null; 1623 } 1624 } 1625 } 1626 1627 /** 1628 * Start preloading of resource data using this Resources object. Only 1629 * for use by the zygote process for loading common system resources. 1630 * {@hide} 1631 */ 1632 public final void startPreloading() { 1633 synchronized (mSync) { 1634 if (mPreloaded) { 1635 throw new IllegalStateException("Resources already preloaded"); 1636 } 1637 mPreloaded = true; 1638 mPreloading = true; 1639 } 1640 } 1641 1642 /** 1643 * Called by zygote when it is done preloading resources, to change back 1644 * to normal Resources operation. 1645 */ 1646 public final void finishPreloading() { 1647 if (mPreloading) { 1648 mPreloading = false; 1649 flushLayoutCache(); 1650 } 1651 } 1652 1653 /*package*/ Drawable loadDrawable(TypedValue value, int id) 1654 throws NotFoundException { 1655 1656 if (TRACE_FOR_PRELOAD) { 1657 // Log only framework resources 1658 if ((id >>> 24) == 0x1) { 1659 final String name = getResourceName(id); 1660 if (name != null) android.util.Log.d("PreloadDrawable", name); 1661 } 1662 } 1663 1664 final long key = (((long) value.assetCookie) << 32) | value.data; 1665 Drawable dr = getCachedDrawable(key); 1666 1667 if (dr != null) { 1668 return dr; 1669 } 1670 1671 Drawable.ConstantState cs = mPreloadedDrawables.get(key); 1672 if (cs != null) { 1673 dr = cs.newDrawable(); 1674 } else { 1675 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT && 1676 value.type <= TypedValue.TYPE_LAST_COLOR_INT) { 1677 dr = new ColorDrawable(value.data); 1678 } 1679 1680 if (dr == null) { 1681 if (value.string == null) { 1682 throw new NotFoundException( 1683 "Resource is not a Drawable (color or path): " + value); 1684 } 1685 1686 String file = value.string.toString(); 1687 1688 if (DEBUG_LOAD) Log.v(TAG, "Loading drawable for cookie " 1689 + value.assetCookie + ": " + file); 1690 1691 if (file.endsWith(".xml")) { 1692 try { 1693 XmlResourceParser rp = loadXmlResourceParser( 1694 file, id, value.assetCookie, "drawable"); 1695 dr = Drawable.createFromXml(this, rp); 1696 rp.close(); 1697 } catch (Exception e) { 1698 NotFoundException rnf = new NotFoundException( 1699 "File " + file + " from drawable resource ID #0x" 1700 + Integer.toHexString(id)); 1701 rnf.initCause(e); 1702 throw rnf; 1703 } 1704 1705 } else { 1706 try { 1707 InputStream is = mAssets.openNonAsset( 1708 value.assetCookie, file, AssetManager.ACCESS_BUFFER); 1709 // System.out.println("Opened file " + file + ": " + is); 1710 dr = Drawable.createFromResourceStream(this, value, is, file); 1711 is.close(); 1712 // System.out.println("Created stream: " + dr); 1713 } catch (Exception e) { 1714 NotFoundException rnf = new NotFoundException( 1715 "File " + file + " from drawable resource ID #0x" 1716 + Integer.toHexString(id)); 1717 rnf.initCause(e); 1718 throw rnf; 1719 } 1720 } 1721 } 1722 } 1723 1724 if (dr != null) { 1725 dr.setChangingConfigurations(value.changingConfigurations); 1726 cs = dr.getConstantState(); 1727 if (cs != null) { 1728 if (mPreloading) { 1729 sPreloadedDrawables.put(key, cs); 1730 } else { 1731 synchronized (mTmpValue) { 1732 //Log.i(TAG, "Saving cached drawable @ #" + 1733 // Integer.toHexString(key.intValue()) 1734 // + " in " + this + ": " + cs); 1735 mDrawableCache.put(key, new WeakReference<Drawable.ConstantState>(cs)); 1736 } 1737 } 1738 } 1739 } 1740 1741 return dr; 1742 } 1743 1744 private Drawable getCachedDrawable(long key) { 1745 synchronized (mTmpValue) { 1746 WeakReference<Drawable.ConstantState> wr = mDrawableCache.get(key); 1747 if (wr != null) { // we have the key 1748 Drawable.ConstantState entry = wr.get(); 1749 if (entry != null) { 1750 //Log.i(TAG, "Returning cached drawable @ #" + 1751 // Integer.toHexString(((Integer)key).intValue()) 1752 // + " in " + this + ": " + entry); 1753 return entry.newDrawable(); 1754 } 1755 else { // our entry has been purged 1756 mDrawableCache.delete(key); 1757 } 1758 } 1759 } 1760 return null; 1761 } 1762 1763 /*package*/ ColorStateList loadColorStateList(TypedValue value, int id) 1764 throws NotFoundException { 1765 if (TRACE_FOR_PRELOAD) { 1766 // Log only framework resources 1767 if ((id >>> 24) == 0x1) { 1768 final String name = getResourceName(id); 1769 if (name != null) android.util.Log.d("PreloadColorStateList", name); 1770 } 1771 } 1772 1773 final int key = (value.assetCookie << 24) | value.data; 1774 1775 ColorStateList csl; 1776 1777 if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT && 1778 value.type <= TypedValue.TYPE_LAST_COLOR_INT) { 1779 1780 csl = mPreloadedColorStateLists.get(key); 1781 if (csl != null) { 1782 return csl; 1783 } 1784 1785 csl = ColorStateList.valueOf(value.data); 1786 if (mPreloading) { 1787 mPreloadedColorStateLists.put(key, csl); 1788 } 1789 1790 return csl; 1791 } 1792 1793 csl = getCachedColorStateList(key); 1794 if (csl != null) { 1795 return csl; 1796 } 1797 1798 csl = mPreloadedColorStateLists.get(key); 1799 if (csl != null) { 1800 return csl; 1801 } 1802 1803 if (value.string == null) { 1804 throw new NotFoundException( 1805 "Resource is not a ColorStateList (color or path): " + value); 1806 } 1807 1808 String file = value.string.toString(); 1809 1810 if (file.endsWith(".xml")) { 1811 try { 1812 XmlResourceParser rp = loadXmlResourceParser( 1813 file, id, value.assetCookie, "colorstatelist"); 1814 csl = ColorStateList.createFromXml(this, rp); 1815 rp.close(); 1816 } catch (Exception e) { 1817 NotFoundException rnf = new NotFoundException( 1818 "File " + file + " from color state list resource ID #0x" 1819 + Integer.toHexString(id)); 1820 rnf.initCause(e); 1821 throw rnf; 1822 } 1823 } else { 1824 throw new NotFoundException( 1825 "File " + file + " from drawable resource ID #0x" 1826 + Integer.toHexString(id) + ": .xml extension required"); 1827 } 1828 1829 if (csl != null) { 1830 if (mPreloading) { 1831 mPreloadedColorStateLists.put(key, csl); 1832 } else { 1833 synchronized (mTmpValue) { 1834 //Log.i(TAG, "Saving cached color state list @ #" + 1835 // Integer.toHexString(key.intValue()) 1836 // + " in " + this + ": " + csl); 1837 mColorStateListCache.put( 1838 key, new WeakReference<ColorStateList>(csl)); 1839 } 1840 } 1841 } 1842 1843 return csl; 1844 } 1845 1846 private ColorStateList getCachedColorStateList(int key) { 1847 synchronized (mTmpValue) { 1848 WeakReference<ColorStateList> wr = mColorStateListCache.get(key); 1849 if (wr != null) { // we have the key 1850 ColorStateList entry = wr.get(); 1851 if (entry != null) { 1852 //Log.i(TAG, "Returning cached color state list @ #" + 1853 // Integer.toHexString(((Integer)key).intValue()) 1854 // + " in " + this + ": " + entry); 1855 return entry; 1856 } 1857 else { // our entry has been purged 1858 mColorStateListCache.delete(key); 1859 } 1860 } 1861 } 1862 return null; 1863 } 1864 1865 /*package*/ XmlResourceParser loadXmlResourceParser(int id, String type) 1866 throws NotFoundException { 1867 synchronized (mTmpValue) { 1868 TypedValue value = mTmpValue; 1869 getValue(id, value, true); 1870 if (value.type == TypedValue.TYPE_STRING) { 1871 return loadXmlResourceParser(value.string.toString(), id, 1872 value.assetCookie, type); 1873 } 1874 throw new NotFoundException( 1875 "Resource ID #0x" + Integer.toHexString(id) + " type #0x" 1876 + Integer.toHexString(value.type) + " is not valid"); 1877 } 1878 } 1879 1880 /*package*/ XmlResourceParser loadXmlResourceParser(String file, int id, 1881 int assetCookie, String type) throws NotFoundException { 1882 if (id != 0) { 1883 try { 1884 // These may be compiled... 1885 synchronized (mCachedXmlBlockIds) { 1886 // First see if this block is in our cache. 1887 final int num = mCachedXmlBlockIds.length; 1888 for (int i=0; i<num; i++) { 1889 if (mCachedXmlBlockIds[i] == id) { 1890 //System.out.println("**** REUSING XML BLOCK! id=" 1891 // + id + ", index=" + i); 1892 return mCachedXmlBlocks[i].newParser(); 1893 } 1894 } 1895 1896 // Not in the cache, create a new block and put it at 1897 // the next slot in the cache. 1898 XmlBlock block = mAssets.openXmlBlockAsset( 1899 assetCookie, file); 1900 if (block != null) { 1901 int pos = mLastCachedXmlBlockIndex+1; 1902 if (pos >= num) pos = 0; 1903 mLastCachedXmlBlockIndex = pos; 1904 XmlBlock oldBlock = mCachedXmlBlocks[pos]; 1905 if (oldBlock != null) { 1906 oldBlock.close(); 1907 } 1908 mCachedXmlBlockIds[pos] = id; 1909 mCachedXmlBlocks[pos] = block; 1910 //System.out.println("**** CACHING NEW XML BLOCK! id=" 1911 // + id + ", index=" + pos); 1912 return block.newParser(); 1913 } 1914 } 1915 } catch (Exception e) { 1916 NotFoundException rnf = new NotFoundException( 1917 "File " + file + " from xml type " + type + " resource ID #0x" 1918 + Integer.toHexString(id)); 1919 rnf.initCause(e); 1920 throw rnf; 1921 } 1922 } 1923 1924 throw new NotFoundException( 1925 "File " + file + " from xml type " + type + " resource ID #0x" 1926 + Integer.toHexString(id)); 1927 } 1928 1929 /** 1930 * Returns the display adjusted for the Resources' metrics. 1931 * @hide 1932 */ 1933 public Display getDefaultDisplay(Display defaultDisplay) { 1934 if (mDefaultDisplay == null) { 1935 if (!mCompatibilityInfo.isScalingRequired() && mCompatibilityInfo.supportsScreen()) { 1936 // the app supports the display. just use the default one. 1937 mDefaultDisplay = defaultDisplay; 1938 } else { 1939 // display needs adjustment. 1940 mDefaultDisplay = Display.createMetricsBasedDisplay( 1941 defaultDisplay.getDisplayId(), mMetrics); 1942 } 1943 } 1944 return mDefaultDisplay; 1945 } 1946 1947 private TypedArray getCachedStyledAttributes(int len) { 1948 synchronized (mTmpValue) { 1949 TypedArray attrs = mCachedStyledAttributes; 1950 if (attrs != null) { 1951 mCachedStyledAttributes = null; 1952 1953 attrs.mLength = len; 1954 int fullLen = len * AssetManager.STYLE_NUM_ENTRIES; 1955 if (attrs.mData.length >= fullLen) { 1956 return attrs; 1957 } 1958 attrs.mData = new int[fullLen]; 1959 attrs.mIndices = new int[1+len]; 1960 return attrs; 1961 } 1962 return new TypedArray(this, 1963 new int[len*AssetManager.STYLE_NUM_ENTRIES], 1964 new int[1+len], len); 1965 } 1966 } 1967 1968 private Resources() { 1969 mAssets = AssetManager.getSystem(); 1970 // NOTE: Intentionally leaving this uninitialized (all values set 1971 // to zero), so that anyone who tries to do something that requires 1972 // metrics will get a very wrong value. 1973 mConfiguration.setToDefaults(); 1974 mMetrics.setToDefaults(); 1975 updateConfiguration(null, null); 1976 mAssets.ensureStringBlocks(); 1977 mPreloadedDrawables = sPreloadedDrawables; 1978 mCompatibilityInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO; 1979 } 1980} 1981