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