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