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