Resources.java revision 7941a7fd8e2976922172ef28106b803caa49d7d1
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            // If the drawable's XML lives in our current density qualifier,
870            // it's okay to use a scaled version from the cache. Otherwise, we
871            // need to actually load the drawable from XML.
872            final boolean useCache = value.density == mMetrics.densityDpi;
873
874            /*
875             * Pretend the requested density is actually the display density. If
876             * the drawable returned is not the requested density, then force it
877             * to be scaled later by dividing its density by the ratio of
878             * requested density to actual device density. Drawables that have
879             * undefined density or no density don't need to be handled here.
880             */
881            if (value.density > 0 && value.density != TypedValue.DENSITY_NONE) {
882                if (value.density == density) {
883                    value.density = mMetrics.densityDpi;
884                } else {
885                    value.density = (value.density * mMetrics.densityDpi) / density;
886                }
887            }
888
889            return loadDrawable(value, id, theme, useCache);
890        } finally {
891            releaseTempTypedValue(value);
892        }
893    }
894
895    /**
896     * Return a movie object associated with the particular resource ID.
897     * @param id The desired resource identifier, as generated by the aapt
898     *           tool. This integer encodes the package, type, and resource
899     *           entry. The value 0 is an invalid identifier.
900     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
901     *
902     */
903    public Movie getMovie(@RawRes int id) throws NotFoundException {
904        InputStream is = openRawResource(id);
905        Movie movie = Movie.decodeStream(is);
906        try {
907            is.close();
908        }
909        catch (java.io.IOException e) {
910            // don't care, since the return value is valid
911        }
912        return movie;
913    }
914
915    /**
916     * Returns a color integer associated with a particular resource ID. If the
917     * resource holds a complex {@link ColorStateList}, then the default color
918     * from the set is returned.
919     *
920     * @param id The desired resource identifier, as generated by the aapt
921     *           tool. This integer encodes the package, type, and resource
922     *           entry. The value 0 is an invalid identifier.
923     *
924     * @throws NotFoundException Throws NotFoundException if the given ID does
925     *         not exist.
926     *
927     * @return A single color value in the form 0xAARRGGBB.
928     * @deprecated Use {@link #getColor(int, Theme)} instead.
929     */
930    @ColorInt
931    @Deprecated
932    public int getColor(@ColorRes int id) throws NotFoundException {
933        return getColor(id, null);
934    }
935
936    /**
937     * Returns a themed color integer associated with a particular resource ID.
938     * If the resource holds a complex {@link ColorStateList}, then the default
939     * color from the set is returned.
940     *
941     * @param id The desired resource identifier, as generated by the aapt
942     *           tool. This integer encodes the package, type, and resource
943     *           entry. The value 0 is an invalid identifier.
944     * @param theme The theme used to style the color attributes, may be
945     *              {@code null}.
946     *
947     * @throws NotFoundException Throws NotFoundException if the given ID does
948     *         not exist.
949     *
950     * @return A single color value in the form 0xAARRGGBB.
951     */
952    @ColorInt
953    public int getColor(@ColorRes int id, @Nullable Theme theme) throws NotFoundException {
954        final TypedValue value = obtainTempTypedValue(id);
955        try {
956            if (value.type >= TypedValue.TYPE_FIRST_INT
957                    && value.type <= TypedValue.TYPE_LAST_INT) {
958                return value.data;
959            } else if (value.type != TypedValue.TYPE_STRING) {
960                throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
961                        + " type #0x" + Integer.toHexString(value.type) + " is not valid");
962            }
963
964            final ColorStateList csl = loadColorStateList(value, id, theme);
965            return csl.getDefaultColor();
966        } finally {
967            releaseTempTypedValue(value);
968        }
969    }
970
971    /**
972     * Returns a color state list associated with a particular resource ID. The
973     * resource may contain either a single raw color value or a complex
974     * {@link ColorStateList} holding multiple possible colors.
975     *
976     * @param id The desired resource identifier of a {@link ColorStateList},
977     *           as generated by the aapt tool. This integer encodes the
978     *           package, type, and resource entry. The value 0 is an invalid
979     *           identifier.
980     *
981     * @throws NotFoundException Throws NotFoundException if the given ID does
982     *         not exist.
983     *
984     * @return A ColorStateList object containing either a single solid color
985     *         or multiple colors that can be selected based on a state.
986     * @deprecated Use {@link #getColorStateList(int, Theme)} instead.
987     */
988    @Nullable
989    @Deprecated
990    public ColorStateList getColorStateList(@ColorRes int id) throws NotFoundException {
991        final ColorStateList csl = getColorStateList(id, null);
992        if (csl != null && csl.canApplyTheme()) {
993            Log.w(TAG, "ColorStateList " + getResourceName(id) + " has "
994                    + "unresolved theme attributes! Consider using "
995                    + "Resources.getColorStateList(int, Theme) or "
996                    + "Context.getColorStateList(int).", new RuntimeException());
997        }
998        return csl;
999    }
1000
1001    /**
1002     * Returns a themed color state list associated with a particular resource
1003     * ID. The resource may contain either a single raw color value or a
1004     * complex {@link ColorStateList} holding multiple possible colors.
1005     *
1006     * @param id The desired resource identifier of a {@link ColorStateList},
1007     *           as generated by the aapt tool. This integer encodes the
1008     *           package, type, and resource entry. The value 0 is an invalid
1009     *           identifier.
1010     * @param theme The theme used to style the color attributes, may be
1011     *              {@code null}.
1012     *
1013     * @throws NotFoundException Throws NotFoundException if the given ID does
1014     *         not exist.
1015     *
1016     * @return A themed ColorStateList object containing either a single solid
1017     *         color or multiple colors that can be selected based on a state.
1018     */
1019    @Nullable
1020    public ColorStateList getColorStateList(@ColorRes int id, @Nullable Theme theme)
1021            throws NotFoundException {
1022        final TypedValue value = obtainTempTypedValue(id);
1023        try {
1024            return loadColorStateList(value, id, theme);
1025        } finally {
1026            releaseTempTypedValue(value);
1027        }
1028    }
1029
1030    /**
1031     * Return a boolean associated with a particular resource ID.  This can be
1032     * used with any integral resource value, and will return true if it is
1033     * non-zero.
1034     *
1035     * @param id The desired resource identifier, as generated by the aapt
1036     *           tool. This integer encodes the package, type, and resource
1037     *           entry. The value 0 is an invalid identifier.
1038     *
1039     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1040     *
1041     * @return Returns the boolean value contained in the resource.
1042     */
1043    public boolean getBoolean(@BoolRes int id) throws NotFoundException {
1044        final TypedValue value = obtainTempTypedValue(id);
1045        try {
1046            if (value.type >= TypedValue.TYPE_FIRST_INT
1047                    && value.type <= TypedValue.TYPE_LAST_INT) {
1048                return value.data != 0;
1049            }
1050            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1051                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1052        } finally {
1053            releaseTempTypedValue(value);
1054        }
1055    }
1056
1057    /**
1058     * Return an integer associated with a particular resource ID.
1059     *
1060     * @param id The desired resource identifier, as generated by the aapt
1061     *           tool. This integer encodes the package, type, and resource
1062     *           entry. The value 0 is an invalid identifier.
1063     *
1064     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1065     *
1066     * @return Returns the integer value contained in the resource.
1067     */
1068    public int getInteger(@IntegerRes int id) throws NotFoundException {
1069        final TypedValue value = obtainTempTypedValue(id);
1070        try {
1071            if (value.type >= TypedValue.TYPE_FIRST_INT
1072                    && value.type <= TypedValue.TYPE_LAST_INT) {
1073                return value.data;
1074            }
1075            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1076                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1077        } finally {
1078            releaseTempTypedValue(value);
1079        }
1080    }
1081
1082    /**
1083     * Retrieve a floating-point value for a particular resource ID.
1084     *
1085     * @param id The desired resource identifier, as generated by the aapt
1086     *           tool. This integer encodes the package, type, and resource
1087     *           entry. The value 0 is an invalid identifier.
1088     *
1089     * @return Returns the floating-point value contained in the resource.
1090     *
1091     * @throws NotFoundException Throws NotFoundException if the given ID does
1092     *         not exist or is not a floating-point value.
1093     * @hide Pending API council approval.
1094     */
1095    public float getFloat(int id) {
1096        final TypedValue value = obtainTempTypedValue(id);
1097        try {
1098            if (value.type == TypedValue.TYPE_FLOAT) {
1099                return value.getFloat();
1100            }
1101            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
1102                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
1103        } finally {
1104            releaseTempTypedValue(value);
1105        }
1106    }
1107
1108    /**
1109     * Return an XmlResourceParser through which you can read a view layout
1110     * description for the given resource ID.  This parser has limited
1111     * functionality -- in particular, you can't change its input, and only
1112     * the high-level events are available.
1113     *
1114     * <p>This function is really a simple wrapper for calling
1115     * {@link #getXml} with a layout resource.
1116     *
1117     * @param id The desired resource identifier, as generated by the aapt
1118     *           tool. This integer encodes the package, type, and resource
1119     *           entry. The value 0 is an invalid identifier.
1120     *
1121     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1122     *
1123     * @return A new parser object through which you can read
1124     *         the XML data.
1125     *
1126     * @see #getXml
1127     */
1128    public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException {
1129        return loadXmlResourceParser(id, "layout");
1130    }
1131
1132    /**
1133     * Return an XmlResourceParser through which you can read an animation
1134     * description for the given resource ID.  This parser has limited
1135     * functionality -- in particular, you can't change its input, and only
1136     * the high-level events are available.
1137     *
1138     * <p>This function is really a simple wrapper for calling
1139     * {@link #getXml} with an animation resource.
1140     *
1141     * @param id The desired resource identifier, as generated by the aapt
1142     *           tool. This integer encodes the package, type, and resource
1143     *           entry. The value 0 is an invalid identifier.
1144     *
1145     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1146     *
1147     * @return A new parser object through which you can read
1148     *         the XML data.
1149     *
1150     * @see #getXml
1151     */
1152    public XmlResourceParser getAnimation(@AnimRes int id) throws NotFoundException {
1153        return loadXmlResourceParser(id, "anim");
1154    }
1155
1156    /**
1157     * Return an XmlResourceParser through which you can read a generic XML
1158     * resource for the given resource ID.
1159     *
1160     * <p>The XmlPullParser implementation returned here has some limited
1161     * functionality.  In particular, you can't change its input, and only
1162     * high-level parsing events are available (since the document was
1163     * pre-parsed for you at build time, which involved merging text and
1164     * stripping comments).
1165     *
1166     * @param id The desired resource identifier, as generated by the aapt
1167     *           tool. This integer encodes the package, type, and resource
1168     *           entry. The value 0 is an invalid identifier.
1169     *
1170     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1171     *
1172     * @return A new parser object through which you can read
1173     *         the XML data.
1174     *
1175     * @see android.util.AttributeSet
1176     */
1177    public XmlResourceParser getXml(@XmlRes int id) throws NotFoundException {
1178        return loadXmlResourceParser(id, "xml");
1179    }
1180
1181    /**
1182     * Open a data stream for reading a raw resource.  This can only be used
1183     * with resources whose value is the name of an asset files -- that is, it can be
1184     * used to open drawable, sound, and raw resources; it will fail on string
1185     * and color resources.
1186     *
1187     * @param id The resource identifier to open, as generated by the appt
1188     *           tool.
1189     *
1190     * @return InputStream Access to the resource data.
1191     *
1192     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1193     *
1194     */
1195    public InputStream openRawResource(@RawRes int id) throws NotFoundException {
1196        final TypedValue value = obtainTempTypedValue();
1197        try {
1198            return openRawResource(id, value);
1199        } finally {
1200            releaseTempTypedValue(value);
1201        }
1202    }
1203
1204    /**
1205     * Returns a TypedValue populated with data for the specified resource ID
1206     * that's suitable for temporary use. The obtained TypedValue should be
1207     * released using {@link #releaseTempTypedValue(TypedValue)}.
1208     *
1209     * @param id the resource ID for which data should be obtained
1210     * @return a populated typed value suitable for temporary use
1211     */
1212    private TypedValue obtainTempTypedValue(@AnyRes int id) {
1213        final TypedValue value = obtainTempTypedValue();
1214        getValue(id, value, true);
1215        return value;
1216    }
1217
1218    /**
1219     * Returns a TypedValue suitable for temporary use. The obtained TypedValue
1220     * should be released using {@link #releaseTempTypedValue(TypedValue)}.
1221     *
1222     * @return a typed value suitable for temporary use
1223     */
1224    private TypedValue obtainTempTypedValue() {
1225        TypedValue tmpValue = null;
1226        synchronized (mTmpValueLock) {
1227            if (mTmpValue != null) {
1228                tmpValue = mTmpValue;
1229                mTmpValue = null;
1230            }
1231        }
1232        if (tmpValue == null) {
1233            return new TypedValue();
1234        }
1235        return tmpValue;
1236    }
1237
1238    /**
1239     * Returns a TypedValue to the pool. After calling this method, the
1240     * specified TypedValue should no longer be accessed.
1241     *
1242     * @param value the typed value to return to the pool
1243     */
1244    private void releaseTempTypedValue(TypedValue value) {
1245        synchronized (mTmpValueLock) {
1246            if (mTmpValue == null) {
1247                mTmpValue = value;
1248            }
1249        }
1250    }
1251
1252    /**
1253     * Open a data stream for reading a raw resource.  This can only be used
1254     * with resources whose value is the name of an asset file -- that is, it can be
1255     * used to open drawable, sound, and raw resources; it will fail on string
1256     * and color resources.
1257     *
1258     * @param id The resource identifier to open, as generated by the appt tool.
1259     * @param value The TypedValue object to hold the resource information.
1260     *
1261     * @return InputStream Access to the resource data.
1262     *
1263     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1264     */
1265    public InputStream openRawResource(@RawRes int id, TypedValue value)
1266            throws NotFoundException {
1267        getValue(id, value, true);
1268
1269        try {
1270            return mAssets.openNonAsset(value.assetCookie, value.string.toString(),
1271                    AssetManager.ACCESS_STREAMING);
1272        } catch (Exception e) {
1273            NotFoundException rnf = new NotFoundException("File " + value.string.toString() +
1274                    " from drawable resource ID #0x" + Integer.toHexString(id));
1275            rnf.initCause(e);
1276            throw rnf;
1277        }
1278    }
1279
1280    /**
1281     * Open a file descriptor for reading a raw resource.  This can only be used
1282     * with resources whose value is the name of an asset files -- that is, it can be
1283     * used to open drawable, sound, and raw resources; it will fail on string
1284     * and color resources.
1285     *
1286     * <p>This function only works for resources that are stored in the package
1287     * as uncompressed data, which typically includes things like mp3 files
1288     * and png images.
1289     *
1290     * @param id The resource identifier to open, as generated by the appt
1291     *           tool.
1292     *
1293     * @return AssetFileDescriptor A new file descriptor you can use to read
1294     * the resource.  This includes the file descriptor itself, as well as the
1295     * offset and length of data where the resource appears in the file.  A
1296     * null is returned if the file exists but is compressed.
1297     *
1298     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1299     *
1300     */
1301    public AssetFileDescriptor openRawResourceFd(@RawRes int id)
1302            throws NotFoundException {
1303        final TypedValue value = obtainTempTypedValue(id);
1304        try {
1305            return mAssets.openNonAssetFd(value.assetCookie, value.string.toString());
1306        } catch (Exception e) {
1307            throw new NotFoundException("File " + value.string.toString() + " from drawable "
1308                    + "resource ID #0x" + Integer.toHexString(id), e);
1309        } finally {
1310            releaseTempTypedValue(value);
1311        }
1312    }
1313
1314    /**
1315     * Return the raw data associated with a particular resource ID.
1316     *
1317     * @param id The desired resource identifier, as generated by the aapt
1318     *           tool. This integer encodes the package, type, and resource
1319     *           entry. The value 0 is an invalid identifier.
1320     * @param outValue Object in which to place the resource data.
1321     * @param resolveRefs If true, a resource that is a reference to another
1322     *                    resource will be followed so that you receive the
1323     *                    actual final resource data.  If false, the TypedValue
1324     *                    will be filled in with the reference itself.
1325     *
1326     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1327     *
1328     */
1329    public void getValue(@AnyRes int id, TypedValue outValue, boolean resolveRefs)
1330            throws NotFoundException {
1331        boolean found = mAssets.getResourceValue(id, 0, outValue, resolveRefs);
1332        if (found) {
1333            return;
1334        }
1335        throw new NotFoundException("Resource ID #0x"
1336                                    + Integer.toHexString(id));
1337    }
1338
1339    /**
1340     * Get the raw value associated with a resource with associated density.
1341     *
1342     * @param id resource identifier
1343     * @param density density in DPI
1344     * @param resolveRefs If true, a resource that is a reference to another
1345     *            resource will be followed so that you receive the actual final
1346     *            resource data. If false, the TypedValue will be filled in with
1347     *            the reference itself.
1348     * @throws NotFoundException Throws NotFoundException if the given ID does
1349     *             not exist.
1350     * @see #getValue(String, TypedValue, boolean)
1351     */
1352    public void getValueForDensity(@AnyRes int id, int density, TypedValue outValue,
1353            boolean resolveRefs) throws NotFoundException {
1354        boolean found = mAssets.getResourceValue(id, density, outValue, resolveRefs);
1355        if (found) {
1356            return;
1357        }
1358        throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id));
1359    }
1360
1361    /**
1362     * Return the raw data associated with a particular resource ID.
1363     * See getIdentifier() for information on how names are mapped to resource
1364     * IDs, and getString(int) for information on how string resources are
1365     * retrieved.
1366     *
1367     * <p>Note: use of this function is discouraged.  It is much more
1368     * efficient to retrieve resources by identifier than by name.
1369     *
1370     * @param name The name of the desired resource.  This is passed to
1371     *             getIdentifier() with a default type of "string".
1372     * @param outValue Object in which to place the resource data.
1373     * @param resolveRefs If true, a resource that is a reference to another
1374     *                    resource will be followed so that you receive the
1375     *                    actual final resource data.  If false, the TypedValue
1376     *                    will be filled in with the reference itself.
1377     *
1378     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1379     *
1380     */
1381    public void getValue(String name, TypedValue outValue, boolean resolveRefs)
1382            throws NotFoundException {
1383        int id = getIdentifier(name, "string", null);
1384        if (id != 0) {
1385            getValue(id, outValue, resolveRefs);
1386            return;
1387        }
1388        throw new NotFoundException("String resource name " + name);
1389    }
1390
1391    /**
1392     * This class holds the current attribute values for a particular theme.
1393     * In other words, a Theme is a set of values for resource attributes;
1394     * these are used in conjunction with {@link TypedArray}
1395     * to resolve the final value for an attribute.
1396     *
1397     * <p>The Theme's attributes come into play in two ways: (1) a styled
1398     * attribute can explicit reference a value in the theme through the
1399     * "?themeAttribute" syntax; (2) if no value has been defined for a
1400     * particular styled attribute, as a last resort we will try to find that
1401     * attribute's value in the Theme.
1402     *
1403     * <p>You will normally use the {@link #obtainStyledAttributes} APIs to
1404     * retrieve XML attributes with style and theme information applied.
1405     */
1406    public final class Theme {
1407        /**
1408         * Place new attribute values into the theme.  The style resource
1409         * specified by <var>resid</var> will be retrieved from this Theme's
1410         * resources, its values placed into the Theme object.
1411         *
1412         * <p>The semantics of this function depends on the <var>force</var>
1413         * argument:  If false, only values that are not already defined in
1414         * the theme will be copied from the system resource; otherwise, if
1415         * any of the style's attributes are already defined in the theme, the
1416         * current values in the theme will be overwritten.
1417         *
1418         * @param resId The resource ID of a style resource from which to
1419         *              obtain attribute values.
1420         * @param force If true, values in the style resource will always be
1421         *              used in the theme; otherwise, they will only be used
1422         *              if not already defined in the theme.
1423         */
1424        public void applyStyle(int resId, boolean force) {
1425            synchronized (mKey) {
1426                AssetManager.applyThemeStyle(mTheme, resId, force);
1427
1428                mThemeResId = resId;
1429                mKey.append(resId, force);
1430            }
1431        }
1432
1433        /**
1434         * Set this theme to hold the same contents as the theme
1435         * <var>other</var>.  If both of these themes are from the same
1436         * Resources object, they will be identical after this function
1437         * returns.  If they are from different Resources, only the resources
1438         * they have in common will be set in this theme.
1439         *
1440         * @param other The existing Theme to copy from.
1441         */
1442        public void setTo(Theme other) {
1443            synchronized (mKey) {
1444                synchronized (other.mKey) {
1445                    AssetManager.copyTheme(mTheme, other.mTheme);
1446
1447                    mThemeResId = other.mThemeResId;
1448                    mKey.setTo(other.getKey());
1449                }
1450            }
1451        }
1452
1453        /**
1454         * Return a TypedArray holding the values defined by
1455         * <var>Theme</var> which are listed in <var>attrs</var>.
1456         *
1457         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1458         * with the array.
1459         *
1460         * @param attrs The desired attributes.
1461         *
1462         * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1463         *
1464         * @return Returns a TypedArray holding an array of the attribute values.
1465         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1466         * when done with it.
1467         *
1468         * @see Resources#obtainAttributes
1469         * @see #obtainStyledAttributes(int, int[])
1470         * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1471         */
1472        public TypedArray obtainStyledAttributes(@StyleableRes int[] attrs) {
1473            synchronized (mKey) {
1474                final int len = attrs.length;
1475                final TypedArray array = TypedArray.obtain(Resources.this, len);
1476                array.mTheme = this;
1477                AssetManager.applyStyle(mTheme, 0, 0, 0, attrs, array.mData, array.mIndices);
1478                return array;
1479            }
1480        }
1481
1482        /**
1483         * Return a TypedArray holding the values defined by the style
1484         * resource <var>resid</var> which are listed in <var>attrs</var>.
1485         *
1486         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1487         * with the array.
1488         *
1489         * @param resId The desired style resource.
1490         * @param attrs The desired attributes in the style.
1491         *
1492         * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
1493         *
1494         * @return Returns a TypedArray holding an array of the attribute values.
1495         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1496         * when done with it.
1497         *
1498         * @see Resources#obtainAttributes
1499         * @see #obtainStyledAttributes(int[])
1500         * @see #obtainStyledAttributes(AttributeSet, int[], int, int)
1501         */
1502        public TypedArray obtainStyledAttributes(@StyleRes int resId, @StyleableRes int[] attrs)
1503                throws NotFoundException {
1504            synchronized (mKey) {
1505                final int len = attrs.length;
1506                final TypedArray array = TypedArray.obtain(Resources.this, len);
1507                array.mTheme = this;
1508                AssetManager.applyStyle(mTheme, 0, resId, 0, attrs, array.mData, array.mIndices);
1509                return array;
1510            }
1511        }
1512
1513        /**
1514         * Return a TypedArray holding the attribute values in
1515         * <var>set</var>
1516         * that are listed in <var>attrs</var>.  In addition, if the given
1517         * AttributeSet specifies a style class (through the "style" attribute),
1518         * that style will be applied on top of the base attributes it defines.
1519         *
1520         * <p>Be sure to call {@link TypedArray#recycle() TypedArray.recycle()} when you are done
1521         * with the array.
1522         *
1523         * <p>When determining the final value of a particular attribute, there
1524         * are four inputs that come into play:</p>
1525         *
1526         * <ol>
1527         *     <li> Any attribute values in the given AttributeSet.
1528         *     <li> The style resource specified in the AttributeSet (named
1529         *     "style").
1530         *     <li> The default style specified by <var>defStyleAttr</var> and
1531         *     <var>defStyleRes</var>
1532         *     <li> The base values in this theme.
1533         * </ol>
1534         *
1535         * <p>Each of these inputs is considered in-order, with the first listed
1536         * taking precedence over the following ones.  In other words, if in the
1537         * AttributeSet you have supplied <code>&lt;Button
1538         * textColor="#ff000000"&gt;</code>, then the button's text will
1539         * <em>always</em> be black, regardless of what is specified in any of
1540         * the styles.
1541         *
1542         * @param set The base set of attribute values.  May be null.
1543         * @param attrs The desired attributes to be retrieved.
1544         * @param defStyleAttr An attribute in the current theme that contains a
1545         *                     reference to a style resource that supplies
1546         *                     defaults values for the TypedArray.  Can be
1547         *                     0 to not look for defaults.
1548         * @param defStyleRes A resource identifier of a style resource that
1549         *                    supplies default values for the TypedArray,
1550         *                    used only if defStyleAttr is 0 or can not be found
1551         *                    in the theme.  Can be 0 to not look for defaults.
1552         *
1553         * @return Returns a TypedArray holding an array of the attribute values.
1554         * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1555         * when done with it.
1556         *
1557         * @see Resources#obtainAttributes
1558         * @see #obtainStyledAttributes(int[])
1559         * @see #obtainStyledAttributes(int, int[])
1560         */
1561        public TypedArray obtainStyledAttributes(AttributeSet set,
1562                @StyleableRes int[] attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
1563            synchronized (mKey) {
1564                final int len = attrs.length;
1565                final TypedArray array = TypedArray.obtain(Resources.this, len);
1566
1567                // XXX note that for now we only work with compiled XML files.
1568                // To support generic XML files we will need to manually parse
1569                // out the attributes from the XML file (applying type information
1570                // contained in the resources and such).
1571                final XmlBlock.Parser parser = (XmlBlock.Parser) set;
1572                AssetManager.applyStyle(mTheme, defStyleAttr, defStyleRes,
1573                        parser != null ? parser.mParseState : 0,
1574                        attrs, array.mData, array.mIndices);
1575                array.mTheme = this;
1576                array.mXml = parser;
1577
1578                return array;
1579            }
1580        }
1581
1582        /**
1583         * Retrieve the values for a set of attributes in the Theme. The
1584         * contents of the typed array are ultimately filled in by
1585         * {@link Resources#getValue}.
1586         *
1587         * @param values The base set of attribute values, must be equal in
1588         *               length to {@code attrs}. All values must be of type
1589         *               {@link TypedValue#TYPE_ATTRIBUTE}.
1590         * @param attrs The desired attributes to be retrieved.
1591         * @return Returns a TypedArray holding an array of the attribute
1592         *         values. Be sure to call {@link TypedArray#recycle()}
1593         *         when done with it.
1594         * @hide
1595         */
1596        @NonNull
1597        public TypedArray resolveAttributes(@NonNull int[] values, @NonNull int[] attrs) {
1598            synchronized (mKey) {
1599                final int len = attrs.length;
1600                if (values == null || len != values.length) {
1601                    throw new IllegalArgumentException(
1602                            "Base attribute values must the same length as attrs");
1603                }
1604
1605                final TypedArray array = TypedArray.obtain(Resources.this, len);
1606                AssetManager.resolveAttrs(mTheme, 0, 0, values, attrs, array.mData, array.mIndices);
1607                array.mTheme = this;
1608                array.mXml = null;
1609
1610                return array;
1611            }
1612        }
1613
1614        /**
1615         * Retrieve the value of an attribute in the Theme.  The contents of
1616         * <var>outValue</var> are ultimately filled in by
1617         * {@link Resources#getValue}.
1618         *
1619         * @param resid The resource identifier of the desired theme
1620         *              attribute.
1621         * @param outValue Filled in with the ultimate resource value supplied
1622         *                 by the attribute.
1623         * @param resolveRefs If true, resource references will be walked; if
1624         *                    false, <var>outValue</var> may be a
1625         *                    TYPE_REFERENCE.  In either case, it will never
1626         *                    be a TYPE_ATTRIBUTE.
1627         *
1628         * @return boolean Returns true if the attribute was found and
1629         *         <var>outValue</var> is valid, else false.
1630         */
1631        public boolean resolveAttribute(int resid, TypedValue outValue, boolean resolveRefs) {
1632            synchronized (mKey) {
1633                return mAssets.getThemeValue(mTheme, resid, outValue, resolveRefs);
1634            }
1635        }
1636
1637        /**
1638         * Gets all of the attribute ids associated with this {@link Theme}. For debugging only.
1639         *
1640         * @return The int array containing attribute ids associated with this {@link Theme}.
1641         * @hide
1642         */
1643        public int[] getAllAttributes() {
1644            return mAssets.getStyleAttributes(getAppliedStyleResId());
1645        }
1646
1647        /**
1648         * Returns the resources to which this theme belongs.
1649         *
1650         * @return Resources to which this theme belongs.
1651         */
1652        public Resources getResources() {
1653            return Resources.this;
1654        }
1655
1656        /**
1657         * Return a drawable object associated with a particular resource ID
1658         * and styled for the Theme.
1659         *
1660         * @param id The desired resource identifier, as generated by the aapt
1661         *           tool. This integer encodes the package, type, and resource
1662         *           entry. The value 0 is an invalid identifier.
1663         * @return Drawable An object that can be used to draw this resource.
1664         * @throws NotFoundException Throws NotFoundException if the given ID
1665         *         does not exist.
1666         */
1667        public Drawable getDrawable(@DrawableRes int id) throws NotFoundException {
1668            return Resources.this.getDrawable(id, this);
1669        }
1670
1671        /**
1672         * Returns a bit mask of configuration changes that will impact this
1673         * theme (and thus require completely reloading it).
1674         *
1675         * @return a bit mask of configuration changes, as defined by
1676         *         {@link ActivityInfo}
1677         * @see ActivityInfo
1678         */
1679        public int getChangingConfigurations() {
1680            synchronized (mKey) {
1681                final int nativeChangingConfig =
1682                        AssetManager.getThemeChangingConfigurations(mTheme);
1683                return ActivityInfo.activityInfoConfigNativeToJava(nativeChangingConfig);
1684            }
1685        }
1686
1687        /**
1688         * Print contents of this theme out to the log.  For debugging only.
1689         *
1690         * @param priority The log priority to use.
1691         * @param tag The log tag to use.
1692         * @param prefix Text to prefix each line printed.
1693         */
1694        public void dump(int priority, String tag, String prefix) {
1695            synchronized (mKey) {
1696                AssetManager.dumpTheme(mTheme, priority, tag, prefix);
1697            }
1698        }
1699
1700        @Override
1701        protected void finalize() throws Throwable {
1702            super.finalize();
1703            mAssets.releaseTheme(mTheme);
1704        }
1705
1706        /*package*/ Theme() {
1707            mAssets = Resources.this.mAssets;
1708            mTheme = mAssets.createTheme();
1709        }
1710
1711        /** Unique key for the series of styles applied to this theme. */
1712        private final ThemeKey mKey = new ThemeKey();
1713
1714        @SuppressWarnings("hiding")
1715        private final AssetManager mAssets;
1716        private final long mTheme;
1717
1718        /** Resource identifier for the theme. */
1719        private int mThemeResId = 0;
1720
1721        // Needed by layoutlib.
1722        /*package*/ long getNativeTheme() {
1723            return mTheme;
1724        }
1725
1726        /*package*/ int getAppliedStyleResId() {
1727            return mThemeResId;
1728        }
1729
1730        /*package*/ ThemeKey getKey() {
1731            return mKey;
1732        }
1733
1734        private String getResourceNameFromHexString(String hexString) {
1735            return getResourceName(Integer.parseInt(hexString, 16));
1736        }
1737
1738        /**
1739         * Parses {@link #mKey} and returns a String array that holds pairs of
1740         * adjacent Theme data: resource name followed by whether or not it was
1741         * forced, as specified by {@link #applyStyle(int, boolean)}.
1742         *
1743         * @hide
1744         */
1745        @ViewDebug.ExportedProperty(category = "theme", hasAdjacentMapping = true)
1746        public String[] getTheme() {
1747            synchronized (mKey) {
1748                final int N = mKey.mCount;
1749                final String[] themes = new String[N * 2];
1750                for (int i = 0, j = N - 1; i < themes.length; i += 2, --j) {
1751                    final int resId = mKey.mResId[j];
1752                    final boolean forced = mKey.mForce[j];
1753                    try {
1754                        themes[i] = getResourceName(resId);
1755                    } catch (NotFoundException e) {
1756                        themes[i] = Integer.toHexString(i);
1757                    }
1758                    themes[i + 1] = forced ? "forced" : "not forced";
1759                }
1760                return themes;
1761            }
1762        }
1763
1764        /** @hide */
1765        public void encode(@NonNull ViewHierarchyEncoder encoder) {
1766            encoder.beginObject(this);
1767            final String[] properties = getTheme();
1768            for (int i = 0; i < properties.length; i += 2) {
1769                encoder.addProperty(properties[i], properties[i+1]);
1770            }
1771            encoder.endObject();
1772        }
1773
1774        /**
1775         * Rebases the theme against the parent Resource object's current
1776         * configuration by re-applying the styles passed to
1777         * {@link #applyStyle(int, boolean)}.
1778         *
1779         * @hide
1780         */
1781        public void rebase() {
1782            synchronized (mKey) {
1783                AssetManager.clearTheme(mTheme);
1784
1785                // Reapply the same styles in the same order.
1786                for (int i = 0; i < mKey.mCount; i++) {
1787                    final int resId = mKey.mResId[i];
1788                    final boolean force = mKey.mForce[i];
1789                    AssetManager.applyThemeStyle(mTheme, resId, force);
1790                }
1791            }
1792        }
1793    }
1794
1795    static class ThemeKey implements Cloneable {
1796        int[] mResId;
1797        boolean[] mForce;
1798        int mCount;
1799
1800        private int mHashCode = 0;
1801
1802        public void append(int resId, boolean force) {
1803            if (mResId == null) {
1804                mResId = new int[4];
1805            }
1806
1807            if (mForce == null) {
1808                mForce = new boolean[4];
1809            }
1810
1811            mResId = GrowingArrayUtils.append(mResId, mCount, resId);
1812            mForce = GrowingArrayUtils.append(mForce, mCount, force);
1813            mCount++;
1814
1815            mHashCode = 31 * (31 * mHashCode + resId) + (force ? 1 : 0);
1816        }
1817
1818        /**
1819         * Sets up this key as a deep copy of another key.
1820         *
1821         * @param other the key to deep copy into this key
1822         */
1823        public void setTo(ThemeKey other) {
1824            mResId = other.mResId == null ? null : other.mResId.clone();
1825            mForce = other.mForce == null ? null : other.mForce.clone();
1826            mCount = other.mCount;
1827        }
1828
1829        @Override
1830        public int hashCode() {
1831            return mHashCode;
1832        }
1833
1834        @Override
1835        public boolean equals(Object o) {
1836            if (this == o) {
1837                return true;
1838            }
1839
1840            if (o == null || getClass() != o.getClass() || hashCode() != o.hashCode()) {
1841                return false;
1842            }
1843
1844            final ThemeKey t = (ThemeKey) o;
1845            if (mCount != t.mCount) {
1846                return false;
1847            }
1848
1849            final int N = mCount;
1850            for (int i = 0; i < N; i++) {
1851                if (mResId[i] != t.mResId[i] || mForce[i] != t.mForce[i]) {
1852                    return false;
1853                }
1854            }
1855
1856            return true;
1857        }
1858
1859        /**
1860         * @return a shallow copy of this key
1861         */
1862        @Override
1863        public ThemeKey clone() {
1864            final ThemeKey other = new ThemeKey();
1865            other.mResId = mResId;
1866            other.mForce = mForce;
1867            other.mCount = mCount;
1868            other.mHashCode = mHashCode;
1869            return other;
1870        }
1871    }
1872
1873    /**
1874     * Generate a new Theme object for this set of Resources.  It initially
1875     * starts out empty.
1876     *
1877     * @return Theme The newly created Theme container.
1878     */
1879    public final Theme newTheme() {
1880        return new Theme();
1881    }
1882
1883    /**
1884     * Retrieve a set of basic attribute values from an AttributeSet, not
1885     * performing styling of them using a theme and/or style resources.
1886     *
1887     * @param set The current attribute values to retrieve.
1888     * @param attrs The specific attributes to be retrieved.
1889     * @return Returns a TypedArray holding an array of the attribute values.
1890     * Be sure to call {@link TypedArray#recycle() TypedArray.recycle()}
1891     * when done with it.
1892     *
1893     * @see Theme#obtainStyledAttributes(AttributeSet, int[], int, int)
1894     */
1895    public TypedArray obtainAttributes(AttributeSet set, int[] attrs) {
1896        int len = attrs.length;
1897        TypedArray array = TypedArray.obtain(this, len);
1898
1899        // XXX note that for now we only work with compiled XML files.
1900        // To support generic XML files we will need to manually parse
1901        // out the attributes from the XML file (applying type information
1902        // contained in the resources and such).
1903        XmlBlock.Parser parser = (XmlBlock.Parser)set;
1904        mAssets.retrieveAttributes(parser.mParseState, attrs,
1905                array.mData, array.mIndices);
1906
1907        array.mXml = parser;
1908
1909        return array;
1910    }
1911
1912    /**
1913     * Store the newly updated configuration.
1914     */
1915    public void updateConfiguration(Configuration config,
1916            DisplayMetrics metrics) {
1917        updateConfiguration(config, metrics, null);
1918    }
1919
1920    /**
1921     * @hide
1922     */
1923    public void updateConfiguration(Configuration config,
1924            DisplayMetrics metrics, CompatibilityInfo compat) {
1925        synchronized (mAccessLock) {
1926            if (false) {
1927                Slog.i(TAG, "**** Updating config of " + this + ": old config is "
1928                        + mConfiguration + " old compat is " + mCompatibilityInfo);
1929                Slog.i(TAG, "**** Updating config of " + this + ": new config is "
1930                        + config + " new compat is " + compat);
1931            }
1932            if (compat != null) {
1933                mCompatibilityInfo = compat;
1934            }
1935            if (metrics != null) {
1936                mMetrics.setTo(metrics);
1937            }
1938            // NOTE: We should re-arrange this code to create a Display
1939            // with the CompatibilityInfo that is used everywhere we deal
1940            // with the display in relation to this app, rather than
1941            // doing the conversion here.  This impl should be okay because
1942            // we make sure to return a compatible display in the places
1943            // where there are public APIs to retrieve the display...  but
1944            // it would be cleaner and more maintainble to just be
1945            // consistently dealing with a compatible display everywhere in
1946            // the framework.
1947            mCompatibilityInfo.applyToDisplayMetrics(mMetrics);
1948
1949            final int configChanges = calcConfigChanges(config);
1950
1951            LocaleList locales = mConfiguration.getLocales();
1952            final boolean setLocalesToDefault = locales.isEmpty();
1953            if (setLocalesToDefault) {
1954                locales = LocaleList.getDefault();
1955                mConfiguration.setLocales(locales);
1956            }
1957            if (mConfiguration.densityDpi != Configuration.DENSITY_DPI_UNDEFINED) {
1958                mMetrics.densityDpi = mConfiguration.densityDpi;
1959                mMetrics.density = mConfiguration.densityDpi * DisplayMetrics.DENSITY_DEFAULT_SCALE;
1960            }
1961            mMetrics.scaledDensity = mMetrics.density * mConfiguration.fontScale;
1962
1963            final int width, height;
1964            if (mMetrics.widthPixels >= mMetrics.heightPixels) {
1965                width = mMetrics.widthPixels;
1966                height = mMetrics.heightPixels;
1967            } else {
1968                //noinspection SuspiciousNameCombination
1969                width = mMetrics.heightPixels;
1970                //noinspection SuspiciousNameCombination
1971                height = mMetrics.widthPixels;
1972            }
1973
1974            final int keyboardHidden;
1975            if (mConfiguration.keyboardHidden == Configuration.KEYBOARDHIDDEN_NO
1976                    && mConfiguration.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
1977                keyboardHidden = Configuration.KEYBOARDHIDDEN_SOFT;
1978            } else {
1979                keyboardHidden = mConfiguration.keyboardHidden;
1980            }
1981
1982            if (setLocalesToDefault || mResolvedLocale == null
1983                    || (configChanges & Configuration.NATIVE_CONFIG_LOCALE) != 0) {
1984                mResolvedLocale = locales.getFirstMatch(mAssets.getLocales());
1985            }
1986            mAssets.setConfiguration(mConfiguration.mcc, mConfiguration.mnc,
1987                    adjustLanguageTag(mResolvedLocale.toLanguageTag()),
1988                    mConfiguration.orientation,
1989                    mConfiguration.touchscreen,
1990                    mConfiguration.densityDpi, mConfiguration.keyboard,
1991                    keyboardHidden, mConfiguration.navigation, width, height,
1992                    mConfiguration.smallestScreenWidthDp,
1993                    mConfiguration.screenWidthDp, mConfiguration.screenHeightDp,
1994                    mConfiguration.screenLayout, mConfiguration.uiMode,
1995                    Build.VERSION.RESOURCES_SDK_INT);
1996
1997            if (DEBUG_CONFIG) {
1998                Slog.i(TAG, "**** Updating config of " + this + ": final config is "
1999                        + mConfiguration + " final compat is " + mCompatibilityInfo);
2000            }
2001
2002            mDrawableCache.onConfigurationChange(configChanges);
2003            mColorDrawableCache.onConfigurationChange(configChanges);
2004            mColorStateListCache.onConfigurationChange(configChanges);
2005            mAnimatorCache.onConfigurationChange(configChanges);
2006            mStateListAnimatorCache.onConfigurationChange(configChanges);
2007
2008            flushLayoutCache();
2009        }
2010        synchronized (sSync) {
2011            if (mPluralRule != null) {
2012                mPluralRule = PluralRules.forLocale(mResolvedLocale);
2013            }
2014        }
2015    }
2016
2017    /**
2018     * Called by ConfigurationBoundResourceCacheTest via reflection.
2019     */
2020    private int calcConfigChanges(Configuration config) {
2021        int configChanges = 0xfffffff;
2022        if (config != null) {
2023            mTmpConfig.setTo(config);
2024            int density = config.densityDpi;
2025            if (density == Configuration.DENSITY_DPI_UNDEFINED) {
2026                density = mMetrics.noncompatDensityDpi;
2027            }
2028
2029            mCompatibilityInfo.applyToConfiguration(density, mTmpConfig);
2030
2031            if (mTmpConfig.getLocales().isEmpty()) {
2032                mTmpConfig.setLocales(LocaleList.getDefault());
2033            }
2034            configChanges = mConfiguration.updateFrom(mTmpConfig);
2035            configChanges = ActivityInfo.activityInfoConfigToNative(configChanges);
2036        }
2037        return configChanges;
2038    }
2039
2040    /**
2041     * {@code Locale.toLanguageTag} will transform the obsolete (and deprecated)
2042     * language codes "in", "ji" and "iw" to "id", "yi" and "he" respectively.
2043     *
2044     * All released versions of android prior to "L" used the deprecated language
2045     * tags, so we will need to support them for backwards compatibility.
2046     *
2047     * Note that this conversion needs to take place *after* the call to
2048     * {@code toLanguageTag} because that will convert all the deprecated codes to
2049     * the new ones, even if they're set manually.
2050     */
2051    private static String adjustLanguageTag(String languageTag) {
2052        final int separator = languageTag.indexOf('-');
2053        final String language;
2054        final String remainder;
2055
2056        if (separator == -1) {
2057            language = languageTag;
2058            remainder = "";
2059        } else {
2060            language = languageTag.substring(0, separator);
2061            remainder = languageTag.substring(separator);
2062        }
2063
2064        return Locale.adjustLanguageCode(language) + remainder;
2065    }
2066
2067    /**
2068     * Update the system resources configuration if they have previously
2069     * been initialized.
2070     *
2071     * @hide
2072     */
2073    public static void updateSystemConfiguration(Configuration config, DisplayMetrics metrics,
2074            CompatibilityInfo compat) {
2075        if (mSystem != null) {
2076            mSystem.updateConfiguration(config, metrics, compat);
2077            //Log.i(TAG, "Updated system resources " + mSystem
2078            //        + ": " + mSystem.getConfiguration());
2079        }
2080    }
2081
2082    /**
2083     * Return the current display metrics that are in effect for this resource
2084     * object.  The returned object should be treated as read-only.
2085     *
2086     * @return The resource's current display metrics.
2087     */
2088    public DisplayMetrics getDisplayMetrics() {
2089        if (DEBUG_CONFIG) Slog.v(TAG, "Returning DisplayMetrics: " + mMetrics.widthPixels
2090                + "x" + mMetrics.heightPixels + " " + mMetrics.density);
2091        return mMetrics;
2092    }
2093
2094    /**
2095     * Return the current configuration that is in effect for this resource
2096     * object.  The returned object should be treated as read-only.
2097     *
2098     * @return The resource's current configuration.
2099     */
2100    public Configuration getConfiguration() {
2101        return mConfiguration;
2102    }
2103
2104    /** @hide */
2105    public Configuration[] getSizeConfigurations() {
2106        return mAssets.getSizeConfigurations();
2107    };
2108
2109    /**
2110     * Return the compatibility mode information for the application.
2111     * The returned object should be treated as read-only.
2112     *
2113     * @return compatibility info.
2114     * @hide
2115     */
2116    public CompatibilityInfo getCompatibilityInfo() {
2117        return mCompatibilityInfo;
2118    }
2119
2120    /**
2121     * This is just for testing.
2122     * @hide
2123     */
2124    public void setCompatibilityInfo(CompatibilityInfo ci) {
2125        if (ci != null) {
2126            mCompatibilityInfo = ci;
2127            updateConfiguration(mConfiguration, mMetrics);
2128        }
2129    }
2130
2131    /**
2132     * Return a resource identifier for the given resource name.  A fully
2133     * qualified resource name is of the form "package:type/entry".  The first
2134     * two components (package and type) are optional if defType and
2135     * defPackage, respectively, are specified here.
2136     *
2137     * <p>Note: use of this function is discouraged.  It is much more
2138     * efficient to retrieve resources by identifier than by name.
2139     *
2140     * @param name The name of the desired resource.
2141     * @param defType Optional default resource type to find, if "type/" is
2142     *                not included in the name.  Can be null to require an
2143     *                explicit type.
2144     * @param defPackage Optional default package to find, if "package:" is
2145     *                   not included in the name.  Can be null to require an
2146     *                   explicit package.
2147     *
2148     * @return int The associated resource identifier.  Returns 0 if no such
2149     *         resource was found.  (0 is not a valid resource ID.)
2150     */
2151    public int getIdentifier(String name, String defType, String defPackage) {
2152        if (name == null) {
2153            throw new NullPointerException("name is null");
2154        }
2155        try {
2156            return Integer.parseInt(name);
2157        } catch (Exception e) {
2158            // Ignore
2159        }
2160        return mAssets.getResourceIdentifier(name, defType, defPackage);
2161    }
2162
2163    /**
2164     * Return true if given resource identifier includes a package.
2165     *
2166     * @hide
2167     */
2168    public static boolean resourceHasPackage(@AnyRes int resid) {
2169        return (resid >>> 24) != 0;
2170    }
2171
2172    /**
2173     * Return the full name for a given resource identifier.  This name is
2174     * a single string of the form "package:type/entry".
2175     *
2176     * @param resid The resource identifier whose name is to be retrieved.
2177     *
2178     * @return A string holding the name of the resource.
2179     *
2180     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2181     *
2182     * @see #getResourcePackageName
2183     * @see #getResourceTypeName
2184     * @see #getResourceEntryName
2185     */
2186    public String getResourceName(@AnyRes int resid) throws NotFoundException {
2187        String str = mAssets.getResourceName(resid);
2188        if (str != null) return str;
2189        throw new NotFoundException("Unable to find resource ID #0x"
2190                + Integer.toHexString(resid));
2191    }
2192
2193    /**
2194     * Return the package name for a given resource identifier.
2195     *
2196     * @param resid The resource identifier whose package name is to be
2197     * retrieved.
2198     *
2199     * @return A string holding the package name of the resource.
2200     *
2201     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2202     *
2203     * @see #getResourceName
2204     */
2205    public String getResourcePackageName(@AnyRes int resid) throws NotFoundException {
2206        String str = mAssets.getResourcePackageName(resid);
2207        if (str != null) return str;
2208        throw new NotFoundException("Unable to find resource ID #0x"
2209                + Integer.toHexString(resid));
2210    }
2211
2212    /**
2213     * Return the type name for a given resource identifier.
2214     *
2215     * @param resid The resource identifier whose type name is to be
2216     * retrieved.
2217     *
2218     * @return A string holding the type name of the resource.
2219     *
2220     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2221     *
2222     * @see #getResourceName
2223     */
2224    public String getResourceTypeName(@AnyRes int resid) throws NotFoundException {
2225        String str = mAssets.getResourceTypeName(resid);
2226        if (str != null) return str;
2227        throw new NotFoundException("Unable to find resource ID #0x"
2228                + Integer.toHexString(resid));
2229    }
2230
2231    /**
2232     * Return the entry name for a given resource identifier.
2233     *
2234     * @param resid The resource identifier whose entry name is to be
2235     * retrieved.
2236     *
2237     * @return A string holding the entry name of the resource.
2238     *
2239     * @throws NotFoundException Throws NotFoundException if the given ID does not exist.
2240     *
2241     * @see #getResourceName
2242     */
2243    public String getResourceEntryName(@AnyRes int resid) throws NotFoundException {
2244        String str = mAssets.getResourceEntryName(resid);
2245        if (str != null) return str;
2246        throw new NotFoundException("Unable to find resource ID #0x"
2247                + Integer.toHexString(resid));
2248    }
2249
2250    /**
2251     * Parse a series of {@link android.R.styleable#Extra &lt;extra&gt;} tags from
2252     * an XML file.  You call this when you are at the parent tag of the
2253     * extra tags, and it will return once all of the child tags have been parsed.
2254     * This will call {@link #parseBundleExtra} for each extra tag encountered.
2255     *
2256     * @param parser The parser from which to retrieve the extras.
2257     * @param outBundle A Bundle in which to place all parsed extras.
2258     * @throws XmlPullParserException
2259     * @throws IOException
2260     */
2261    public void parseBundleExtras(XmlResourceParser parser, Bundle outBundle)
2262            throws XmlPullParserException, IOException {
2263        int outerDepth = parser.getDepth();
2264        int type;
2265        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2266               && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) {
2267            if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
2268                continue;
2269            }
2270
2271            String nodeName = parser.getName();
2272            if (nodeName.equals("extra")) {
2273                parseBundleExtra("extra", parser, outBundle);
2274                XmlUtils.skipCurrentTag(parser);
2275
2276            } else {
2277                XmlUtils.skipCurrentTag(parser);
2278            }
2279        }
2280    }
2281
2282    /**
2283     * Parse a name/value pair out of an XML tag holding that data.  The
2284     * AttributeSet must be holding the data defined by
2285     * {@link android.R.styleable#Extra}.  The following value types are supported:
2286     * <ul>
2287     * <li> {@link TypedValue#TYPE_STRING}:
2288     * {@link Bundle#putCharSequence Bundle.putCharSequence()}
2289     * <li> {@link TypedValue#TYPE_INT_BOOLEAN}:
2290     * {@link Bundle#putCharSequence Bundle.putBoolean()}
2291     * <li> {@link TypedValue#TYPE_FIRST_INT}-{@link TypedValue#TYPE_LAST_INT}:
2292     * {@link Bundle#putCharSequence Bundle.putBoolean()}
2293     * <li> {@link TypedValue#TYPE_FLOAT}:
2294     * {@link Bundle#putCharSequence Bundle.putFloat()}
2295     * </ul>
2296     *
2297     * @param tagName The name of the tag these attributes come from; this is
2298     * only used for reporting error messages.
2299     * @param attrs The attributes from which to retrieve the name/value pair.
2300     * @param outBundle The Bundle in which to place the parsed value.
2301     * @throws XmlPullParserException If the attributes are not valid.
2302     */
2303    public void parseBundleExtra(String tagName, AttributeSet attrs,
2304            Bundle outBundle) throws XmlPullParserException {
2305        TypedArray sa = obtainAttributes(attrs,
2306                com.android.internal.R.styleable.Extra);
2307
2308        String name = sa.getString(
2309                com.android.internal.R.styleable.Extra_name);
2310        if (name == null) {
2311            sa.recycle();
2312            throw new XmlPullParserException("<" + tagName
2313                    + "> requires an android:name attribute at "
2314                    + attrs.getPositionDescription());
2315        }
2316
2317        TypedValue v = sa.peekValue(
2318                com.android.internal.R.styleable.Extra_value);
2319        if (v != null) {
2320            if (v.type == TypedValue.TYPE_STRING) {
2321                CharSequence cs = v.coerceToString();
2322                outBundle.putCharSequence(name, cs);
2323            } else if (v.type == TypedValue.TYPE_INT_BOOLEAN) {
2324                outBundle.putBoolean(name, v.data != 0);
2325            } else if (v.type >= TypedValue.TYPE_FIRST_INT
2326                    && v.type <= TypedValue.TYPE_LAST_INT) {
2327                outBundle.putInt(name, v.data);
2328            } else if (v.type == TypedValue.TYPE_FLOAT) {
2329                outBundle.putFloat(name, v.getFloat());
2330            } else {
2331                sa.recycle();
2332                throw new XmlPullParserException("<" + tagName
2333                        + "> only supports string, integer, float, color, and boolean at "
2334                        + attrs.getPositionDescription());
2335            }
2336        } else {
2337            sa.recycle();
2338            throw new XmlPullParserException("<" + tagName
2339                    + "> requires an android:value or android:resource attribute at "
2340                    + attrs.getPositionDescription());
2341        }
2342
2343        sa.recycle();
2344    }
2345
2346    /**
2347     * Retrieve underlying AssetManager storage for these resources.
2348     */
2349    public final AssetManager getAssets() {
2350        return mAssets;
2351    }
2352
2353    /**
2354     * Call this to remove all cached loaded layout resources from the
2355     * Resources object.  Only intended for use with performance testing
2356     * tools.
2357     */
2358    public final void flushLayoutCache() {
2359        synchronized (mCachedXmlBlockIds) {
2360            // First see if this block is in our cache.
2361            final int num = mCachedXmlBlockIds.length;
2362            for (int i=0; i<num; i++) {
2363                mCachedXmlBlockIds[i] = -0;
2364                XmlBlock oldBlock = mCachedXmlBlocks[i];
2365                if (oldBlock != null) {
2366                    oldBlock.close();
2367                }
2368                mCachedXmlBlocks[i] = null;
2369            }
2370        }
2371    }
2372
2373    /**
2374     * Start preloading of resource data using this Resources object.  Only
2375     * for use by the zygote process for loading common system resources.
2376     * {@hide}
2377     */
2378    public final void startPreloading() {
2379        synchronized (sSync) {
2380            if (sPreloaded) {
2381                throw new IllegalStateException("Resources already preloaded");
2382            }
2383            sPreloaded = true;
2384            mPreloading = true;
2385            mConfiguration.densityDpi = DisplayMetrics.DENSITY_DEVICE;
2386            updateConfiguration(null, null);
2387        }
2388    }
2389
2390    /**
2391     * Called by zygote when it is done preloading resources, to change back
2392     * to normal Resources operation.
2393     */
2394    public final void finishPreloading() {
2395        if (mPreloading) {
2396            mPreloading = false;
2397            flushLayoutCache();
2398        }
2399    }
2400
2401    /**
2402     * @hide
2403     */
2404    public LongSparseArray<ConstantState> getPreloadedDrawables() {
2405        return sPreloadedDrawables[0];
2406    }
2407
2408    private boolean verifyPreloadConfig(int changingConfigurations, int allowVarying,
2409            int resourceId, String name) {
2410        // We allow preloading of resources even if they vary by font scale (which
2411        // doesn't impact resource selection) or density (which we handle specially by
2412        // simply turning off all preloading), as well as any other configs specified
2413        // by the caller.
2414        if (((changingConfigurations&~(ActivityInfo.CONFIG_FONT_SCALE |
2415                ActivityInfo.CONFIG_DENSITY)) & ~allowVarying) != 0) {
2416            String resName;
2417            try {
2418                resName = getResourceName(resourceId);
2419            } catch (NotFoundException e) {
2420                resName = "?";
2421            }
2422            // This should never happen in production, so we should log a
2423            // warning even if we're not debugging.
2424            Log.w(TAG, "Preloaded " + name + " resource #0x"
2425                    + Integer.toHexString(resourceId)
2426                    + " (" + resName + ") that varies with configuration!!");
2427            return false;
2428        }
2429        if (TRACE_FOR_PRELOAD) {
2430            String resName;
2431            try {
2432                resName = getResourceName(resourceId);
2433            } catch (NotFoundException e) {
2434                resName = "?";
2435            }
2436            Log.w(TAG, "Preloading " + name + " resource #0x"
2437                    + Integer.toHexString(resourceId)
2438                    + " (" + resName + ")");
2439        }
2440        return true;
2441    }
2442
2443    @Nullable
2444    Drawable loadDrawable(TypedValue value, int id, Theme theme) throws NotFoundException {
2445        return loadDrawable(value, id, theme, true);
2446    }
2447
2448    @Nullable
2449    Drawable loadDrawable(TypedValue value, int id, Theme theme, boolean useCache)
2450            throws NotFoundException {
2451        try {
2452            if (TRACE_FOR_PRELOAD) {
2453                // Log only framework resources
2454                if ((id >>> 24) == 0x1) {
2455                    final String name = getResourceName(id);
2456                    if (name != null) {
2457                        Log.d("PreloadDrawable", name);
2458                    }
2459                }
2460            }
2461
2462            final boolean isColorDrawable;
2463            final DrawableCache caches;
2464            final long key;
2465            if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2466                    && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2467                isColorDrawable = true;
2468                caches = mColorDrawableCache;
2469                key = value.data;
2470            } else {
2471                isColorDrawable = false;
2472                caches = mDrawableCache;
2473                key = (((long) value.assetCookie) << 32) | value.data;
2474            }
2475
2476            // First, check whether we have a cached version of this drawable
2477            // that was inflated against the specified theme. Skip the cache if
2478            // we're currently preloading or we're not using the cache.
2479            if (!mPreloading && useCache) {
2480                final Drawable cachedDrawable = caches.getInstance(key, theme);
2481                if (cachedDrawable != null) {
2482                    return cachedDrawable;
2483                }
2484            }
2485
2486            // Next, check preloaded drawables. Preloaded drawables may contain
2487            // unresolved theme attributes.
2488            final ConstantState cs;
2489            if (isColorDrawable) {
2490                cs = sPreloadedColorDrawables.get(key);
2491            } else {
2492                cs = sPreloadedDrawables[mConfiguration.getLayoutDirection()].get(key);
2493            }
2494
2495            Drawable dr;
2496            if (cs != null) {
2497                dr = cs.newDrawable(this);
2498            } else if (isColorDrawable) {
2499                dr = new ColorDrawable(value.data);
2500            } else {
2501                dr = loadDrawableForCookie(value, id, null);
2502            }
2503
2504            // Determine if the drawable has unresolved theme attributes. If it
2505            // does, we'll need to apply a theme and store it in a theme-specific
2506            // cache.
2507            final boolean canApplyTheme = dr != null && dr.canApplyTheme();
2508            if (canApplyTheme && theme != null) {
2509                dr = dr.mutate();
2510                dr.applyTheme(theme);
2511                dr.clearMutated();
2512            }
2513
2514            // If we were able to obtain a drawable, store it in the appropriate
2515            // cache: preload, not themed, null theme, or theme-specific. Don't
2516            // pollute the cache with drawables loaded from a foreign density.
2517            if (dr != null && useCache) {
2518                dr.setChangingConfigurations(value.changingConfigurations);
2519                cacheDrawable(value, isColorDrawable, caches, theme, canApplyTheme, key, dr);
2520            }
2521
2522            return dr;
2523        } catch (Exception e) {
2524            String name;
2525            try {
2526                name = getResourceName(id);
2527            } catch (NotFoundException e2) {
2528                name = "(missing name)";
2529            }
2530
2531            // The target drawable might fail to load for any number of
2532            // reasons, but we always want to include the resource name.
2533            // Since the client already expects this method to throw a
2534            // NotFoundException, just throw one of those.
2535            final NotFoundException nfe = new NotFoundException("Drawable " + name
2536                    + " with resource ID #0x" + Integer.toHexString(id), e);
2537            nfe.setStackTrace(new StackTraceElement[0]);
2538            throw nfe;
2539        }
2540    }
2541
2542    private void cacheDrawable(TypedValue value, boolean isColorDrawable, DrawableCache caches,
2543            Theme theme, boolean usesTheme, long key, Drawable dr) {
2544        final ConstantState cs = dr.getConstantState();
2545        if (cs == null) {
2546            return;
2547        }
2548
2549        if (mPreloading) {
2550            final int changingConfigs = cs.getChangingConfigurations();
2551            if (isColorDrawable) {
2552                if (verifyPreloadConfig(changingConfigs, 0, value.resourceId, "drawable")) {
2553                    sPreloadedColorDrawables.put(key, cs);
2554                }
2555            } else {
2556                if (verifyPreloadConfig(
2557                        changingConfigs, LAYOUT_DIR_CONFIG, value.resourceId, "drawable")) {
2558                    if ((changingConfigs & LAYOUT_DIR_CONFIG) == 0) {
2559                        // If this resource does not vary based on layout direction,
2560                        // we can put it in all of the preload maps.
2561                        sPreloadedDrawables[0].put(key, cs);
2562                        sPreloadedDrawables[1].put(key, cs);
2563                    } else {
2564                        // Otherwise, only in the layout dir we loaded it for.
2565                        sPreloadedDrawables[mConfiguration.getLayoutDirection()].put(key, cs);
2566                    }
2567                }
2568            }
2569        } else {
2570            synchronized (mAccessLock) {
2571                caches.put(key, theme, cs, usesTheme);
2572            }
2573        }
2574    }
2575
2576    /**
2577     * Loads a drawable from XML or resources stream.
2578     */
2579    private Drawable loadDrawableForCookie(TypedValue value, int id, Theme theme) {
2580        if (value.string == null) {
2581            throw new NotFoundException("Resource \"" + getResourceName(id) + "\" ("
2582                    + Integer.toHexString(id) + ") is not a Drawable (color or path): " + value);
2583        }
2584
2585        final String file = value.string.toString();
2586
2587        if (TRACE_FOR_MISS_PRELOAD) {
2588            // Log only framework resources
2589            if ((id >>> 24) == 0x1) {
2590                final String name = getResourceName(id);
2591                if (name != null) {
2592                    Log.d(TAG, "Loading framework drawable #" + Integer.toHexString(id)
2593                            + ": " + name + " at " + file);
2594                }
2595            }
2596        }
2597
2598        if (DEBUG_LOAD) {
2599            Log.v(TAG, "Loading drawable for cookie " + value.assetCookie + ": " + file);
2600        }
2601
2602        final Drawable dr;
2603
2604        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2605        try {
2606            if (file.endsWith(".xml")) {
2607                final XmlResourceParser rp = loadXmlResourceParser(
2608                        file, id, value.assetCookie, "drawable");
2609                dr = Drawable.createFromXml(this, rp, theme);
2610                rp.close();
2611            } else {
2612                final InputStream is = mAssets.openNonAsset(
2613                        value.assetCookie, file, AssetManager.ACCESS_STREAMING);
2614                dr = Drawable.createFromResourceStream(this, value, is, file, null);
2615                is.close();
2616            }
2617        } catch (Exception e) {
2618            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2619            final NotFoundException rnf = new NotFoundException(
2620                    "File " + file + " from drawable resource ID #0x" + Integer.toHexString(id));
2621            rnf.initCause(e);
2622            throw rnf;
2623        }
2624        Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2625
2626        return dr;
2627    }
2628
2629    @Nullable
2630    ColorStateList loadColorStateList(TypedValue value, int id, Theme theme)
2631            throws NotFoundException {
2632        if (TRACE_FOR_PRELOAD) {
2633            // Log only framework resources
2634            if ((id >>> 24) == 0x1) {
2635                final String name = getResourceName(id);
2636                if (name != null) android.util.Log.d("PreloadColorStateList", name);
2637            }
2638        }
2639
2640        final long key = (((long) value.assetCookie) << 32) | value.data;
2641
2642        ColorStateList csl;
2643
2644        // Handle inline color definitions.
2645        if (value.type >= TypedValue.TYPE_FIRST_COLOR_INT
2646                && value.type <= TypedValue.TYPE_LAST_COLOR_INT) {
2647            final android.content.res.ConstantState<ColorStateList> factory =
2648                    sPreloadedColorStateLists.get(key);
2649            if (factory != null) {
2650                return factory.newInstance();
2651            }
2652
2653            csl = ColorStateList.valueOf(value.data);
2654
2655            if (mPreloading) {
2656                if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2657                        "color")) {
2658                    sPreloadedColorStateLists.put(key, csl.getConstantState());
2659                }
2660            }
2661
2662            return csl;
2663        }
2664
2665        final ConfigurationBoundResourceCache<ColorStateList> cache = mColorStateListCache;
2666        csl = cache.getInstance(key, theme);
2667        if (csl != null) {
2668            return csl;
2669        }
2670
2671        final android.content.res.ConstantState<ColorStateList> factory =
2672                sPreloadedColorStateLists.get(key);
2673        if (factory != null) {
2674            csl = factory.newInstance(this, theme);
2675        }
2676
2677        if (csl == null) {
2678            csl = loadColorStateListForCookie(value, id, theme);
2679        }
2680
2681        if (csl != null) {
2682            if (mPreloading) {
2683                if (verifyPreloadConfig(value.changingConfigurations, 0, value.resourceId,
2684                        "color")) {
2685                    sPreloadedColorStateLists.put(key, csl.getConstantState());
2686                }
2687            } else {
2688                cache.put(key, theme, csl.getConstantState());
2689            }
2690        }
2691
2692        return csl;
2693    }
2694
2695    private ColorStateList loadColorStateListForCookie(TypedValue value, int id, Theme theme) {
2696        if (value.string == null) {
2697            throw new UnsupportedOperationException(
2698                    "Can't convert to color state list: type=0x" + value.type);
2699        }
2700
2701        final String file = value.string.toString();
2702
2703        if (TRACE_FOR_MISS_PRELOAD) {
2704            // Log only framework resources
2705            if ((id >>> 24) == 0x1) {
2706                final String name = getResourceName(id);
2707                if (name != null) {
2708                    Log.d(TAG, "Loading framework color state list #" + Integer.toHexString(id)
2709                            + ": " + name + " at " + file);
2710                }
2711            }
2712        }
2713
2714        if (DEBUG_LOAD) {
2715            Log.v(TAG, "Loading color state list for cookie " + value.assetCookie + ": " + file);
2716        }
2717
2718        final ColorStateList csl;
2719
2720        Trace.traceBegin(Trace.TRACE_TAG_RESOURCES, file);
2721        if (file.endsWith(".xml")) {
2722            try {
2723                final XmlResourceParser rp = loadXmlResourceParser(
2724                        file, id, value.assetCookie, "colorstatelist");
2725                csl = ColorStateList.createFromXml(this, rp, theme);
2726                rp.close();
2727            } catch (Exception e) {
2728                Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2729                final NotFoundException rnf = new NotFoundException(
2730                        "File " + file + " from color state list resource ID #0x"
2731                                + Integer.toHexString(id));
2732                rnf.initCause(e);
2733                throw rnf;
2734            }
2735        } else {
2736            Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2737            throw new NotFoundException(
2738                    "File " + file + " from drawable resource ID #0x"
2739                            + Integer.toHexString(id) + ": .xml extension required");
2740        }
2741        Trace.traceEnd(Trace.TRACE_TAG_RESOURCES);
2742
2743        return csl;
2744    }
2745
2746    /*package*/ XmlResourceParser loadXmlResourceParser(int id, String type)
2747            throws NotFoundException {
2748        final TypedValue value = obtainTempTypedValue(id);
2749        try {
2750            if (value.type == TypedValue.TYPE_STRING) {
2751                return loadXmlResourceParser(value.string.toString(), id,
2752                        value.assetCookie, type);
2753            }
2754            throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
2755                    + " type #0x" + Integer.toHexString(value.type) + " is not valid");
2756        } finally {
2757            releaseTempTypedValue(value);
2758        }
2759    }
2760
2761    /*package*/ XmlResourceParser loadXmlResourceParser(String file, int id,
2762            int assetCookie, String type) throws NotFoundException {
2763        if (id != 0) {
2764            try {
2765                // These may be compiled...
2766                synchronized (mCachedXmlBlockIds) {
2767                    // First see if this block is in our cache.
2768                    final int num = mCachedXmlBlockIds.length;
2769                    for (int i=0; i<num; i++) {
2770                        if (mCachedXmlBlockIds[i] == id) {
2771                            //System.out.println("**** REUSING XML BLOCK!  id="
2772                            //                   + id + ", index=" + i);
2773                            return mCachedXmlBlocks[i].newParser();
2774                        }
2775                    }
2776
2777                    // Not in the cache, create a new block and put it at
2778                    // the next slot in the cache.
2779                    XmlBlock block = mAssets.openXmlBlockAsset(
2780                            assetCookie, file);
2781                    if (block != null) {
2782                        int pos = mLastCachedXmlBlockIndex+1;
2783                        if (pos >= num) pos = 0;
2784                        mLastCachedXmlBlockIndex = pos;
2785                        XmlBlock oldBlock = mCachedXmlBlocks[pos];
2786                        if (oldBlock != null) {
2787                            oldBlock.close();
2788                        }
2789                        mCachedXmlBlockIds[pos] = id;
2790                        mCachedXmlBlocks[pos] = block;
2791                        //System.out.println("**** CACHING NEW XML BLOCK!  id="
2792                        //                   + id + ", index=" + pos);
2793                        return block.newParser();
2794                    }
2795                }
2796            } catch (Exception e) {
2797                NotFoundException rnf = new NotFoundException(
2798                        "File " + file + " from xml type " + type + " resource ID #0x"
2799                        + Integer.toHexString(id));
2800                rnf.initCause(e);
2801                throw rnf;
2802            }
2803        }
2804
2805        throw new NotFoundException(
2806                "File " + file + " from xml type " + type + " resource ID #0x"
2807                + Integer.toHexString(id));
2808    }
2809
2810    /**
2811     * Obtains styled attributes from the theme, if available, or unstyled
2812     * resources if the theme is null.
2813     *
2814     * @hide
2815     */
2816    public static TypedArray obtainAttributes(
2817            Resources res, Theme theme, AttributeSet set, int[] attrs) {
2818        if (theme == null) {
2819            return res.obtainAttributes(set, attrs);
2820        }
2821        return theme.obtainStyledAttributes(set, attrs, 0, 0);
2822    }
2823
2824    private Resources() {
2825        mAssets = AssetManager.getSystem();
2826        mClassLoader = ClassLoader.getSystemClassLoader();
2827        // NOTE: Intentionally leaving this uninitialized (all values set
2828        // to zero), so that anyone who tries to do something that requires
2829        // metrics will get a very wrong value.
2830        mConfiguration.setToDefaults();
2831        mMetrics.setToDefaults();
2832        updateConfiguration(null, null);
2833        mAssets.ensureStringBlocks();
2834    }
2835}
2836