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