Parcel.java revision da5a3e12f4f8f965c57d6f93c74190f43ea233f3
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.os;
18
19import android.text.TextUtils;
20import android.util.ArrayMap;
21import android.util.Log;
22import android.util.SparseArray;
23import android.util.SparseBooleanArray;
24
25import java.io.ByteArrayInputStream;
26import java.io.ByteArrayOutputStream;
27import java.io.FileDescriptor;
28import java.io.FileNotFoundException;
29import java.io.IOException;
30import java.io.ObjectInputStream;
31import java.io.ObjectOutputStream;
32import java.io.Serializable;
33import java.lang.reflect.Field;
34import java.util.ArrayList;
35import java.util.Arrays;
36import java.util.HashMap;
37import java.util.List;
38import java.util.Map;
39import java.util.Set;
40
41/**
42 * Container for a message (data and object references) that can
43 * be sent through an IBinder.  A Parcel can contain both flattened data
44 * that will be unflattened on the other side of the IPC (using the various
45 * methods here for writing specific types, or the general
46 * {@link Parcelable} interface), and references to live {@link IBinder}
47 * objects that will result in the other side receiving a proxy IBinder
48 * connected with the original IBinder in the Parcel.
49 *
50 * <p class="note">Parcel is <strong>not</strong> a general-purpose
51 * serialization mechanism.  This class (and the corresponding
52 * {@link Parcelable} API for placing arbitrary objects into a Parcel) is
53 * designed as a high-performance IPC transport.  As such, it is not
54 * appropriate to place any Parcel data in to persistent storage: changes
55 * in the underlying implementation of any of the data in the Parcel can
56 * render older data unreadable.</p>
57 *
58 * <p>The bulk of the Parcel API revolves around reading and writing data
59 * of various types.  There are six major classes of such functions available.</p>
60 *
61 * <h3>Primitives</h3>
62 *
63 * <p>The most basic data functions are for writing and reading primitive
64 * data types: {@link #writeByte}, {@link #readByte}, {@link #writeDouble},
65 * {@link #readDouble}, {@link #writeFloat}, {@link #readFloat}, {@link #writeInt},
66 * {@link #readInt}, {@link #writeLong}, {@link #readLong},
67 * {@link #writeString}, {@link #readString}.  Most other
68 * data operations are built on top of these.  The given data is written and
69 * read using the endianess of the host CPU.</p>
70 *
71 * <h3>Primitive Arrays</h3>
72 *
73 * <p>There are a variety of methods for reading and writing raw arrays
74 * of primitive objects, which generally result in writing a 4-byte length
75 * followed by the primitive data items.  The methods for reading can either
76 * read the data into an existing array, or create and return a new array.
77 * These available types are:</p>
78 *
79 * <ul>
80 * <li> {@link #writeBooleanArray(boolean[])},
81 * {@link #readBooleanArray(boolean[])}, {@link #createBooleanArray()}
82 * <li> {@link #writeByteArray(byte[])},
83 * {@link #writeByteArray(byte[], int, int)}, {@link #readByteArray(byte[])},
84 * {@link #createByteArray()}
85 * <li> {@link #writeCharArray(char[])}, {@link #readCharArray(char[])},
86 * {@link #createCharArray()}
87 * <li> {@link #writeDoubleArray(double[])}, {@link #readDoubleArray(double[])},
88 * {@link #createDoubleArray()}
89 * <li> {@link #writeFloatArray(float[])}, {@link #readFloatArray(float[])},
90 * {@link #createFloatArray()}
91 * <li> {@link #writeIntArray(int[])}, {@link #readIntArray(int[])},
92 * {@link #createIntArray()}
93 * <li> {@link #writeLongArray(long[])}, {@link #readLongArray(long[])},
94 * {@link #createLongArray()}
95 * <li> {@link #writeStringArray(String[])}, {@link #readStringArray(String[])},
96 * {@link #createStringArray()}.
97 * <li> {@link #writeSparseBooleanArray(SparseBooleanArray)},
98 * {@link #readSparseBooleanArray()}.
99 * </ul>
100 *
101 * <h3>Parcelables</h3>
102 *
103 * <p>The {@link Parcelable} protocol provides an extremely efficient (but
104 * low-level) protocol for objects to write and read themselves from Parcels.
105 * You can use the direct methods {@link #writeParcelable(Parcelable, int)}
106 * and {@link #readParcelable(ClassLoader)} or
107 * {@link #writeParcelableArray} and
108 * {@link #readParcelableArray(ClassLoader)} to write or read.  These
109 * methods write both the class type and its data to the Parcel, allowing
110 * that class to be reconstructed from the appropriate class loader when
111 * later reading.</p>
112 *
113 * <p>There are also some methods that provide a more efficient way to work
114 * with Parcelables: {@link #writeTypedArray},
115 * {@link #writeTypedList(List)},
116 * {@link #readTypedArray} and {@link #readTypedList}.  These methods
117 * do not write the class information of the original object: instead, the
118 * caller of the read function must know what type to expect and pass in the
119 * appropriate {@link Parcelable.Creator Parcelable.Creator} instead to
120 * properly construct the new object and read its data.  (To more efficient
121 * write and read a single Parceable object, you can directly call
122 * {@link Parcelable#writeToParcel Parcelable.writeToParcel} and
123 * {@link Parcelable.Creator#createFromParcel Parcelable.Creator.createFromParcel}
124 * yourself.)</p>
125 *
126 * <h3>Bundles</h3>
127 *
128 * <p>A special type-safe container, called {@link Bundle}, is available
129 * for key/value maps of heterogeneous values.  This has many optimizations
130 * for improved performance when reading and writing data, and its type-safe
131 * API avoids difficult to debug type errors when finally marshalling the
132 * data contents into a Parcel.  The methods to use are
133 * {@link #writeBundle(Bundle)}, {@link #readBundle()}, and
134 * {@link #readBundle(ClassLoader)}.
135 *
136 * <h3>Active Objects</h3>
137 *
138 * <p>An unusual feature of Parcel is the ability to read and write active
139 * objects.  For these objects the actual contents of the object is not
140 * written, rather a special token referencing the object is written.  When
141 * reading the object back from the Parcel, you do not get a new instance of
142 * the object, but rather a handle that operates on the exact same object that
143 * was originally written.  There are two forms of active objects available.</p>
144 *
145 * <p>{@link Binder} objects are a core facility of Android's general cross-process
146 * communication system.  The {@link IBinder} interface describes an abstract
147 * protocol with a Binder object.  Any such interface can be written in to
148 * a Parcel, and upon reading you will receive either the original object
149 * implementing that interface or a special proxy implementation
150 * that communicates calls back to the original object.  The methods to use are
151 * {@link #writeStrongBinder(IBinder)},
152 * {@link #writeStrongInterface(IInterface)}, {@link #readStrongBinder()},
153 * {@link #writeBinderArray(IBinder[])}, {@link #readBinderArray(IBinder[])},
154 * {@link #createBinderArray()},
155 * {@link #writeBinderList(List)}, {@link #readBinderList(List)},
156 * {@link #createBinderArrayList()}.</p>
157 *
158 * <p>FileDescriptor objects, representing raw Linux file descriptor identifiers,
159 * can be written and {@link ParcelFileDescriptor} objects returned to operate
160 * on the original file descriptor.  The returned file descriptor is a dup
161 * of the original file descriptor: the object and fd is different, but
162 * operating on the same underlying file stream, with the same position, etc.
163 * The methods to use are {@link #writeFileDescriptor(FileDescriptor)},
164 * {@link #readFileDescriptor()}.
165 *
166 * <h3>Untyped Containers</h3>
167 *
168 * <p>A final class of methods are for writing and reading standard Java
169 * containers of arbitrary types.  These all revolve around the
170 * {@link #writeValue(Object)} and {@link #readValue(ClassLoader)} methods
171 * which define the types of objects allowed.  The container methods are
172 * {@link #writeArray(Object[])}, {@link #readArray(ClassLoader)},
173 * {@link #writeList(List)}, {@link #readList(List, ClassLoader)},
174 * {@link #readArrayList(ClassLoader)},
175 * {@link #writeMap(Map)}, {@link #readMap(Map, ClassLoader)},
176 * {@link #writeSparseArray(SparseArray)},
177 * {@link #readSparseArray(ClassLoader)}.
178 */
179public final class Parcel {
180    private static final boolean DEBUG_RECYCLE = false;
181    private static final String TAG = "Parcel";
182
183    @SuppressWarnings({"UnusedDeclaration"})
184    private int mNativePtr; // used by native code
185
186    /**
187     * Flag indicating if {@link #mNativePtr} was allocated by this object,
188     * indicating that we're responsible for its lifecycle.
189     */
190    private boolean mOwnsNativeParcelObject;
191
192    private RuntimeException mStack;
193
194    private static final int POOL_SIZE = 6;
195    private static final Parcel[] sOwnedPool = new Parcel[POOL_SIZE];
196    private static final Parcel[] sHolderPool = new Parcel[POOL_SIZE];
197
198    private static final int VAL_NULL = -1;
199    private static final int VAL_STRING = 0;
200    private static final int VAL_INTEGER = 1;
201    private static final int VAL_MAP = 2;
202    private static final int VAL_BUNDLE = 3;
203    private static final int VAL_PARCELABLE = 4;
204    private static final int VAL_SHORT = 5;
205    private static final int VAL_LONG = 6;
206    private static final int VAL_FLOAT = 7;
207    private static final int VAL_DOUBLE = 8;
208    private static final int VAL_BOOLEAN = 9;
209    private static final int VAL_CHARSEQUENCE = 10;
210    private static final int VAL_LIST  = 11;
211    private static final int VAL_SPARSEARRAY = 12;
212    private static final int VAL_BYTEARRAY = 13;
213    private static final int VAL_STRINGARRAY = 14;
214    private static final int VAL_IBINDER = 15;
215    private static final int VAL_PARCELABLEARRAY = 16;
216    private static final int VAL_OBJECTARRAY = 17;
217    private static final int VAL_INTARRAY = 18;
218    private static final int VAL_LONGARRAY = 19;
219    private static final int VAL_BYTE = 20;
220    private static final int VAL_SERIALIZABLE = 21;
221    private static final int VAL_SPARSEBOOLEANARRAY = 22;
222    private static final int VAL_BOOLEANARRAY = 23;
223    private static final int VAL_CHARSEQUENCEARRAY = 24;
224
225    // The initial int32 in a Binder call's reply Parcel header:
226    private static final int EX_SECURITY = -1;
227    private static final int EX_BAD_PARCELABLE = -2;
228    private static final int EX_ILLEGAL_ARGUMENT = -3;
229    private static final int EX_NULL_POINTER = -4;
230    private static final int EX_ILLEGAL_STATE = -5;
231    private static final int EX_HAS_REPLY_HEADER = -128;  // special; see below
232
233    private static native int nativeDataSize(int nativePtr);
234    private static native int nativeDataAvail(int nativePtr);
235    private static native int nativeDataPosition(int nativePtr);
236    private static native int nativeDataCapacity(int nativePtr);
237    private static native void nativeSetDataSize(int nativePtr, int size);
238    private static native void nativeSetDataPosition(int nativePtr, int pos);
239    private static native void nativeSetDataCapacity(int nativePtr, int size);
240
241    private static native boolean nativePushAllowFds(int nativePtr, boolean allowFds);
242    private static native void nativeRestoreAllowFds(int nativePtr, boolean lastValue);
243
244    private static native void nativeWriteByteArray(int nativePtr, byte[] b, int offset, int len);
245    private static native void nativeWriteInt(int nativePtr, int val);
246    private static native void nativeWriteLong(int nativePtr, long val);
247    private static native void nativeWriteFloat(int nativePtr, float val);
248    private static native void nativeWriteDouble(int nativePtr, double val);
249    private static native void nativeWriteString(int nativePtr, String val);
250    private static native void nativeWriteStrongBinder(int nativePtr, IBinder val);
251    private static native void nativeWriteFileDescriptor(int nativePtr, FileDescriptor val);
252
253    private static native byte[] nativeCreateByteArray(int nativePtr);
254    private static native int nativeReadInt(int nativePtr);
255    private static native long nativeReadLong(int nativePtr);
256    private static native float nativeReadFloat(int nativePtr);
257    private static native double nativeReadDouble(int nativePtr);
258    private static native String nativeReadString(int nativePtr);
259    private static native IBinder nativeReadStrongBinder(int nativePtr);
260    private static native FileDescriptor nativeReadFileDescriptor(int nativePtr);
261
262    private static native int nativeCreate();
263    private static native void nativeFreeBuffer(int nativePtr);
264    private static native void nativeDestroy(int nativePtr);
265
266    private static native byte[] nativeMarshall(int nativePtr);
267    private static native void nativeUnmarshall(
268            int nativePtr, byte[] data, int offest, int length);
269    private static native void nativeAppendFrom(
270            int thisNativePtr, int otherNativePtr, int offset, int length);
271    private static native boolean nativeHasFileDescriptors(int nativePtr);
272    private static native void nativeWriteInterfaceToken(int nativePtr, String interfaceName);
273    private static native void nativeEnforceInterface(int nativePtr, String interfaceName);
274
275    public final static Parcelable.Creator<String> STRING_CREATOR
276             = new Parcelable.Creator<String>() {
277        public String createFromParcel(Parcel source) {
278            return source.readString();
279        }
280        public String[] newArray(int size) {
281            return new String[size];
282        }
283    };
284
285    /**
286     * Retrieve a new Parcel object from the pool.
287     */
288    public static Parcel obtain() {
289        final Parcel[] pool = sOwnedPool;
290        synchronized (pool) {
291            Parcel p;
292            for (int i=0; i<POOL_SIZE; i++) {
293                p = pool[i];
294                if (p != null) {
295                    pool[i] = null;
296                    if (DEBUG_RECYCLE) {
297                        p.mStack = new RuntimeException();
298                    }
299                    return p;
300                }
301            }
302        }
303        return new Parcel(0);
304    }
305
306    /**
307     * Put a Parcel object back into the pool.  You must not touch
308     * the object after this call.
309     */
310    public final void recycle() {
311        if (DEBUG_RECYCLE) mStack = null;
312        freeBuffer();
313
314        final Parcel[] pool;
315        if (mOwnsNativeParcelObject) {
316            pool = sOwnedPool;
317        } else {
318            mNativePtr = 0;
319            pool = sHolderPool;
320        }
321
322        synchronized (pool) {
323            for (int i=0; i<POOL_SIZE; i++) {
324                if (pool[i] == null) {
325                    pool[i] = this;
326                    return;
327                }
328            }
329        }
330    }
331
332    /**
333     * Returns the total amount of data contained in the parcel.
334     */
335    public final int dataSize() {
336        return nativeDataSize(mNativePtr);
337    }
338
339    /**
340     * Returns the amount of data remaining to be read from the
341     * parcel.  That is, {@link #dataSize}-{@link #dataPosition}.
342     */
343    public final int dataAvail() {
344        return nativeDataAvail(mNativePtr);
345    }
346
347    /**
348     * Returns the current position in the parcel data.  Never
349     * more than {@link #dataSize}.
350     */
351    public final int dataPosition() {
352        return nativeDataPosition(mNativePtr);
353    }
354
355    /**
356     * Returns the total amount of space in the parcel.  This is always
357     * >= {@link #dataSize}.  The difference between it and dataSize() is the
358     * amount of room left until the parcel needs to re-allocate its
359     * data buffer.
360     */
361    public final int dataCapacity() {
362        return nativeDataCapacity(mNativePtr);
363    }
364
365    /**
366     * Change the amount of data in the parcel.  Can be either smaller or
367     * larger than the current size.  If larger than the current capacity,
368     * more memory will be allocated.
369     *
370     * @param size The new number of bytes in the Parcel.
371     */
372    public final void setDataSize(int size) {
373        nativeSetDataSize(mNativePtr, size);
374    }
375
376    /**
377     * Move the current read/write position in the parcel.
378     * @param pos New offset in the parcel; must be between 0 and
379     * {@link #dataSize}.
380     */
381    public final void setDataPosition(int pos) {
382        nativeSetDataPosition(mNativePtr, pos);
383    }
384
385    /**
386     * Change the capacity (current available space) of the parcel.
387     *
388     * @param size The new capacity of the parcel, in bytes.  Can not be
389     * less than {@link #dataSize} -- that is, you can not drop existing data
390     * with this method.
391     */
392    public final void setDataCapacity(int size) {
393        nativeSetDataCapacity(mNativePtr, size);
394    }
395
396    /** @hide */
397    public final boolean pushAllowFds(boolean allowFds) {
398        return nativePushAllowFds(mNativePtr, allowFds);
399    }
400
401    /** @hide */
402    public final void restoreAllowFds(boolean lastValue) {
403        nativeRestoreAllowFds(mNativePtr, lastValue);
404    }
405
406    /**
407     * Returns the raw bytes of the parcel.
408     *
409     * <p class="note">The data you retrieve here <strong>must not</strong>
410     * be placed in any kind of persistent storage (on local disk, across
411     * a network, etc).  For that, you should use standard serialization
412     * or another kind of general serialization mechanism.  The Parcel
413     * marshalled representation is highly optimized for local IPC, and as
414     * such does not attempt to maintain compatibility with data created
415     * in different versions of the platform.
416     */
417    public final byte[] marshall() {
418        return nativeMarshall(mNativePtr);
419    }
420
421    /**
422     * Set the bytes in data to be the raw bytes of this Parcel.
423     */
424    public final void unmarshall(byte[] data, int offest, int length) {
425        nativeUnmarshall(mNativePtr, data, offest, length);
426    }
427
428    public final void appendFrom(Parcel parcel, int offset, int length) {
429        nativeAppendFrom(mNativePtr, parcel.mNativePtr, offset, length);
430    }
431
432    /**
433     * Report whether the parcel contains any marshalled file descriptors.
434     */
435    public final boolean hasFileDescriptors() {
436        return nativeHasFileDescriptors(mNativePtr);
437    }
438
439    /**
440     * Store or read an IBinder interface token in the parcel at the current
441     * {@link #dataPosition}.  This is used to validate that the marshalled
442     * transaction is intended for the target interface.
443     */
444    public final void writeInterfaceToken(String interfaceName) {
445        nativeWriteInterfaceToken(mNativePtr, interfaceName);
446    }
447
448    public final void enforceInterface(String interfaceName) {
449        nativeEnforceInterface(mNativePtr, interfaceName);
450    }
451
452    /**
453     * Write a byte array into the parcel at the current {@link #dataPosition},
454     * growing {@link #dataCapacity} if needed.
455     * @param b Bytes to place into the parcel.
456     */
457    public final void writeByteArray(byte[] b) {
458        writeByteArray(b, 0, (b != null) ? b.length : 0);
459    }
460
461    /**
462     * Write a byte array into the parcel at the current {@link #dataPosition},
463     * growing {@link #dataCapacity} if needed.
464     * @param b Bytes to place into the parcel.
465     * @param offset Index of first byte to be written.
466     * @param len Number of bytes to write.
467     */
468    public final void writeByteArray(byte[] b, int offset, int len) {
469        if (b == null) {
470            writeInt(-1);
471            return;
472        }
473        Arrays.checkOffsetAndCount(b.length, offset, len);
474        nativeWriteByteArray(mNativePtr, b, offset, len);
475    }
476
477    /**
478     * Write an integer value into the parcel at the current dataPosition(),
479     * growing dataCapacity() if needed.
480     */
481    public final void writeInt(int val) {
482        nativeWriteInt(mNativePtr, val);
483    }
484
485    /**
486     * Write a long integer value into the parcel at the current dataPosition(),
487     * growing dataCapacity() if needed.
488     */
489    public final void writeLong(long val) {
490        nativeWriteLong(mNativePtr, val);
491    }
492
493    /**
494     * Write a floating point value into the parcel at the current
495     * dataPosition(), growing dataCapacity() if needed.
496     */
497    public final void writeFloat(float val) {
498        nativeWriteFloat(mNativePtr, val);
499    }
500
501    /**
502     * Write a double precision floating point value into the parcel at the
503     * current dataPosition(), growing dataCapacity() if needed.
504     */
505    public final void writeDouble(double val) {
506        nativeWriteDouble(mNativePtr, val);
507    }
508
509    /**
510     * Write a string value into the parcel at the current dataPosition(),
511     * growing dataCapacity() if needed.
512     */
513    public final void writeString(String val) {
514        nativeWriteString(mNativePtr, val);
515    }
516
517    /**
518     * Write a CharSequence value into the parcel at the current dataPosition(),
519     * growing dataCapacity() if needed.
520     * @hide
521     */
522    public final void writeCharSequence(CharSequence val) {
523        TextUtils.writeToParcel(val, this, 0);
524    }
525
526    /**
527     * Write an object into the parcel at the current dataPosition(),
528     * growing dataCapacity() if needed.
529     */
530    public final void writeStrongBinder(IBinder val) {
531        nativeWriteStrongBinder(mNativePtr, val);
532    }
533
534    /**
535     * Write an object into the parcel at the current dataPosition(),
536     * growing dataCapacity() if needed.
537     */
538    public final void writeStrongInterface(IInterface val) {
539        writeStrongBinder(val == null ? null : val.asBinder());
540    }
541
542    /**
543     * Write a FileDescriptor into the parcel at the current dataPosition(),
544     * growing dataCapacity() if needed.
545     *
546     * <p class="caution">The file descriptor will not be closed, which may
547     * result in file descriptor leaks when objects are returned from Binder
548     * calls.  Use {@link ParcelFileDescriptor#writeToParcel} instead, which
549     * accepts contextual flags and will close the original file descriptor
550     * if {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set.</p>
551     */
552    public final void writeFileDescriptor(FileDescriptor val) {
553        nativeWriteFileDescriptor(mNativePtr, val);
554    }
555
556    /**
557     * Write a byte value into the parcel at the current dataPosition(),
558     * growing dataCapacity() if needed.
559     */
560    public final void writeByte(byte val) {
561        writeInt(val);
562    }
563
564    /**
565     * Please use {@link #writeBundle} instead.  Flattens a Map into the parcel
566     * at the current dataPosition(),
567     * growing dataCapacity() if needed.  The Map keys must be String objects.
568     * The Map values are written using {@link #writeValue} and must follow
569     * the specification there.
570     *
571     * <p>It is strongly recommended to use {@link #writeBundle} instead of
572     * this method, since the Bundle class provides a type-safe API that
573     * allows you to avoid mysterious type errors at the point of marshalling.
574     */
575    public final void writeMap(Map val) {
576        writeMapInternal((Map<String, Object>) val);
577    }
578
579    /**
580     * Flatten a Map into the parcel at the current dataPosition(),
581     * growing dataCapacity() if needed.  The Map keys must be String objects.
582     */
583    /* package */ void writeMapInternal(Map<String,Object> val) {
584        if (val == null) {
585            writeInt(-1);
586            return;
587        }
588        Set<Map.Entry<String,Object>> entries = val.entrySet();
589        writeInt(entries.size());
590        for (Map.Entry<String,Object> e : entries) {
591            writeValue(e.getKey());
592            writeValue(e.getValue());
593        }
594    }
595
596    /**
597     * Flatten an ArrayMap into the parcel at the current dataPosition(),
598     * growing dataCapacity() if needed.  The Map keys must be String objects.
599     */
600    /* package */ void writeArrayMapInternal(ArrayMap<String,Object> val) {
601        if (val == null) {
602            writeInt(-1);
603            return;
604        }
605        final int N = val.size();
606        writeInt(N);
607        for (int i=0; i<N; i++) {
608            writeValue(val.keyAt(i));
609            writeValue(val.valueAt(i));
610        }
611    }
612
613    /**
614     * Flatten a Bundle into the parcel at the current dataPosition(),
615     * growing dataCapacity() if needed.
616     */
617    public final void writeBundle(Bundle val) {
618        if (val == null) {
619            writeInt(-1);
620            return;
621        }
622
623        val.writeToParcel(this, 0);
624    }
625
626    /**
627     * Flatten a List into the parcel at the current dataPosition(), growing
628     * dataCapacity() if needed.  The List values are written using
629     * {@link #writeValue} and must follow the specification there.
630     */
631    public final void writeList(List val) {
632        if (val == null) {
633            writeInt(-1);
634            return;
635        }
636        int N = val.size();
637        int i=0;
638        writeInt(N);
639        while (i < N) {
640            writeValue(val.get(i));
641            i++;
642        }
643    }
644
645    /**
646     * Flatten an Object array into the parcel at the current dataPosition(),
647     * growing dataCapacity() if needed.  The array values are written using
648     * {@link #writeValue} and must follow the specification there.
649     */
650    public final void writeArray(Object[] val) {
651        if (val == null) {
652            writeInt(-1);
653            return;
654        }
655        int N = val.length;
656        int i=0;
657        writeInt(N);
658        while (i < N) {
659            writeValue(val[i]);
660            i++;
661        }
662    }
663
664    /**
665     * Flatten a generic SparseArray into the parcel at the current
666     * dataPosition(), growing dataCapacity() if needed.  The SparseArray
667     * values are written using {@link #writeValue} and must follow the
668     * specification there.
669     */
670    public final void writeSparseArray(SparseArray<Object> val) {
671        if (val == null) {
672            writeInt(-1);
673            return;
674        }
675        int N = val.size();
676        writeInt(N);
677        int i=0;
678        while (i < N) {
679            writeInt(val.keyAt(i));
680            writeValue(val.valueAt(i));
681            i++;
682        }
683    }
684
685    public final void writeSparseBooleanArray(SparseBooleanArray val) {
686        if (val == null) {
687            writeInt(-1);
688            return;
689        }
690        int N = val.size();
691        writeInt(N);
692        int i=0;
693        while (i < N) {
694            writeInt(val.keyAt(i));
695            writeByte((byte)(val.valueAt(i) ? 1 : 0));
696            i++;
697        }
698    }
699
700    public final void writeBooleanArray(boolean[] val) {
701        if (val != null) {
702            int N = val.length;
703            writeInt(N);
704            for (int i=0; i<N; i++) {
705                writeInt(val[i] ? 1 : 0);
706            }
707        } else {
708            writeInt(-1);
709        }
710    }
711
712    public final boolean[] createBooleanArray() {
713        int N = readInt();
714        // >>2 as a fast divide-by-4 works in the create*Array() functions
715        // because dataAvail() will never return a negative number.  4 is
716        // the size of a stored boolean in the stream.
717        if (N >= 0 && N <= (dataAvail() >> 2)) {
718            boolean[] val = new boolean[N];
719            for (int i=0; i<N; i++) {
720                val[i] = readInt() != 0;
721            }
722            return val;
723        } else {
724            return null;
725        }
726    }
727
728    public final void readBooleanArray(boolean[] val) {
729        int N = readInt();
730        if (N == val.length) {
731            for (int i=0; i<N; i++) {
732                val[i] = readInt() != 0;
733            }
734        } else {
735            throw new RuntimeException("bad array lengths");
736        }
737    }
738
739    public final void writeCharArray(char[] val) {
740        if (val != null) {
741            int N = val.length;
742            writeInt(N);
743            for (int i=0; i<N; i++) {
744                writeInt((int)val[i]);
745            }
746        } else {
747            writeInt(-1);
748        }
749    }
750
751    public final char[] createCharArray() {
752        int N = readInt();
753        if (N >= 0 && N <= (dataAvail() >> 2)) {
754            char[] val = new char[N];
755            for (int i=0; i<N; i++) {
756                val[i] = (char)readInt();
757            }
758            return val;
759        } else {
760            return null;
761        }
762    }
763
764    public final void readCharArray(char[] val) {
765        int N = readInt();
766        if (N == val.length) {
767            for (int i=0; i<N; i++) {
768                val[i] = (char)readInt();
769            }
770        } else {
771            throw new RuntimeException("bad array lengths");
772        }
773    }
774
775    public final void writeIntArray(int[] val) {
776        if (val != null) {
777            int N = val.length;
778            writeInt(N);
779            for (int i=0; i<N; i++) {
780                writeInt(val[i]);
781            }
782        } else {
783            writeInt(-1);
784        }
785    }
786
787    public final int[] createIntArray() {
788        int N = readInt();
789        if (N >= 0 && N <= (dataAvail() >> 2)) {
790            int[] val = new int[N];
791            for (int i=0; i<N; i++) {
792                val[i] = readInt();
793            }
794            return val;
795        } else {
796            return null;
797        }
798    }
799
800    public final void readIntArray(int[] val) {
801        int N = readInt();
802        if (N == val.length) {
803            for (int i=0; i<N; i++) {
804                val[i] = readInt();
805            }
806        } else {
807            throw new RuntimeException("bad array lengths");
808        }
809    }
810
811    public final void writeLongArray(long[] val) {
812        if (val != null) {
813            int N = val.length;
814            writeInt(N);
815            for (int i=0; i<N; i++) {
816                writeLong(val[i]);
817            }
818        } else {
819            writeInt(-1);
820        }
821    }
822
823    public final long[] createLongArray() {
824        int N = readInt();
825        // >>3 because stored longs are 64 bits
826        if (N >= 0 && N <= (dataAvail() >> 3)) {
827            long[] val = new long[N];
828            for (int i=0; i<N; i++) {
829                val[i] = readLong();
830            }
831            return val;
832        } else {
833            return null;
834        }
835    }
836
837    public final void readLongArray(long[] val) {
838        int N = readInt();
839        if (N == val.length) {
840            for (int i=0; i<N; i++) {
841                val[i] = readLong();
842            }
843        } else {
844            throw new RuntimeException("bad array lengths");
845        }
846    }
847
848    public final void writeFloatArray(float[] val) {
849        if (val != null) {
850            int N = val.length;
851            writeInt(N);
852            for (int i=0; i<N; i++) {
853                writeFloat(val[i]);
854            }
855        } else {
856            writeInt(-1);
857        }
858    }
859
860    public final float[] createFloatArray() {
861        int N = readInt();
862        // >>2 because stored floats are 4 bytes
863        if (N >= 0 && N <= (dataAvail() >> 2)) {
864            float[] val = new float[N];
865            for (int i=0; i<N; i++) {
866                val[i] = readFloat();
867            }
868            return val;
869        } else {
870            return null;
871        }
872    }
873
874    public final void readFloatArray(float[] val) {
875        int N = readInt();
876        if (N == val.length) {
877            for (int i=0; i<N; i++) {
878                val[i] = readFloat();
879            }
880        } else {
881            throw new RuntimeException("bad array lengths");
882        }
883    }
884
885    public final void writeDoubleArray(double[] val) {
886        if (val != null) {
887            int N = val.length;
888            writeInt(N);
889            for (int i=0; i<N; i++) {
890                writeDouble(val[i]);
891            }
892        } else {
893            writeInt(-1);
894        }
895    }
896
897    public final double[] createDoubleArray() {
898        int N = readInt();
899        // >>3 because stored doubles are 8 bytes
900        if (N >= 0 && N <= (dataAvail() >> 3)) {
901            double[] val = new double[N];
902            for (int i=0; i<N; i++) {
903                val[i] = readDouble();
904            }
905            return val;
906        } else {
907            return null;
908        }
909    }
910
911    public final void readDoubleArray(double[] val) {
912        int N = readInt();
913        if (N == val.length) {
914            for (int i=0; i<N; i++) {
915                val[i] = readDouble();
916            }
917        } else {
918            throw new RuntimeException("bad array lengths");
919        }
920    }
921
922    public final void writeStringArray(String[] val) {
923        if (val != null) {
924            int N = val.length;
925            writeInt(N);
926            for (int i=0; i<N; i++) {
927                writeString(val[i]);
928            }
929        } else {
930            writeInt(-1);
931        }
932    }
933
934    public final String[] createStringArray() {
935        int N = readInt();
936        if (N >= 0) {
937            String[] val = new String[N];
938            for (int i=0; i<N; i++) {
939                val[i] = readString();
940            }
941            return val;
942        } else {
943            return null;
944        }
945    }
946
947    public final void readStringArray(String[] val) {
948        int N = readInt();
949        if (N == val.length) {
950            for (int i=0; i<N; i++) {
951                val[i] = readString();
952            }
953        } else {
954            throw new RuntimeException("bad array lengths");
955        }
956    }
957
958    public final void writeBinderArray(IBinder[] val) {
959        if (val != null) {
960            int N = val.length;
961            writeInt(N);
962            for (int i=0; i<N; i++) {
963                writeStrongBinder(val[i]);
964            }
965        } else {
966            writeInt(-1);
967        }
968    }
969
970    /**
971     * @hide
972     */
973    public final void writeCharSequenceArray(CharSequence[] val) {
974        if (val != null) {
975            int N = val.length;
976            writeInt(N);
977            for (int i=0; i<N; i++) {
978                writeCharSequence(val[i]);
979            }
980        } else {
981            writeInt(-1);
982        }
983    }
984
985    public final IBinder[] createBinderArray() {
986        int N = readInt();
987        if (N >= 0) {
988            IBinder[] val = new IBinder[N];
989            for (int i=0; i<N; i++) {
990                val[i] = readStrongBinder();
991            }
992            return val;
993        } else {
994            return null;
995        }
996    }
997
998    public final void readBinderArray(IBinder[] val) {
999        int N = readInt();
1000        if (N == val.length) {
1001            for (int i=0; i<N; i++) {
1002                val[i] = readStrongBinder();
1003            }
1004        } else {
1005            throw new RuntimeException("bad array lengths");
1006        }
1007    }
1008
1009    /**
1010     * Flatten a List containing a particular object type into the parcel, at
1011     * the current dataPosition() and growing dataCapacity() if needed.  The
1012     * type of the objects in the list must be one that implements Parcelable.
1013     * Unlike the generic writeList() method, however, only the raw data of the
1014     * objects is written and not their type, so you must use the corresponding
1015     * readTypedList() to unmarshall them.
1016     *
1017     * @param val The list of objects to be written.
1018     *
1019     * @see #createTypedArrayList
1020     * @see #readTypedList
1021     * @see Parcelable
1022     */
1023    public final <T extends Parcelable> void writeTypedList(List<T> val) {
1024        if (val == null) {
1025            writeInt(-1);
1026            return;
1027        }
1028        int N = val.size();
1029        int i=0;
1030        writeInt(N);
1031        while (i < N) {
1032            T item = val.get(i);
1033            if (item != null) {
1034                writeInt(1);
1035                item.writeToParcel(this, 0);
1036            } else {
1037                writeInt(0);
1038            }
1039            i++;
1040        }
1041    }
1042
1043    /**
1044     * Flatten a List containing String objects into the parcel, at
1045     * the current dataPosition() and growing dataCapacity() if needed.  They
1046     * can later be retrieved with {@link #createStringArrayList} or
1047     * {@link #readStringList}.
1048     *
1049     * @param val The list of strings to be written.
1050     *
1051     * @see #createStringArrayList
1052     * @see #readStringList
1053     */
1054    public final void writeStringList(List<String> val) {
1055        if (val == null) {
1056            writeInt(-1);
1057            return;
1058        }
1059        int N = val.size();
1060        int i=0;
1061        writeInt(N);
1062        while (i < N) {
1063            writeString(val.get(i));
1064            i++;
1065        }
1066    }
1067
1068    /**
1069     * Flatten a List containing IBinder objects into the parcel, at
1070     * the current dataPosition() and growing dataCapacity() if needed.  They
1071     * can later be retrieved with {@link #createBinderArrayList} or
1072     * {@link #readBinderList}.
1073     *
1074     * @param val The list of strings to be written.
1075     *
1076     * @see #createBinderArrayList
1077     * @see #readBinderList
1078     */
1079    public final void writeBinderList(List<IBinder> val) {
1080        if (val == null) {
1081            writeInt(-1);
1082            return;
1083        }
1084        int N = val.size();
1085        int i=0;
1086        writeInt(N);
1087        while (i < N) {
1088            writeStrongBinder(val.get(i));
1089            i++;
1090        }
1091    }
1092
1093    /**
1094     * Flatten a heterogeneous array containing a particular object type into
1095     * the parcel, at
1096     * the current dataPosition() and growing dataCapacity() if needed.  The
1097     * type of the objects in the array must be one that implements Parcelable.
1098     * Unlike the {@link #writeParcelableArray} method, however, only the
1099     * raw data of the objects is written and not their type, so you must use
1100     * {@link #readTypedArray} with the correct corresponding
1101     * {@link Parcelable.Creator} implementation to unmarshall them.
1102     *
1103     * @param val The array of objects to be written.
1104     * @param parcelableFlags Contextual flags as per
1105     * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1106     *
1107     * @see #readTypedArray
1108     * @see #writeParcelableArray
1109     * @see Parcelable.Creator
1110     */
1111    public final <T extends Parcelable> void writeTypedArray(T[] val,
1112            int parcelableFlags) {
1113        if (val != null) {
1114            int N = val.length;
1115            writeInt(N);
1116            for (int i=0; i<N; i++) {
1117                T item = val[i];
1118                if (item != null) {
1119                    writeInt(1);
1120                    item.writeToParcel(this, parcelableFlags);
1121                } else {
1122                    writeInt(0);
1123                }
1124            }
1125        } else {
1126            writeInt(-1);
1127        }
1128    }
1129
1130    /**
1131     * Flatten a generic object in to a parcel.  The given Object value may
1132     * currently be one of the following types:
1133     *
1134     * <ul>
1135     * <li> null
1136     * <li> String
1137     * <li> Byte
1138     * <li> Short
1139     * <li> Integer
1140     * <li> Long
1141     * <li> Float
1142     * <li> Double
1143     * <li> Boolean
1144     * <li> String[]
1145     * <li> boolean[]
1146     * <li> byte[]
1147     * <li> int[]
1148     * <li> long[]
1149     * <li> Object[] (supporting objects of the same type defined here).
1150     * <li> {@link Bundle}
1151     * <li> Map (as supported by {@link #writeMap}).
1152     * <li> Any object that implements the {@link Parcelable} protocol.
1153     * <li> Parcelable[]
1154     * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
1155     * <li> List (as supported by {@link #writeList}).
1156     * <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}).
1157     * <li> {@link IBinder}
1158     * <li> Any object that implements Serializable (but see
1159     *      {@link #writeSerializable} for caveats).  Note that all of the
1160     *      previous types have relatively efficient implementations for
1161     *      writing to a Parcel; having to rely on the generic serialization
1162     *      approach is much less efficient and should be avoided whenever
1163     *      possible.
1164     * </ul>
1165     *
1166     * <p class="caution">{@link Parcelable} objects are written with
1167     * {@link Parcelable#writeToParcel} using contextual flags of 0.  When
1168     * serializing objects containing {@link ParcelFileDescriptor}s,
1169     * this may result in file descriptor leaks when they are returned from
1170     * Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE}
1171     * should be used).</p>
1172     */
1173    public final void writeValue(Object v) {
1174        if (v == null) {
1175            writeInt(VAL_NULL);
1176        } else if (v instanceof String) {
1177            writeInt(VAL_STRING);
1178            writeString((String) v);
1179        } else if (v instanceof Integer) {
1180            writeInt(VAL_INTEGER);
1181            writeInt((Integer) v);
1182        } else if (v instanceof Map) {
1183            writeInt(VAL_MAP);
1184            writeMap((Map) v);
1185        } else if (v instanceof Bundle) {
1186            // Must be before Parcelable
1187            writeInt(VAL_BUNDLE);
1188            writeBundle((Bundle) v);
1189        } else if (v instanceof Parcelable) {
1190            writeInt(VAL_PARCELABLE);
1191            writeParcelable((Parcelable) v, 0);
1192        } else if (v instanceof Short) {
1193            writeInt(VAL_SHORT);
1194            writeInt(((Short) v).intValue());
1195        } else if (v instanceof Long) {
1196            writeInt(VAL_LONG);
1197            writeLong((Long) v);
1198        } else if (v instanceof Float) {
1199            writeInt(VAL_FLOAT);
1200            writeFloat((Float) v);
1201        } else if (v instanceof Double) {
1202            writeInt(VAL_DOUBLE);
1203            writeDouble((Double) v);
1204        } else if (v instanceof Boolean) {
1205            writeInt(VAL_BOOLEAN);
1206            writeInt((Boolean) v ? 1 : 0);
1207        } else if (v instanceof CharSequence) {
1208            // Must be after String
1209            writeInt(VAL_CHARSEQUENCE);
1210            writeCharSequence((CharSequence) v);
1211        } else if (v instanceof List) {
1212            writeInt(VAL_LIST);
1213            writeList((List) v);
1214        } else if (v instanceof SparseArray) {
1215            writeInt(VAL_SPARSEARRAY);
1216            writeSparseArray((SparseArray) v);
1217        } else if (v instanceof boolean[]) {
1218            writeInt(VAL_BOOLEANARRAY);
1219            writeBooleanArray((boolean[]) v);
1220        } else if (v instanceof byte[]) {
1221            writeInt(VAL_BYTEARRAY);
1222            writeByteArray((byte[]) v);
1223        } else if (v instanceof String[]) {
1224            writeInt(VAL_STRINGARRAY);
1225            writeStringArray((String[]) v);
1226        } else if (v instanceof CharSequence[]) {
1227            // Must be after String[] and before Object[]
1228            writeInt(VAL_CHARSEQUENCEARRAY);
1229            writeCharSequenceArray((CharSequence[]) v);
1230        } else if (v instanceof IBinder) {
1231            writeInt(VAL_IBINDER);
1232            writeStrongBinder((IBinder) v);
1233        } else if (v instanceof Parcelable[]) {
1234            writeInt(VAL_PARCELABLEARRAY);
1235            writeParcelableArray((Parcelable[]) v, 0);
1236        } else if (v instanceof Object[]) {
1237            writeInt(VAL_OBJECTARRAY);
1238            writeArray((Object[]) v);
1239        } else if (v instanceof int[]) {
1240            writeInt(VAL_INTARRAY);
1241            writeIntArray((int[]) v);
1242        } else if (v instanceof long[]) {
1243            writeInt(VAL_LONGARRAY);
1244            writeLongArray((long[]) v);
1245        } else if (v instanceof Byte) {
1246            writeInt(VAL_BYTE);
1247            writeInt((Byte) v);
1248        } else if (v instanceof Serializable) {
1249            // Must be last
1250            writeInt(VAL_SERIALIZABLE);
1251            writeSerializable((Serializable) v);
1252        } else {
1253            throw new RuntimeException("Parcel: unable to marshal value " + v);
1254        }
1255    }
1256
1257    /**
1258     * Flatten the name of the class of the Parcelable and its contents
1259     * into the parcel.
1260     *
1261     * @param p The Parcelable object to be written.
1262     * @param parcelableFlags Contextual flags as per
1263     * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1264     */
1265    public final void writeParcelable(Parcelable p, int parcelableFlags) {
1266        if (p == null) {
1267            writeString(null);
1268            return;
1269        }
1270        String name = p.getClass().getName();
1271        writeString(name);
1272        p.writeToParcel(this, parcelableFlags);
1273    }
1274
1275    /** @hide */
1276    public final void writeParcelableCreator(Parcelable p) {
1277        String name = p.getClass().getName();
1278        writeString(name);
1279    }
1280
1281    /**
1282     * Write a generic serializable object in to a Parcel.  It is strongly
1283     * recommended that this method be avoided, since the serialization
1284     * overhead is extremely large, and this approach will be much slower than
1285     * using the other approaches to writing data in to a Parcel.
1286     */
1287    public final void writeSerializable(Serializable s) {
1288        if (s == null) {
1289            writeString(null);
1290            return;
1291        }
1292        String name = s.getClass().getName();
1293        writeString(name);
1294
1295        ByteArrayOutputStream baos = new ByteArrayOutputStream();
1296        try {
1297            ObjectOutputStream oos = new ObjectOutputStream(baos);
1298            oos.writeObject(s);
1299            oos.close();
1300
1301            writeByteArray(baos.toByteArray());
1302        } catch (IOException ioe) {
1303            throw new RuntimeException("Parcelable encountered " +
1304                "IOException writing serializable object (name = " + name +
1305                ")", ioe);
1306        }
1307    }
1308
1309    /**
1310     * Special function for writing an exception result at the header of
1311     * a parcel, to be used when returning an exception from a transaction.
1312     * Note that this currently only supports a few exception types; any other
1313     * exception will be re-thrown by this function as a RuntimeException
1314     * (to be caught by the system's last-resort exception handling when
1315     * dispatching a transaction).
1316     *
1317     * <p>The supported exception types are:
1318     * <ul>
1319     * <li>{@link BadParcelableException}
1320     * <li>{@link IllegalArgumentException}
1321     * <li>{@link IllegalStateException}
1322     * <li>{@link NullPointerException}
1323     * <li>{@link SecurityException}
1324     * </ul>
1325     *
1326     * @param e The Exception to be written.
1327     *
1328     * @see #writeNoException
1329     * @see #readException
1330     */
1331    public final void writeException(Exception e) {
1332        int code = 0;
1333        if (e instanceof SecurityException) {
1334            code = EX_SECURITY;
1335        } else if (e instanceof BadParcelableException) {
1336            code = EX_BAD_PARCELABLE;
1337        } else if (e instanceof IllegalArgumentException) {
1338            code = EX_ILLEGAL_ARGUMENT;
1339        } else if (e instanceof NullPointerException) {
1340            code = EX_NULL_POINTER;
1341        } else if (e instanceof IllegalStateException) {
1342            code = EX_ILLEGAL_STATE;
1343        }
1344        writeInt(code);
1345        StrictMode.clearGatheredViolations();
1346        if (code == 0) {
1347            if (e instanceof RuntimeException) {
1348                throw (RuntimeException) e;
1349            }
1350            throw new RuntimeException(e);
1351        }
1352        writeString(e.getMessage());
1353    }
1354
1355    /**
1356     * Special function for writing information at the front of the Parcel
1357     * indicating that no exception occurred.
1358     *
1359     * @see #writeException
1360     * @see #readException
1361     */
1362    public final void writeNoException() {
1363        // Despite the name of this function ("write no exception"),
1364        // it should instead be thought of as "write the RPC response
1365        // header", but because this function name is written out by
1366        // the AIDL compiler, we're not going to rename it.
1367        //
1368        // The response header, in the non-exception case (see also
1369        // writeException above, also called by the AIDL compiler), is
1370        // either a 0 (the default case), or EX_HAS_REPLY_HEADER if
1371        // StrictMode has gathered up violations that have occurred
1372        // during a Binder call, in which case we write out the number
1373        // of violations and their details, serialized, before the
1374        // actual RPC respons data.  The receiving end of this is
1375        // readException(), below.
1376        if (StrictMode.hasGatheredViolations()) {
1377            writeInt(EX_HAS_REPLY_HEADER);
1378            final int sizePosition = dataPosition();
1379            writeInt(0);  // total size of fat header, to be filled in later
1380            StrictMode.writeGatheredViolationsToParcel(this);
1381            final int payloadPosition = dataPosition();
1382            setDataPosition(sizePosition);
1383            writeInt(payloadPosition - sizePosition);  // header size
1384            setDataPosition(payloadPosition);
1385        } else {
1386            writeInt(0);
1387        }
1388    }
1389
1390    /**
1391     * Special function for reading an exception result from the header of
1392     * a parcel, to be used after receiving the result of a transaction.  This
1393     * will throw the exception for you if it had been written to the Parcel,
1394     * otherwise return and let you read the normal result data from the Parcel.
1395     *
1396     * @see #writeException
1397     * @see #writeNoException
1398     */
1399    public final void readException() {
1400        int code = readExceptionCode();
1401        if (code != 0) {
1402            String msg = readString();
1403            readException(code, msg);
1404        }
1405    }
1406
1407    /**
1408     * Parses the header of a Binder call's response Parcel and
1409     * returns the exception code.  Deals with lite or fat headers.
1410     * In the common successful case, this header is generally zero.
1411     * In less common cases, it's a small negative number and will be
1412     * followed by an error string.
1413     *
1414     * This exists purely for android.database.DatabaseUtils and
1415     * insulating it from having to handle fat headers as returned by
1416     * e.g. StrictMode-induced RPC responses.
1417     *
1418     * @hide
1419     */
1420    public final int readExceptionCode() {
1421        int code = readInt();
1422        if (code == EX_HAS_REPLY_HEADER) {
1423            int headerSize = readInt();
1424            if (headerSize == 0) {
1425                Log.e(TAG, "Unexpected zero-sized Parcel reply header.");
1426            } else {
1427                // Currently the only thing in the header is StrictMode stacks,
1428                // but discussions around event/RPC tracing suggest we might
1429                // put that here too.  If so, switch on sub-header tags here.
1430                // But for now, just parse out the StrictMode stuff.
1431                StrictMode.readAndHandleBinderCallViolations(this);
1432            }
1433            // And fat response headers are currently only used when
1434            // there are no exceptions, so return no error:
1435            return 0;
1436        }
1437        return code;
1438    }
1439
1440    /**
1441     * Use this function for customized exception handling.
1442     * customized method call this method for all unknown case
1443     * @param code exception code
1444     * @param msg exception message
1445     */
1446    public final void readException(int code, String msg) {
1447        switch (code) {
1448            case EX_SECURITY:
1449                throw new SecurityException(msg);
1450            case EX_BAD_PARCELABLE:
1451                throw new BadParcelableException(msg);
1452            case EX_ILLEGAL_ARGUMENT:
1453                throw new IllegalArgumentException(msg);
1454            case EX_NULL_POINTER:
1455                throw new NullPointerException(msg);
1456            case EX_ILLEGAL_STATE:
1457                throw new IllegalStateException(msg);
1458        }
1459        throw new RuntimeException("Unknown exception code: " + code
1460                + " msg " + msg);
1461    }
1462
1463    /**
1464     * Read an integer value from the parcel at the current dataPosition().
1465     */
1466    public final int readInt() {
1467        return nativeReadInt(mNativePtr);
1468    }
1469
1470    /**
1471     * Read a long integer value from the parcel at the current dataPosition().
1472     */
1473    public final long readLong() {
1474        return nativeReadLong(mNativePtr);
1475    }
1476
1477    /**
1478     * Read a floating point value from the parcel at the current
1479     * dataPosition().
1480     */
1481    public final float readFloat() {
1482        return nativeReadFloat(mNativePtr);
1483    }
1484
1485    /**
1486     * Read a double precision floating point value from the parcel at the
1487     * current dataPosition().
1488     */
1489    public final double readDouble() {
1490        return nativeReadDouble(mNativePtr);
1491    }
1492
1493    /**
1494     * Read a string value from the parcel at the current dataPosition().
1495     */
1496    public final String readString() {
1497        return nativeReadString(mNativePtr);
1498    }
1499
1500    /**
1501     * Read a CharSequence value from the parcel at the current dataPosition().
1502     * @hide
1503     */
1504    public final CharSequence readCharSequence() {
1505        return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
1506    }
1507
1508    /**
1509     * Read an object from the parcel at the current dataPosition().
1510     */
1511    public final IBinder readStrongBinder() {
1512        return nativeReadStrongBinder(mNativePtr);
1513    }
1514
1515    /**
1516     * Read a FileDescriptor from the parcel at the current dataPosition().
1517     */
1518    public final ParcelFileDescriptor readFileDescriptor() {
1519        FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
1520        return fd != null ? new ParcelFileDescriptor(fd) : null;
1521    }
1522
1523    /** {@hide} */
1524    public final FileDescriptor readRawFileDescriptor() {
1525        return nativeReadFileDescriptor(mNativePtr);
1526    }
1527
1528    /*package*/ static native FileDescriptor openFileDescriptor(String file,
1529            int mode) throws FileNotFoundException;
1530    /*package*/ static native FileDescriptor dupFileDescriptor(FileDescriptor orig)
1531            throws IOException;
1532    /*package*/ static native void closeFileDescriptor(FileDescriptor desc)
1533            throws IOException;
1534    /*package*/ static native void clearFileDescriptor(FileDescriptor desc);
1535
1536    /**
1537     * Read a byte value from the parcel at the current dataPosition().
1538     */
1539    public final byte readByte() {
1540        return (byte)(readInt() & 0xff);
1541    }
1542
1543    /**
1544     * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
1545     * been written with {@link #writeBundle}.  Read into an existing Map object
1546     * from the parcel at the current dataPosition().
1547     */
1548    public final void readMap(Map outVal, ClassLoader loader) {
1549        int N = readInt();
1550        readMapInternal(outVal, N, loader);
1551    }
1552
1553    /**
1554     * Read into an existing List object from the parcel at the current
1555     * dataPosition(), using the given class loader to load any enclosed
1556     * Parcelables.  If it is null, the default class loader is used.
1557     */
1558    public final void readList(List outVal, ClassLoader loader) {
1559        int N = readInt();
1560        readListInternal(outVal, N, loader);
1561    }
1562
1563    /**
1564     * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
1565     * been written with {@link #writeBundle}.  Read and return a new HashMap
1566     * object from the parcel at the current dataPosition(), using the given
1567     * class loader to load any enclosed Parcelables.  Returns null if
1568     * the previously written map object was null.
1569     */
1570    public final HashMap readHashMap(ClassLoader loader)
1571    {
1572        int N = readInt();
1573        if (N < 0) {
1574            return null;
1575        }
1576        HashMap m = new HashMap(N);
1577        readMapInternal(m, N, loader);
1578        return m;
1579    }
1580
1581    /**
1582     * Read and return a new Bundle object from the parcel at the current
1583     * dataPosition().  Returns null if the previously written Bundle object was
1584     * null.
1585     */
1586    public final Bundle readBundle() {
1587        return readBundle(null);
1588    }
1589
1590    /**
1591     * Read and return a new Bundle object from the parcel at the current
1592     * dataPosition(), using the given class loader to initialize the class
1593     * loader of the Bundle for later retrieval of Parcelable objects.
1594     * Returns null if the previously written Bundle object was null.
1595     */
1596    public final Bundle readBundle(ClassLoader loader) {
1597        int length = readInt();
1598        if (length < 0) {
1599            return null;
1600        }
1601
1602        final Bundle bundle = new Bundle(this, length);
1603        if (loader != null) {
1604            bundle.setClassLoader(loader);
1605        }
1606        return bundle;
1607    }
1608
1609    /**
1610     * Read and return a byte[] object from the parcel.
1611     */
1612    public final byte[] createByteArray() {
1613        return nativeCreateByteArray(mNativePtr);
1614    }
1615
1616    /**
1617     * Read a byte[] object from the parcel and copy it into the
1618     * given byte array.
1619     */
1620    public final void readByteArray(byte[] val) {
1621        // TODO: make this a native method to avoid the extra copy.
1622        byte[] ba = createByteArray();
1623        if (ba.length == val.length) {
1624           System.arraycopy(ba, 0, val, 0, ba.length);
1625        } else {
1626            throw new RuntimeException("bad array lengths");
1627        }
1628    }
1629
1630    /**
1631     * Read and return a String[] object from the parcel.
1632     * {@hide}
1633     */
1634    public final String[] readStringArray() {
1635        String[] array = null;
1636
1637        int length = readInt();
1638        if (length >= 0)
1639        {
1640            array = new String[length];
1641
1642            for (int i = 0 ; i < length ; i++)
1643            {
1644                array[i] = readString();
1645            }
1646        }
1647
1648        return array;
1649    }
1650
1651    /**
1652     * Read and return a CharSequence[] object from the parcel.
1653     * {@hide}
1654     */
1655    public final CharSequence[] readCharSequenceArray() {
1656        CharSequence[] array = null;
1657
1658        int length = readInt();
1659        if (length >= 0)
1660        {
1661            array = new CharSequence[length];
1662
1663            for (int i = 0 ; i < length ; i++)
1664            {
1665                array[i] = readCharSequence();
1666            }
1667        }
1668
1669        return array;
1670    }
1671
1672    /**
1673     * Read and return a new ArrayList object from the parcel at the current
1674     * dataPosition().  Returns null if the previously written list object was
1675     * null.  The given class loader will be used to load any enclosed
1676     * Parcelables.
1677     */
1678    public final ArrayList readArrayList(ClassLoader loader) {
1679        int N = readInt();
1680        if (N < 0) {
1681            return null;
1682        }
1683        ArrayList l = new ArrayList(N);
1684        readListInternal(l, N, loader);
1685        return l;
1686    }
1687
1688    /**
1689     * Read and return a new Object array from the parcel at the current
1690     * dataPosition().  Returns null if the previously written array was
1691     * null.  The given class loader will be used to load any enclosed
1692     * Parcelables.
1693     */
1694    public final Object[] readArray(ClassLoader loader) {
1695        int N = readInt();
1696        if (N < 0) {
1697            return null;
1698        }
1699        Object[] l = new Object[N];
1700        readArrayInternal(l, N, loader);
1701        return l;
1702    }
1703
1704    /**
1705     * Read and return a new SparseArray object from the parcel at the current
1706     * dataPosition().  Returns null if the previously written list object was
1707     * null.  The given class loader will be used to load any enclosed
1708     * Parcelables.
1709     */
1710    public final SparseArray readSparseArray(ClassLoader loader) {
1711        int N = readInt();
1712        if (N < 0) {
1713            return null;
1714        }
1715        SparseArray sa = new SparseArray(N);
1716        readSparseArrayInternal(sa, N, loader);
1717        return sa;
1718    }
1719
1720    /**
1721     * Read and return a new SparseBooleanArray object from the parcel at the current
1722     * dataPosition().  Returns null if the previously written list object was
1723     * null.
1724     */
1725    public final SparseBooleanArray readSparseBooleanArray() {
1726        int N = readInt();
1727        if (N < 0) {
1728            return null;
1729        }
1730        SparseBooleanArray sa = new SparseBooleanArray(N);
1731        readSparseBooleanArrayInternal(sa, N);
1732        return sa;
1733    }
1734
1735    /**
1736     * Read and return a new ArrayList containing a particular object type from
1737     * the parcel that was written with {@link #writeTypedList} at the
1738     * current dataPosition().  Returns null if the
1739     * previously written list object was null.  The list <em>must</em> have
1740     * previously been written via {@link #writeTypedList} with the same object
1741     * type.
1742     *
1743     * @return A newly created ArrayList containing objects with the same data
1744     *         as those that were previously written.
1745     *
1746     * @see #writeTypedList
1747     */
1748    public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
1749        int N = readInt();
1750        if (N < 0) {
1751            return null;
1752        }
1753        ArrayList<T> l = new ArrayList<T>(N);
1754        while (N > 0) {
1755            if (readInt() != 0) {
1756                l.add(c.createFromParcel(this));
1757            } else {
1758                l.add(null);
1759            }
1760            N--;
1761        }
1762        return l;
1763    }
1764
1765    /**
1766     * Read into the given List items containing a particular object type
1767     * that were written with {@link #writeTypedList} at the
1768     * current dataPosition().  The list <em>must</em> have
1769     * previously been written via {@link #writeTypedList} with the same object
1770     * type.
1771     *
1772     * @return A newly created ArrayList containing objects with the same data
1773     *         as those that were previously written.
1774     *
1775     * @see #writeTypedList
1776     */
1777    public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
1778        int M = list.size();
1779        int N = readInt();
1780        int i = 0;
1781        for (; i < M && i < N; i++) {
1782            if (readInt() != 0) {
1783                list.set(i, c.createFromParcel(this));
1784            } else {
1785                list.set(i, null);
1786            }
1787        }
1788        for (; i<N; i++) {
1789            if (readInt() != 0) {
1790                list.add(c.createFromParcel(this));
1791            } else {
1792                list.add(null);
1793            }
1794        }
1795        for (; i<M; i++) {
1796            list.remove(N);
1797        }
1798    }
1799
1800    /**
1801     * Read and return a new ArrayList containing String objects from
1802     * the parcel that was written with {@link #writeStringList} at the
1803     * current dataPosition().  Returns null if the
1804     * previously written list object was null.
1805     *
1806     * @return A newly created ArrayList containing strings with the same data
1807     *         as those that were previously written.
1808     *
1809     * @see #writeStringList
1810     */
1811    public final ArrayList<String> createStringArrayList() {
1812        int N = readInt();
1813        if (N < 0) {
1814            return null;
1815        }
1816        ArrayList<String> l = new ArrayList<String>(N);
1817        while (N > 0) {
1818            l.add(readString());
1819            N--;
1820        }
1821        return l;
1822    }
1823
1824    /**
1825     * Read and return a new ArrayList containing IBinder objects from
1826     * the parcel that was written with {@link #writeBinderList} at the
1827     * current dataPosition().  Returns null if the
1828     * previously written list object was null.
1829     *
1830     * @return A newly created ArrayList containing strings with the same data
1831     *         as those that were previously written.
1832     *
1833     * @see #writeBinderList
1834     */
1835    public final ArrayList<IBinder> createBinderArrayList() {
1836        int N = readInt();
1837        if (N < 0) {
1838            return null;
1839        }
1840        ArrayList<IBinder> l = new ArrayList<IBinder>(N);
1841        while (N > 0) {
1842            l.add(readStrongBinder());
1843            N--;
1844        }
1845        return l;
1846    }
1847
1848    /**
1849     * Read into the given List items String objects that were written with
1850     * {@link #writeStringList} at the current dataPosition().
1851     *
1852     * @return A newly created ArrayList containing strings with the same data
1853     *         as those that were previously written.
1854     *
1855     * @see #writeStringList
1856     */
1857    public final void readStringList(List<String> list) {
1858        int M = list.size();
1859        int N = readInt();
1860        int i = 0;
1861        for (; i < M && i < N; i++) {
1862            list.set(i, readString());
1863        }
1864        for (; i<N; i++) {
1865            list.add(readString());
1866        }
1867        for (; i<M; i++) {
1868            list.remove(N);
1869        }
1870    }
1871
1872    /**
1873     * Read into the given List items IBinder objects that were written with
1874     * {@link #writeBinderList} at the current dataPosition().
1875     *
1876     * @return A newly created ArrayList containing strings with the same data
1877     *         as those that were previously written.
1878     *
1879     * @see #writeBinderList
1880     */
1881    public final void readBinderList(List<IBinder> list) {
1882        int M = list.size();
1883        int N = readInt();
1884        int i = 0;
1885        for (; i < M && i < N; i++) {
1886            list.set(i, readStrongBinder());
1887        }
1888        for (; i<N; i++) {
1889            list.add(readStrongBinder());
1890        }
1891        for (; i<M; i++) {
1892            list.remove(N);
1893        }
1894    }
1895
1896    /**
1897     * Read and return a new array containing a particular object type from
1898     * the parcel at the current dataPosition().  Returns null if the
1899     * previously written array was null.  The array <em>must</em> have
1900     * previously been written via {@link #writeTypedArray} with the same
1901     * object type.
1902     *
1903     * @return A newly created array containing objects with the same data
1904     *         as those that were previously written.
1905     *
1906     * @see #writeTypedArray
1907     */
1908    public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
1909        int N = readInt();
1910        if (N < 0) {
1911            return null;
1912        }
1913        T[] l = c.newArray(N);
1914        for (int i=0; i<N; i++) {
1915            if (readInt() != 0) {
1916                l[i] = c.createFromParcel(this);
1917            }
1918        }
1919        return l;
1920    }
1921
1922    public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
1923        int N = readInt();
1924        if (N == val.length) {
1925            for (int i=0; i<N; i++) {
1926                if (readInt() != 0) {
1927                    val[i] = c.createFromParcel(this);
1928                } else {
1929                    val[i] = null;
1930                }
1931            }
1932        } else {
1933            throw new RuntimeException("bad array lengths");
1934        }
1935    }
1936
1937    /**
1938     * @deprecated
1939     * @hide
1940     */
1941    @Deprecated
1942    public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
1943        return createTypedArray(c);
1944    }
1945
1946    /**
1947     * Write a heterogeneous array of Parcelable objects into the Parcel.
1948     * Each object in the array is written along with its class name, so
1949     * that the correct class can later be instantiated.  As a result, this
1950     * has significantly more overhead than {@link #writeTypedArray}, but will
1951     * correctly handle an array containing more than one type of object.
1952     *
1953     * @param value The array of objects to be written.
1954     * @param parcelableFlags Contextual flags as per
1955     * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1956     *
1957     * @see #writeTypedArray
1958     */
1959    public final <T extends Parcelable> void writeParcelableArray(T[] value,
1960            int parcelableFlags) {
1961        if (value != null) {
1962            int N = value.length;
1963            writeInt(N);
1964            for (int i=0; i<N; i++) {
1965                writeParcelable(value[i], parcelableFlags);
1966            }
1967        } else {
1968            writeInt(-1);
1969        }
1970    }
1971
1972    /**
1973     * Read a typed object from a parcel.  The given class loader will be
1974     * used to load any enclosed Parcelables.  If it is null, the default class
1975     * loader will be used.
1976     */
1977    public final Object readValue(ClassLoader loader) {
1978        int type = readInt();
1979
1980        switch (type) {
1981        case VAL_NULL:
1982            return null;
1983
1984        case VAL_STRING:
1985            return readString();
1986
1987        case VAL_INTEGER:
1988            return readInt();
1989
1990        case VAL_MAP:
1991            return readHashMap(loader);
1992
1993        case VAL_PARCELABLE:
1994            return readParcelable(loader);
1995
1996        case VAL_SHORT:
1997            return (short) readInt();
1998
1999        case VAL_LONG:
2000            return readLong();
2001
2002        case VAL_FLOAT:
2003            return readFloat();
2004
2005        case VAL_DOUBLE:
2006            return readDouble();
2007
2008        case VAL_BOOLEAN:
2009            return readInt() == 1;
2010
2011        case VAL_CHARSEQUENCE:
2012            return readCharSequence();
2013
2014        case VAL_LIST:
2015            return readArrayList(loader);
2016
2017        case VAL_BOOLEANARRAY:
2018            return createBooleanArray();
2019
2020        case VAL_BYTEARRAY:
2021            return createByteArray();
2022
2023        case VAL_STRINGARRAY:
2024            return readStringArray();
2025
2026        case VAL_CHARSEQUENCEARRAY:
2027            return readCharSequenceArray();
2028
2029        case VAL_IBINDER:
2030            return readStrongBinder();
2031
2032        case VAL_OBJECTARRAY:
2033            return readArray(loader);
2034
2035        case VAL_INTARRAY:
2036            return createIntArray();
2037
2038        case VAL_LONGARRAY:
2039            return createLongArray();
2040
2041        case VAL_BYTE:
2042            return readByte();
2043
2044        case VAL_SERIALIZABLE:
2045            return readSerializable();
2046
2047        case VAL_PARCELABLEARRAY:
2048            return readParcelableArray(loader);
2049
2050        case VAL_SPARSEARRAY:
2051            return readSparseArray(loader);
2052
2053        case VAL_SPARSEBOOLEANARRAY:
2054            return readSparseBooleanArray();
2055
2056        case VAL_BUNDLE:
2057            return readBundle(loader); // loading will be deferred
2058
2059        default:
2060            int off = dataPosition() - 4;
2061            throw new RuntimeException(
2062                "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
2063        }
2064    }
2065
2066    /**
2067     * Read and return a new Parcelable from the parcel.  The given class loader
2068     * will be used to load any enclosed Parcelables.  If it is null, the default
2069     * class loader will be used.
2070     * @param loader A ClassLoader from which to instantiate the Parcelable
2071     * object, or null for the default class loader.
2072     * @return Returns the newly created Parcelable, or null if a null
2073     * object has been written.
2074     * @throws BadParcelableException Throws BadParcelableException if there
2075     * was an error trying to instantiate the Parcelable.
2076     */
2077    public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
2078        Parcelable.Creator<T> creator = readParcelableCreator(loader);
2079        if (creator == null) {
2080            return null;
2081        }
2082        if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2083            return ((Parcelable.ClassLoaderCreator<T>)creator).createFromParcel(this, loader);
2084        }
2085        return creator.createFromParcel(this);
2086    }
2087
2088    /** @hide */
2089    public final <T extends Parcelable> T readCreator(Parcelable.Creator<T> creator,
2090            ClassLoader loader) {
2091        if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2092            return ((Parcelable.ClassLoaderCreator<T>)creator).createFromParcel(this, loader);
2093        }
2094        return creator.createFromParcel(this);
2095    }
2096
2097    /** @hide */
2098    public final <T extends Parcelable> Parcelable.Creator<T> readParcelableCreator(
2099            ClassLoader loader) {
2100        String name = readString();
2101        if (name == null) {
2102            return null;
2103        }
2104        Parcelable.Creator<T> creator;
2105        synchronized (mCreators) {
2106            HashMap<String,Parcelable.Creator> map = mCreators.get(loader);
2107            if (map == null) {
2108                map = new HashMap<String,Parcelable.Creator>();
2109                mCreators.put(loader, map);
2110            }
2111            creator = map.get(name);
2112            if (creator == null) {
2113                try {
2114                    Class c = loader == null ?
2115                        Class.forName(name) : Class.forName(name, true, loader);
2116                    Field f = c.getField("CREATOR");
2117                    creator = (Parcelable.Creator)f.get(null);
2118                }
2119                catch (IllegalAccessException e) {
2120                    Log.e(TAG, "Illegal access when unmarshalling: "
2121                                        + name, e);
2122                    throw new BadParcelableException(
2123                            "IllegalAccessException when unmarshalling: " + name);
2124                }
2125                catch (ClassNotFoundException e) {
2126                    Log.e(TAG, "Class not found when unmarshalling: "
2127                                        + name, e);
2128                    throw new BadParcelableException(
2129                            "ClassNotFoundException when unmarshalling: " + name);
2130                }
2131                catch (ClassCastException e) {
2132                    throw new BadParcelableException("Parcelable protocol requires a "
2133                                        + "Parcelable.Creator object called "
2134                                        + " CREATOR on class " + name);
2135                }
2136                catch (NoSuchFieldException e) {
2137                    throw new BadParcelableException("Parcelable protocol requires a "
2138                                        + "Parcelable.Creator object called "
2139                                        + " CREATOR on class " + name);
2140                }
2141                catch (NullPointerException e) {
2142                    throw new BadParcelableException("Parcelable protocol requires "
2143                            + "the CREATOR object to be static on class " + name);
2144                }
2145                if (creator == null) {
2146                    throw new BadParcelableException("Parcelable protocol requires a "
2147                                        + "Parcelable.Creator object called "
2148                                        + " CREATOR on class " + name);
2149                }
2150
2151                map.put(name, creator);
2152            }
2153        }
2154
2155        return creator;
2156    }
2157
2158    /**
2159     * Read and return a new Parcelable array from the parcel.
2160     * The given class loader will be used to load any enclosed
2161     * Parcelables.
2162     * @return the Parcelable array, or null if the array is null
2163     */
2164    public final Parcelable[] readParcelableArray(ClassLoader loader) {
2165        int N = readInt();
2166        if (N < 0) {
2167            return null;
2168        }
2169        Parcelable[] p = new Parcelable[N];
2170        for (int i = 0; i < N; i++) {
2171            p[i] = (Parcelable) readParcelable(loader);
2172        }
2173        return p;
2174    }
2175
2176    /**
2177     * Read and return a new Serializable object from the parcel.
2178     * @return the Serializable object, or null if the Serializable name
2179     * wasn't found in the parcel.
2180     */
2181    public final Serializable readSerializable() {
2182        String name = readString();
2183        if (name == null) {
2184            // For some reason we were unable to read the name of the Serializable (either there
2185            // is nothing left in the Parcel to read, or the next value wasn't a String), so
2186            // return null, which indicates that the name wasn't found in the parcel.
2187            return null;
2188        }
2189
2190        byte[] serializedData = createByteArray();
2191        ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
2192        try {
2193            ObjectInputStream ois = new ObjectInputStream(bais);
2194            return (Serializable) ois.readObject();
2195        } catch (IOException ioe) {
2196            throw new RuntimeException("Parcelable encountered " +
2197                "IOException reading a Serializable object (name = " + name +
2198                ")", ioe);
2199        } catch (ClassNotFoundException cnfe) {
2200            throw new RuntimeException("Parcelable encountered" +
2201                "ClassNotFoundException reading a Serializable object (name = "
2202                + name + ")", cnfe);
2203        }
2204    }
2205
2206    // Cache of previously looked up CREATOR.createFromParcel() methods for
2207    // particular classes.  Keys are the names of the classes, values are
2208    // Method objects.
2209    private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator>>
2210        mCreators = new HashMap<ClassLoader,HashMap<String,Parcelable.Creator>>();
2211
2212    static protected final Parcel obtain(int obj) {
2213        final Parcel[] pool = sHolderPool;
2214        synchronized (pool) {
2215            Parcel p;
2216            for (int i=0; i<POOL_SIZE; i++) {
2217                p = pool[i];
2218                if (p != null) {
2219                    pool[i] = null;
2220                    if (DEBUG_RECYCLE) {
2221                        p.mStack = new RuntimeException();
2222                    }
2223                    p.init(obj);
2224                    return p;
2225                }
2226            }
2227        }
2228        return new Parcel(obj);
2229    }
2230
2231    private Parcel(int nativePtr) {
2232        if (DEBUG_RECYCLE) {
2233            mStack = new RuntimeException();
2234        }
2235        //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
2236        init(nativePtr);
2237    }
2238
2239    private void init(int nativePtr) {
2240        if (nativePtr != 0) {
2241            mNativePtr = nativePtr;
2242            mOwnsNativeParcelObject = false;
2243        } else {
2244            mNativePtr = nativeCreate();
2245            mOwnsNativeParcelObject = true;
2246        }
2247    }
2248
2249    private void freeBuffer() {
2250        if (mOwnsNativeParcelObject) {
2251            nativeFreeBuffer(mNativePtr);
2252        }
2253    }
2254
2255    private void destroy() {
2256        if (mNativePtr != 0) {
2257            if (mOwnsNativeParcelObject) {
2258                nativeDestroy(mNativePtr);
2259            }
2260            mNativePtr = 0;
2261        }
2262    }
2263
2264    @Override
2265    protected void finalize() throws Throwable {
2266        if (DEBUG_RECYCLE) {
2267            if (mStack != null) {
2268                Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
2269            }
2270        }
2271        destroy();
2272    }
2273
2274    /* package */ void readMapInternal(Map outVal, int N,
2275        ClassLoader loader) {
2276        while (N > 0) {
2277            Object key = readValue(loader);
2278            Object value = readValue(loader);
2279            outVal.put(key, value);
2280            N--;
2281        }
2282    }
2283
2284    /* package */ void readArrayMapInternal(ArrayMap outVal, int N,
2285        ClassLoader loader) {
2286        while (N > 0) {
2287            Object key = readValue(loader);
2288            Object value = readValue(loader);
2289            outVal.append(key, value);
2290            N--;
2291        }
2292    }
2293
2294    private void readListInternal(List outVal, int N,
2295        ClassLoader loader) {
2296        while (N > 0) {
2297            Object value = readValue(loader);
2298            //Log.d(TAG, "Unmarshalling value=" + value);
2299            outVal.add(value);
2300            N--;
2301        }
2302    }
2303
2304    private void readArrayInternal(Object[] outVal, int N,
2305        ClassLoader loader) {
2306        for (int i = 0; i < N; i++) {
2307            Object value = readValue(loader);
2308            //Log.d(TAG, "Unmarshalling value=" + value);
2309            outVal[i] = value;
2310        }
2311    }
2312
2313    private void readSparseArrayInternal(SparseArray outVal, int N,
2314        ClassLoader loader) {
2315        while (N > 0) {
2316            int key = readInt();
2317            Object value = readValue(loader);
2318            //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
2319            outVal.append(key, value);
2320            N--;
2321        }
2322    }
2323
2324
2325    private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
2326        while (N > 0) {
2327            int key = readInt();
2328            boolean value = this.readByte() == 1;
2329            //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
2330            outVal.append(key, value);
2331            N--;
2332        }
2333    }
2334}
2335