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