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