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