OSDN Git Service

Merge "Add the new RIL requests and NetworkScanResult." am: 0727abc423 am: a37b511b67
[android-x86/frameworks-base.git] / core / java / android / os / Parcel.java
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
17 package android.os;
18
19 import android.annotation.Nullable;
20 import android.text.TextUtils;
21 import android.util.ArrayMap;
22 import android.util.ArraySet;
23 import android.util.Log;
24 import android.util.Size;
25 import android.util.SizeF;
26 import android.util.SparseArray;
27 import android.util.SparseBooleanArray;
28 import android.util.SparseIntArray;
29
30 import dalvik.annotation.optimization.FastNative;
31 import dalvik.system.VMRuntime;
32
33 import libcore.util.SneakyThrow;
34
35 import java.io.ByteArrayInputStream;
36 import java.io.ByteArrayOutputStream;
37 import java.io.FileDescriptor;
38 import java.io.FileNotFoundException;
39 import java.io.IOException;
40 import java.io.ObjectInputStream;
41 import java.io.ObjectOutputStream;
42 import java.io.ObjectStreamClass;
43 import java.io.Serializable;
44 import java.lang.reflect.Array;
45 import java.lang.reflect.Field;
46 import java.lang.reflect.Modifier;
47 import java.util.ArrayList;
48 import java.util.Arrays;
49 import java.util.HashMap;
50 import java.util.List;
51 import java.util.Map;
52 import java.util.Set;
53
54 /**
55  * Container for a message (data and object references) that can
56  * be sent through an IBinder.  A Parcel can contain both flattened data
57  * that will be unflattened on the other side of the IPC (using the various
58  * methods here for writing specific types, or the general
59  * {@link Parcelable} interface), and references to live {@link IBinder}
60  * objects that will result in the other side receiving a proxy IBinder
61  * connected with the original IBinder in the Parcel.
62  *
63  * <p class="note">Parcel is <strong>not</strong> a general-purpose
64  * serialization mechanism.  This class (and the corresponding
65  * {@link Parcelable} API for placing arbitrary objects into a Parcel) is
66  * designed as a high-performance IPC transport.  As such, it is not
67  * appropriate to place any Parcel data in to persistent storage: changes
68  * in the underlying implementation of any of the data in the Parcel can
69  * render older data unreadable.</p>
70  *
71  * <p>The bulk of the Parcel API revolves around reading and writing data
72  * of various types.  There are six major classes of such functions available.</p>
73  *
74  * <h3>Primitives</h3>
75  *
76  * <p>The most basic data functions are for writing and reading primitive
77  * data types: {@link #writeByte}, {@link #readByte}, {@link #writeDouble},
78  * {@link #readDouble}, {@link #writeFloat}, {@link #readFloat}, {@link #writeInt},
79  * {@link #readInt}, {@link #writeLong}, {@link #readLong},
80  * {@link #writeString}, {@link #readString}.  Most other
81  * data operations are built on top of these.  The given data is written and
82  * read using the endianess of the host CPU.</p>
83  *
84  * <h3>Primitive Arrays</h3>
85  *
86  * <p>There are a variety of methods for reading and writing raw arrays
87  * of primitive objects, which generally result in writing a 4-byte length
88  * followed by the primitive data items.  The methods for reading can either
89  * read the data into an existing array, or create and return a new array.
90  * These available types are:</p>
91  *
92  * <ul>
93  * <li> {@link #writeBooleanArray(boolean[])},
94  * {@link #readBooleanArray(boolean[])}, {@link #createBooleanArray()}
95  * <li> {@link #writeByteArray(byte[])},
96  * {@link #writeByteArray(byte[], int, int)}, {@link #readByteArray(byte[])},
97  * {@link #createByteArray()}
98  * <li> {@link #writeCharArray(char[])}, {@link #readCharArray(char[])},
99  * {@link #createCharArray()}
100  * <li> {@link #writeDoubleArray(double[])}, {@link #readDoubleArray(double[])},
101  * {@link #createDoubleArray()}
102  * <li> {@link #writeFloatArray(float[])}, {@link #readFloatArray(float[])},
103  * {@link #createFloatArray()}
104  * <li> {@link #writeIntArray(int[])}, {@link #readIntArray(int[])},
105  * {@link #createIntArray()}
106  * <li> {@link #writeLongArray(long[])}, {@link #readLongArray(long[])},
107  * {@link #createLongArray()}
108  * <li> {@link #writeStringArray(String[])}, {@link #readStringArray(String[])},
109  * {@link #createStringArray()}.
110  * <li> {@link #writeSparseBooleanArray(SparseBooleanArray)},
111  * {@link #readSparseBooleanArray()}.
112  * </ul>
113  *
114  * <h3>Parcelables</h3>
115  *
116  * <p>The {@link Parcelable} protocol provides an extremely efficient (but
117  * low-level) protocol for objects to write and read themselves from Parcels.
118  * You can use the direct methods {@link #writeParcelable(Parcelable, int)}
119  * and {@link #readParcelable(ClassLoader)} or
120  * {@link #writeParcelableArray} and
121  * {@link #readParcelableArray(ClassLoader)} to write or read.  These
122  * methods write both the class type and its data to the Parcel, allowing
123  * that class to be reconstructed from the appropriate class loader when
124  * later reading.</p>
125  *
126  * <p>There are also some methods that provide a more efficient way to work
127  * with Parcelables: {@link #writeTypedObject}, {@link #writeTypedArray},
128  * {@link #writeTypedList}, {@link #readTypedObject},
129  * {@link #createTypedArray} and {@link #createTypedArrayList}.  These methods
130  * do not write the class information of the original object: instead, the
131  * caller of the read function must know what type to expect and pass in the
132  * appropriate {@link Parcelable.Creator Parcelable.Creator} instead to
133  * properly construct the new object and read its data.  (To more efficient
134  * write and read a single Parceable object that is not null, you can directly
135  * call {@link Parcelable#writeToParcel Parcelable.writeToParcel} and
136  * {@link Parcelable.Creator#createFromParcel Parcelable.Creator.createFromParcel}
137  * yourself.)</p>
138  *
139  * <h3>Bundles</h3>
140  *
141  * <p>A special type-safe container, called {@link Bundle}, is available
142  * for key/value maps of heterogeneous values.  This has many optimizations
143  * for improved performance when reading and writing data, and its type-safe
144  * API avoids difficult to debug type errors when finally marshalling the
145  * data contents into a Parcel.  The methods to use are
146  * {@link #writeBundle(Bundle)}, {@link #readBundle()}, and
147  * {@link #readBundle(ClassLoader)}.
148  *
149  * <h3>Active Objects</h3>
150  *
151  * <p>An unusual feature of Parcel is the ability to read and write active
152  * objects.  For these objects the actual contents of the object is not
153  * written, rather a special token referencing the object is written.  When
154  * reading the object back from the Parcel, you do not get a new instance of
155  * the object, but rather a handle that operates on the exact same object that
156  * was originally written.  There are two forms of active objects available.</p>
157  *
158  * <p>{@link Binder} objects are a core facility of Android's general cross-process
159  * communication system.  The {@link IBinder} interface describes an abstract
160  * protocol with a Binder object.  Any such interface can be written in to
161  * a Parcel, and upon reading you will receive either the original object
162  * implementing that interface or a special proxy implementation
163  * that communicates calls back to the original object.  The methods to use are
164  * {@link #writeStrongBinder(IBinder)},
165  * {@link #writeStrongInterface(IInterface)}, {@link #readStrongBinder()},
166  * {@link #writeBinderArray(IBinder[])}, {@link #readBinderArray(IBinder[])},
167  * {@link #createBinderArray()},
168  * {@link #writeBinderList(List)}, {@link #readBinderList(List)},
169  * {@link #createBinderArrayList()}.</p>
170  *
171  * <p>FileDescriptor objects, representing raw Linux file descriptor identifiers,
172  * can be written and {@link ParcelFileDescriptor} objects returned to operate
173  * on the original file descriptor.  The returned file descriptor is a dup
174  * of the original file descriptor: the object and fd is different, but
175  * operating on the same underlying file stream, with the same position, etc.
176  * The methods to use are {@link #writeFileDescriptor(FileDescriptor)},
177  * {@link #readFileDescriptor()}.
178  *
179  * <h3>Untyped Containers</h3>
180  *
181  * <p>A final class of methods are for writing and reading standard Java
182  * containers of arbitrary types.  These all revolve around the
183  * {@link #writeValue(Object)} and {@link #readValue(ClassLoader)} methods
184  * which define the types of objects allowed.  The container methods are
185  * {@link #writeArray(Object[])}, {@link #readArray(ClassLoader)},
186  * {@link #writeList(List)}, {@link #readList(List, ClassLoader)},
187  * {@link #readArrayList(ClassLoader)},
188  * {@link #writeMap(Map)}, {@link #readMap(Map, ClassLoader)},
189  * {@link #writeSparseArray(SparseArray)},
190  * {@link #readSparseArray(ClassLoader)}.
191  */
192 public final class Parcel {
193     private static final boolean DEBUG_RECYCLE = false;
194     private static final boolean DEBUG_ARRAY_MAP = false;
195     private static final String TAG = "Parcel";
196
197     @SuppressWarnings({"UnusedDeclaration"})
198     private long mNativePtr; // used by native code
199
200     /**
201      * Flag indicating if {@link #mNativePtr} was allocated by this object,
202      * indicating that we're responsible for its lifecycle.
203      */
204     private boolean mOwnsNativeParcelObject;
205     private long mNativeSize;
206
207     private ArrayMap<Class, Object> mClassCookies;
208
209     private RuntimeException mStack;
210
211     private static final int POOL_SIZE = 6;
212     private static final Parcel[] sOwnedPool = new Parcel[POOL_SIZE];
213     private static final Parcel[] sHolderPool = new Parcel[POOL_SIZE];
214
215     // Keep in sync with frameworks/native/include/private/binder/ParcelValTypes.h.
216     private static final int VAL_NULL = -1;
217     private static final int VAL_STRING = 0;
218     private static final int VAL_INTEGER = 1;
219     private static final int VAL_MAP = 2;
220     private static final int VAL_BUNDLE = 3;
221     private static final int VAL_PARCELABLE = 4;
222     private static final int VAL_SHORT = 5;
223     private static final int VAL_LONG = 6;
224     private static final int VAL_FLOAT = 7;
225     private static final int VAL_DOUBLE = 8;
226     private static final int VAL_BOOLEAN = 9;
227     private static final int VAL_CHARSEQUENCE = 10;
228     private static final int VAL_LIST  = 11;
229     private static final int VAL_SPARSEARRAY = 12;
230     private static final int VAL_BYTEARRAY = 13;
231     private static final int VAL_STRINGARRAY = 14;
232     private static final int VAL_IBINDER = 15;
233     private static final int VAL_PARCELABLEARRAY = 16;
234     private static final int VAL_OBJECTARRAY = 17;
235     private static final int VAL_INTARRAY = 18;
236     private static final int VAL_LONGARRAY = 19;
237     private static final int VAL_BYTE = 20;
238     private static final int VAL_SERIALIZABLE = 21;
239     private static final int VAL_SPARSEBOOLEANARRAY = 22;
240     private static final int VAL_BOOLEANARRAY = 23;
241     private static final int VAL_CHARSEQUENCEARRAY = 24;
242     private static final int VAL_PERSISTABLEBUNDLE = 25;
243     private static final int VAL_SIZE = 26;
244     private static final int VAL_SIZEF = 27;
245     private static final int VAL_DOUBLEARRAY = 28;
246
247     // The initial int32 in a Binder call's reply Parcel header:
248     // Keep these in sync with libbinder's binder/Status.h.
249     private static final int EX_SECURITY = -1;
250     private static final int EX_BAD_PARCELABLE = -2;
251     private static final int EX_ILLEGAL_ARGUMENT = -3;
252     private static final int EX_NULL_POINTER = -4;
253     private static final int EX_ILLEGAL_STATE = -5;
254     private static final int EX_NETWORK_MAIN_THREAD = -6;
255     private static final int EX_UNSUPPORTED_OPERATION = -7;
256     private static final int EX_SERVICE_SPECIFIC = -8;
257     private static final int EX_PARCELABLE = -9;
258     private static final int EX_HAS_REPLY_HEADER = -128;  // special; see below
259     // EX_TRANSACTION_FAILED is used exclusively in native code.
260     // see libbinder's binder/Status.h
261     private static final int EX_TRANSACTION_FAILED = -129;
262
263     @FastNative
264     private static native int nativeDataSize(long nativePtr);
265     @FastNative
266     private static native int nativeDataAvail(long nativePtr);
267     @FastNative
268     private static native int nativeDataPosition(long nativePtr);
269     @FastNative
270     private static native int nativeDataCapacity(long nativePtr);
271     @FastNative
272     private static native long nativeSetDataSize(long nativePtr, int size);
273     @FastNative
274     private static native void nativeSetDataPosition(long nativePtr, int pos);
275     @FastNative
276     private static native void nativeSetDataCapacity(long nativePtr, int size);
277
278     @FastNative
279     private static native boolean nativePushAllowFds(long nativePtr, boolean allowFds);
280     @FastNative
281     private static native void nativeRestoreAllowFds(long nativePtr, boolean lastValue);
282
283     private static native void nativeWriteByteArray(long nativePtr, byte[] b, int offset, int len);
284     private static native void nativeWriteBlob(long nativePtr, byte[] b, int offset, int len);
285     @FastNative
286     private static native void nativeWriteInt(long nativePtr, int val);
287     @FastNative
288     private static native void nativeWriteLong(long nativePtr, long val);
289     @FastNative
290     private static native void nativeWriteFloat(long nativePtr, float val);
291     @FastNative
292     private static native void nativeWriteDouble(long nativePtr, double val);
293     private static native void nativeWriteString(long nativePtr, String val);
294     private static native void nativeWriteStrongBinder(long nativePtr, IBinder val);
295     private static native long nativeWriteFileDescriptor(long nativePtr, FileDescriptor val);
296
297     private static native byte[] nativeCreateByteArray(long nativePtr);
298     private static native byte[] nativeReadBlob(long nativePtr);
299     @FastNative
300     private static native int nativeReadInt(long nativePtr);
301     @FastNative
302     private static native long nativeReadLong(long nativePtr);
303     @FastNative
304     private static native float nativeReadFloat(long nativePtr);
305     @FastNative
306     private static native double nativeReadDouble(long nativePtr);
307     private static native String nativeReadString(long nativePtr);
308     private static native IBinder nativeReadStrongBinder(long nativePtr);
309     private static native FileDescriptor nativeReadFileDescriptor(long nativePtr);
310
311     private static native long nativeCreate();
312     private static native long nativeFreeBuffer(long nativePtr);
313     private static native void nativeDestroy(long nativePtr);
314
315     private static native byte[] nativeMarshall(long nativePtr);
316     private static native long nativeUnmarshall(
317             long nativePtr, byte[] data, int offset, int length);
318     private static native int nativeCompareData(long thisNativePtr, long otherNativePtr);
319     private static native long nativeAppendFrom(
320             long thisNativePtr, long otherNativePtr, int offset, int length);
321     @FastNative
322     private static native boolean nativeHasFileDescriptors(long nativePtr);
323     private static native void nativeWriteInterfaceToken(long nativePtr, String interfaceName);
324     private static native void nativeEnforceInterface(long nativePtr, String interfaceName);
325
326     private static native long nativeGetBlobAshmemSize(long nativePtr);
327
328     public final static Parcelable.Creator<String> STRING_CREATOR
329              = new Parcelable.Creator<String>() {
330         public String createFromParcel(Parcel source) {
331             return source.readString();
332         }
333         public String[] newArray(int size) {
334             return new String[size];
335         }
336     };
337
338     /**
339      * Retrieve a new Parcel object from the pool.
340      */
341     public static Parcel obtain() {
342         final Parcel[] pool = sOwnedPool;
343         synchronized (pool) {
344             Parcel p;
345             for (int i=0; i<POOL_SIZE; i++) {
346                 p = pool[i];
347                 if (p != null) {
348                     pool[i] = null;
349                     if (DEBUG_RECYCLE) {
350                         p.mStack = new RuntimeException();
351                     }
352                     return p;
353                 }
354             }
355         }
356         return new Parcel(0);
357     }
358
359     /**
360      * Put a Parcel object back into the pool.  You must not touch
361      * the object after this call.
362      */
363     public final void recycle() {
364         if (DEBUG_RECYCLE) mStack = null;
365         freeBuffer();
366
367         final Parcel[] pool;
368         if (mOwnsNativeParcelObject) {
369             pool = sOwnedPool;
370         } else {
371             mNativePtr = 0;
372             pool = sHolderPool;
373         }
374
375         synchronized (pool) {
376             for (int i=0; i<POOL_SIZE; i++) {
377                 if (pool[i] == null) {
378                     pool[i] = this;
379                     return;
380                 }
381             }
382         }
383     }
384
385     /** @hide */
386     public static native long getGlobalAllocSize();
387
388     /** @hide */
389     public static native long getGlobalAllocCount();
390
391     /**
392      * Returns the total amount of data contained in the parcel.
393      */
394     public final int dataSize() {
395         return nativeDataSize(mNativePtr);
396     }
397
398     /**
399      * Returns the amount of data remaining to be read from the
400      * parcel.  That is, {@link #dataSize}-{@link #dataPosition}.
401      */
402     public final int dataAvail() {
403         return nativeDataAvail(mNativePtr);
404     }
405
406     /**
407      * Returns the current position in the parcel data.  Never
408      * more than {@link #dataSize}.
409      */
410     public final int dataPosition() {
411         return nativeDataPosition(mNativePtr);
412     }
413
414     /**
415      * Returns the total amount of space in the parcel.  This is always
416      * >= {@link #dataSize}.  The difference between it and dataSize() is the
417      * amount of room left until the parcel needs to re-allocate its
418      * data buffer.
419      */
420     public final int dataCapacity() {
421         return nativeDataCapacity(mNativePtr);
422     }
423
424     /**
425      * Change the amount of data in the parcel.  Can be either smaller or
426      * larger than the current size.  If larger than the current capacity,
427      * more memory will be allocated.
428      *
429      * @param size The new number of bytes in the Parcel.
430      */
431     public final void setDataSize(int size) {
432         // STOPSHIP: Try/catch for exception is for temporary debug. Remove once bug resolved
433         try {
434             updateNativeSize(nativeSetDataSize(mNativePtr, size));
435         } catch (IllegalArgumentException iae) {
436             Log.e(TAG,"Caught Exception representing a known bug in Parcel",iae);
437             Log.wtfStack(TAG, "This flow is using SetDataSize incorrectly");
438         }
439     }
440
441     /**
442      * Move the current read/write position in the parcel.
443      * @param pos New offset in the parcel; must be between 0 and
444      * {@link #dataSize}.
445      */
446     public final void setDataPosition(int pos) {
447         nativeSetDataPosition(mNativePtr, pos);
448     }
449
450     /**
451      * Change the capacity (current available space) of the parcel.
452      *
453      * @param size The new capacity of the parcel, in bytes.  Can not be
454      * less than {@link #dataSize} -- that is, you can not drop existing data
455      * with this method.
456      */
457     public final void setDataCapacity(int size) {
458         nativeSetDataCapacity(mNativePtr, size);
459     }
460
461     /** @hide */
462     public final boolean pushAllowFds(boolean allowFds) {
463         return nativePushAllowFds(mNativePtr, allowFds);
464     }
465
466     /** @hide */
467     public final void restoreAllowFds(boolean lastValue) {
468         nativeRestoreAllowFds(mNativePtr, lastValue);
469     }
470
471     /**
472      * Returns the raw bytes of the parcel.
473      *
474      * <p class="note">The data you retrieve here <strong>must not</strong>
475      * be placed in any kind of persistent storage (on local disk, across
476      * a network, etc).  For that, you should use standard serialization
477      * or another kind of general serialization mechanism.  The Parcel
478      * marshalled representation is highly optimized for local IPC, and as
479      * such does not attempt to maintain compatibility with data created
480      * in different versions of the platform.
481      */
482     public final byte[] marshall() {
483         return nativeMarshall(mNativePtr);
484     }
485
486     /**
487      * Set the bytes in data to be the raw bytes of this Parcel.
488      */
489     public final void unmarshall(byte[] data, int offset, int length) {
490         updateNativeSize(nativeUnmarshall(mNativePtr, data, offset, length));
491     }
492
493     public final void appendFrom(Parcel parcel, int offset, int length) {
494         updateNativeSize(nativeAppendFrom(mNativePtr, parcel.mNativePtr, offset, length));
495     }
496
497     /** @hide */
498     public final int compareData(Parcel other) {
499         return nativeCompareData(mNativePtr, other.mNativePtr);
500     }
501
502     /** @hide */
503     public final void setClassCookie(Class clz, Object cookie) {
504         if (mClassCookies == null) {
505             mClassCookies = new ArrayMap<>();
506         }
507         mClassCookies.put(clz, cookie);
508     }
509
510     /** @hide */
511     public final Object getClassCookie(Class clz) {
512         return mClassCookies != null ? mClassCookies.get(clz) : null;
513     }
514
515     /** @hide */
516     public final void adoptClassCookies(Parcel from) {
517         mClassCookies = from.mClassCookies;
518     }
519
520     /**
521      * Report whether the parcel contains any marshalled file descriptors.
522      */
523     public final boolean hasFileDescriptors() {
524         return nativeHasFileDescriptors(mNativePtr);
525     }
526
527     /**
528      * Store or read an IBinder interface token in the parcel at the current
529      * {@link #dataPosition}.  This is used to validate that the marshalled
530      * transaction is intended for the target interface.
531      */
532     public final void writeInterfaceToken(String interfaceName) {
533         nativeWriteInterfaceToken(mNativePtr, interfaceName);
534     }
535
536     public final void enforceInterface(String interfaceName) {
537         nativeEnforceInterface(mNativePtr, interfaceName);
538     }
539
540     /**
541      * Write a byte array into the parcel at the current {@link #dataPosition},
542      * growing {@link #dataCapacity} if needed.
543      * @param b Bytes to place into the parcel.
544      */
545     public final void writeByteArray(byte[] b) {
546         writeByteArray(b, 0, (b != null) ? b.length : 0);
547     }
548
549     /**
550      * Write a byte array into the parcel at the current {@link #dataPosition},
551      * growing {@link #dataCapacity} if needed.
552      * @param b Bytes to place into the parcel.
553      * @param offset Index of first byte to be written.
554      * @param len Number of bytes to write.
555      */
556     public final void writeByteArray(byte[] b, int offset, int len) {
557         if (b == null) {
558             writeInt(-1);
559             return;
560         }
561         Arrays.checkOffsetAndCount(b.length, offset, len);
562         nativeWriteByteArray(mNativePtr, b, offset, len);
563     }
564
565     /**
566      * Write a blob of data into the parcel at the current {@link #dataPosition},
567      * growing {@link #dataCapacity} if needed.
568      * @param b Bytes to place into the parcel.
569      * {@hide}
570      * {@SystemApi}
571      */
572     public final void writeBlob(byte[] b) {
573         writeBlob(b, 0, (b != null) ? b.length : 0);
574     }
575
576     /**
577      * Write a blob of data into the parcel at the current {@link #dataPosition},
578      * growing {@link #dataCapacity} if needed.
579      * @param b Bytes to place into the parcel.
580      * @param offset Index of first byte to be written.
581      * @param len Number of bytes to write.
582      * {@hide}
583      * {@SystemApi}
584      */
585     public final void writeBlob(byte[] b, int offset, int len) {
586         if (b == null) {
587             writeInt(-1);
588             return;
589         }
590         Arrays.checkOffsetAndCount(b.length, offset, len);
591         nativeWriteBlob(mNativePtr, b, offset, len);
592     }
593
594     /**
595      * Write an integer value into the parcel at the current dataPosition(),
596      * growing dataCapacity() if needed.
597      */
598     public final void writeInt(int val) {
599         nativeWriteInt(mNativePtr, val);
600     }
601
602     /**
603      * Write a long integer value into the parcel at the current dataPosition(),
604      * growing dataCapacity() if needed.
605      */
606     public final void writeLong(long val) {
607         nativeWriteLong(mNativePtr, val);
608     }
609
610     /**
611      * Write a floating point value into the parcel at the current
612      * dataPosition(), growing dataCapacity() if needed.
613      */
614     public final void writeFloat(float val) {
615         nativeWriteFloat(mNativePtr, val);
616     }
617
618     /**
619      * Write a double precision floating point value into the parcel at the
620      * current dataPosition(), growing dataCapacity() if needed.
621      */
622     public final void writeDouble(double val) {
623         nativeWriteDouble(mNativePtr, val);
624     }
625
626     /**
627      * Write a string value into the parcel at the current dataPosition(),
628      * growing dataCapacity() if needed.
629      */
630     public final void writeString(String val) {
631         nativeWriteString(mNativePtr, val);
632     }
633
634     /** @hide */
635     public final void writeBoolean(boolean val) {
636         writeInt(val ? 1 : 0);
637     }
638
639     /**
640      * Write a CharSequence value into the parcel at the current dataPosition(),
641      * growing dataCapacity() if needed.
642      * @hide
643      */
644     public final void writeCharSequence(CharSequence val) {
645         TextUtils.writeToParcel(val, this, 0);
646     }
647
648     /**
649      * Write an object into the parcel at the current dataPosition(),
650      * growing dataCapacity() if needed.
651      */
652     public final void writeStrongBinder(IBinder val) {
653         nativeWriteStrongBinder(mNativePtr, val);
654     }
655
656     /**
657      * Write an object into the parcel at the current dataPosition(),
658      * growing dataCapacity() if needed.
659      */
660     public final void writeStrongInterface(IInterface val) {
661         writeStrongBinder(val == null ? null : val.asBinder());
662     }
663
664     /**
665      * Write a FileDescriptor into the parcel at the current dataPosition(),
666      * growing dataCapacity() if needed.
667      *
668      * <p class="caution">The file descriptor will not be closed, which may
669      * result in file descriptor leaks when objects are returned from Binder
670      * calls.  Use {@link ParcelFileDescriptor#writeToParcel} instead, which
671      * accepts contextual flags and will close the original file descriptor
672      * if {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set.</p>
673      */
674     public final void writeFileDescriptor(FileDescriptor val) {
675         updateNativeSize(nativeWriteFileDescriptor(mNativePtr, val));
676     }
677
678     private void updateNativeSize(long newNativeSize) {
679         if (mOwnsNativeParcelObject) {
680             if (newNativeSize > Integer.MAX_VALUE) {
681                 newNativeSize = Integer.MAX_VALUE;
682             }
683             if (newNativeSize != mNativeSize) {
684                 int delta = (int) (newNativeSize - mNativeSize);
685                 if (delta > 0) {
686                     VMRuntime.getRuntime().registerNativeAllocation(delta);
687                 } else {
688                     VMRuntime.getRuntime().registerNativeFree(-delta);
689                 }
690                 mNativeSize = newNativeSize;
691             }
692         }
693     }
694
695     /**
696      * {@hide}
697      * This will be the new name for writeFileDescriptor, for consistency.
698      **/
699     public final void writeRawFileDescriptor(FileDescriptor val) {
700         nativeWriteFileDescriptor(mNativePtr, val);
701     }
702
703     /**
704      * {@hide}
705      * Write an array of FileDescriptor objects into the Parcel.
706      *
707      * @param value The array of objects to be written.
708      */
709     public final void writeRawFileDescriptorArray(FileDescriptor[] value) {
710         if (value != null) {
711             int N = value.length;
712             writeInt(N);
713             for (int i=0; i<N; i++) {
714                 writeRawFileDescriptor(value[i]);
715             }
716         } else {
717             writeInt(-1);
718         }
719     }
720
721     /**
722      * Write a byte value into the parcel at the current dataPosition(),
723      * growing dataCapacity() if needed.
724      */
725     public final void writeByte(byte val) {
726         writeInt(val);
727     }
728
729     /**
730      * Please use {@link #writeBundle} instead.  Flattens a Map into the parcel
731      * at the current dataPosition(),
732      * growing dataCapacity() if needed.  The Map keys must be String objects.
733      * The Map values are written using {@link #writeValue} and must follow
734      * the specification there.
735      *
736      * <p>It is strongly recommended to use {@link #writeBundle} instead of
737      * this method, since the Bundle class provides a type-safe API that
738      * allows you to avoid mysterious type errors at the point of marshalling.
739      */
740     public final void writeMap(Map val) {
741         writeMapInternal((Map<String, Object>) val);
742     }
743
744     /**
745      * Flatten a Map into the parcel at the current dataPosition(),
746      * growing dataCapacity() if needed.  The Map keys must be String objects.
747      */
748     /* package */ void writeMapInternal(Map<String,Object> val) {
749         if (val == null) {
750             writeInt(-1);
751             return;
752         }
753         Set<Map.Entry<String,Object>> entries = val.entrySet();
754         writeInt(entries.size());
755         for (Map.Entry<String,Object> e : entries) {
756             writeValue(e.getKey());
757             writeValue(e.getValue());
758         }
759     }
760
761     /**
762      * Flatten an ArrayMap into the parcel at the current dataPosition(),
763      * growing dataCapacity() if needed.  The Map keys must be String objects.
764      */
765     /* package */ void writeArrayMapInternal(ArrayMap<String, Object> val) {
766         if (val == null) {
767             writeInt(-1);
768             return;
769         }
770         // Keep the format of this Parcel in sync with writeToParcelInner() in
771         // frameworks/native/libs/binder/PersistableBundle.cpp.
772         final int N = val.size();
773         writeInt(N);
774         if (DEBUG_ARRAY_MAP) {
775             RuntimeException here =  new RuntimeException("here");
776             here.fillInStackTrace();
777             Log.d(TAG, "Writing " + N + " ArrayMap entries", here);
778         }
779         int startPos;
780         for (int i=0; i<N; i++) {
781             if (DEBUG_ARRAY_MAP) startPos = dataPosition();
782             writeString(val.keyAt(i));
783             writeValue(val.valueAt(i));
784             if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Write #" + i + " "
785                     + (dataPosition()-startPos) + " bytes: key=0x"
786                     + Integer.toHexString(val.keyAt(i) != null ? val.keyAt(i).hashCode() : 0)
787                     + " " + val.keyAt(i));
788         }
789     }
790
791     /**
792      * @hide For testing only.
793      */
794     public void writeArrayMap(ArrayMap<String, Object> val) {
795         writeArrayMapInternal(val);
796     }
797
798     /**
799      * Write an array set to the parcel.
800      *
801      * @param val The array set to write.
802      *
803      * @hide
804      */
805     public void writeArraySet(@Nullable ArraySet<? extends Object> val) {
806         final int size = (val != null) ? val.size() : -1;
807         writeInt(size);
808         for (int i = 0; i < size; i++) {
809             writeValue(val.valueAt(i));
810         }
811     }
812
813     /**
814      * Flatten a Bundle into the parcel at the current dataPosition(),
815      * growing dataCapacity() if needed.
816      */
817     public final void writeBundle(Bundle val) {
818         if (val == null) {
819             writeInt(-1);
820             return;
821         }
822
823         val.writeToParcel(this, 0);
824     }
825
826     /**
827      * Flatten a PersistableBundle into the parcel at the current dataPosition(),
828      * growing dataCapacity() if needed.
829      */
830     public final void writePersistableBundle(PersistableBundle val) {
831         if (val == null) {
832             writeInt(-1);
833             return;
834         }
835
836         val.writeToParcel(this, 0);
837     }
838
839     /**
840      * Flatten a Size into the parcel at the current dataPosition(),
841      * growing dataCapacity() if needed.
842      */
843     public final void writeSize(Size val) {
844         writeInt(val.getWidth());
845         writeInt(val.getHeight());
846     }
847
848     /**
849      * Flatten a SizeF into the parcel at the current dataPosition(),
850      * growing dataCapacity() if needed.
851      */
852     public final void writeSizeF(SizeF val) {
853         writeFloat(val.getWidth());
854         writeFloat(val.getHeight());
855     }
856
857     /**
858      * Flatten a List into the parcel at the current dataPosition(), growing
859      * dataCapacity() if needed.  The List values are written using
860      * {@link #writeValue} and must follow the specification there.
861      */
862     public final void writeList(List val) {
863         if (val == null) {
864             writeInt(-1);
865             return;
866         }
867         int N = val.size();
868         int i=0;
869         writeInt(N);
870         while (i < N) {
871             writeValue(val.get(i));
872             i++;
873         }
874     }
875
876     /**
877      * Flatten an Object array into the parcel at the current dataPosition(),
878      * growing dataCapacity() if needed.  The array values are written using
879      * {@link #writeValue} and must follow the specification there.
880      */
881     public final void writeArray(Object[] val) {
882         if (val == null) {
883             writeInt(-1);
884             return;
885         }
886         int N = val.length;
887         int i=0;
888         writeInt(N);
889         while (i < N) {
890             writeValue(val[i]);
891             i++;
892         }
893     }
894
895     /**
896      * Flatten a generic SparseArray into the parcel at the current
897      * dataPosition(), growing dataCapacity() if needed.  The SparseArray
898      * values are written using {@link #writeValue} and must follow the
899      * specification there.
900      */
901     public final void writeSparseArray(SparseArray<Object> val) {
902         if (val == null) {
903             writeInt(-1);
904             return;
905         }
906         int N = val.size();
907         writeInt(N);
908         int i=0;
909         while (i < N) {
910             writeInt(val.keyAt(i));
911             writeValue(val.valueAt(i));
912             i++;
913         }
914     }
915
916     public final void writeSparseBooleanArray(SparseBooleanArray val) {
917         if (val == null) {
918             writeInt(-1);
919             return;
920         }
921         int N = val.size();
922         writeInt(N);
923         int i=0;
924         while (i < N) {
925             writeInt(val.keyAt(i));
926             writeByte((byte)(val.valueAt(i) ? 1 : 0));
927             i++;
928         }
929     }
930
931     /**
932      * @hide
933      */
934     public final void writeSparseIntArray(SparseIntArray val) {
935         if (val == null) {
936             writeInt(-1);
937             return;
938         }
939         int N = val.size();
940         writeInt(N);
941         int i=0;
942         while (i < N) {
943             writeInt(val.keyAt(i));
944             writeInt(val.valueAt(i));
945             i++;
946         }
947     }
948
949     public final void writeBooleanArray(boolean[] val) {
950         if (val != null) {
951             int N = val.length;
952             writeInt(N);
953             for (int i=0; i<N; i++) {
954                 writeInt(val[i] ? 1 : 0);
955             }
956         } else {
957             writeInt(-1);
958         }
959     }
960
961     public final boolean[] createBooleanArray() {
962         int N = readInt();
963         // >>2 as a fast divide-by-4 works in the create*Array() functions
964         // because dataAvail() will never return a negative number.  4 is
965         // the size of a stored boolean in the stream.
966         if (N >= 0 && N <= (dataAvail() >> 2)) {
967             boolean[] val = new boolean[N];
968             for (int i=0; i<N; i++) {
969                 val[i] = readInt() != 0;
970             }
971             return val;
972         } else {
973             return null;
974         }
975     }
976
977     public final void readBooleanArray(boolean[] val) {
978         int N = readInt();
979         if (N == val.length) {
980             for (int i=0; i<N; i++) {
981                 val[i] = readInt() != 0;
982             }
983         } else {
984             throw new RuntimeException("bad array lengths");
985         }
986     }
987
988     public final void writeCharArray(char[] val) {
989         if (val != null) {
990             int N = val.length;
991             writeInt(N);
992             for (int i=0; i<N; i++) {
993                 writeInt((int)val[i]);
994             }
995         } else {
996             writeInt(-1);
997         }
998     }
999
1000     public final char[] createCharArray() {
1001         int N = readInt();
1002         if (N >= 0 && N <= (dataAvail() >> 2)) {
1003             char[] val = new char[N];
1004             for (int i=0; i<N; i++) {
1005                 val[i] = (char)readInt();
1006             }
1007             return val;
1008         } else {
1009             return null;
1010         }
1011     }
1012
1013     public final void readCharArray(char[] val) {
1014         int N = readInt();
1015         if (N == val.length) {
1016             for (int i=0; i<N; i++) {
1017                 val[i] = (char)readInt();
1018             }
1019         } else {
1020             throw new RuntimeException("bad array lengths");
1021         }
1022     }
1023
1024     public final void writeIntArray(int[] val) {
1025         if (val != null) {
1026             int N = val.length;
1027             writeInt(N);
1028             for (int i=0; i<N; i++) {
1029                 writeInt(val[i]);
1030             }
1031         } else {
1032             writeInt(-1);
1033         }
1034     }
1035
1036     public final int[] createIntArray() {
1037         int N = readInt();
1038         if (N >= 0 && N <= (dataAvail() >> 2)) {
1039             int[] val = new int[N];
1040             for (int i=0; i<N; i++) {
1041                 val[i] = readInt();
1042             }
1043             return val;
1044         } else {
1045             return null;
1046         }
1047     }
1048
1049     public final void readIntArray(int[] val) {
1050         int N = readInt();
1051         if (N == val.length) {
1052             for (int i=0; i<N; i++) {
1053                 val[i] = readInt();
1054             }
1055         } else {
1056             throw new RuntimeException("bad array lengths");
1057         }
1058     }
1059
1060     public final void writeLongArray(long[] val) {
1061         if (val != null) {
1062             int N = val.length;
1063             writeInt(N);
1064             for (int i=0; i<N; i++) {
1065                 writeLong(val[i]);
1066             }
1067         } else {
1068             writeInt(-1);
1069         }
1070     }
1071
1072     public final long[] createLongArray() {
1073         int N = readInt();
1074         // >>3 because stored longs are 64 bits
1075         if (N >= 0 && N <= (dataAvail() >> 3)) {
1076             long[] val = new long[N];
1077             for (int i=0; i<N; i++) {
1078                 val[i] = readLong();
1079             }
1080             return val;
1081         } else {
1082             return null;
1083         }
1084     }
1085
1086     public final void readLongArray(long[] val) {
1087         int N = readInt();
1088         if (N == val.length) {
1089             for (int i=0; i<N; i++) {
1090                 val[i] = readLong();
1091             }
1092         } else {
1093             throw new RuntimeException("bad array lengths");
1094         }
1095     }
1096
1097     public final void writeFloatArray(float[] val) {
1098         if (val != null) {
1099             int N = val.length;
1100             writeInt(N);
1101             for (int i=0; i<N; i++) {
1102                 writeFloat(val[i]);
1103             }
1104         } else {
1105             writeInt(-1);
1106         }
1107     }
1108
1109     public final float[] createFloatArray() {
1110         int N = readInt();
1111         // >>2 because stored floats are 4 bytes
1112         if (N >= 0 && N <= (dataAvail() >> 2)) {
1113             float[] val = new float[N];
1114             for (int i=0; i<N; i++) {
1115                 val[i] = readFloat();
1116             }
1117             return val;
1118         } else {
1119             return null;
1120         }
1121     }
1122
1123     public final void readFloatArray(float[] val) {
1124         int N = readInt();
1125         if (N == val.length) {
1126             for (int i=0; i<N; i++) {
1127                 val[i] = readFloat();
1128             }
1129         } else {
1130             throw new RuntimeException("bad array lengths");
1131         }
1132     }
1133
1134     public final void writeDoubleArray(double[] val) {
1135         if (val != null) {
1136             int N = val.length;
1137             writeInt(N);
1138             for (int i=0; i<N; i++) {
1139                 writeDouble(val[i]);
1140             }
1141         } else {
1142             writeInt(-1);
1143         }
1144     }
1145
1146     public final double[] createDoubleArray() {
1147         int N = readInt();
1148         // >>3 because stored doubles are 8 bytes
1149         if (N >= 0 && N <= (dataAvail() >> 3)) {
1150             double[] val = new double[N];
1151             for (int i=0; i<N; i++) {
1152                 val[i] = readDouble();
1153             }
1154             return val;
1155         } else {
1156             return null;
1157         }
1158     }
1159
1160     public final void readDoubleArray(double[] val) {
1161         int N = readInt();
1162         if (N == val.length) {
1163             for (int i=0; i<N; i++) {
1164                 val[i] = readDouble();
1165             }
1166         } else {
1167             throw new RuntimeException("bad array lengths");
1168         }
1169     }
1170
1171     public final void writeStringArray(String[] val) {
1172         if (val != null) {
1173             int N = val.length;
1174             writeInt(N);
1175             for (int i=0; i<N; i++) {
1176                 writeString(val[i]);
1177             }
1178         } else {
1179             writeInt(-1);
1180         }
1181     }
1182
1183     public final String[] createStringArray() {
1184         int N = readInt();
1185         if (N >= 0) {
1186             String[] val = new String[N];
1187             for (int i=0; i<N; i++) {
1188                 val[i] = readString();
1189             }
1190             return val;
1191         } else {
1192             return null;
1193         }
1194     }
1195
1196     public final void readStringArray(String[] val) {
1197         int N = readInt();
1198         if (N == val.length) {
1199             for (int i=0; i<N; i++) {
1200                 val[i] = readString();
1201             }
1202         } else {
1203             throw new RuntimeException("bad array lengths");
1204         }
1205     }
1206
1207     public final void writeBinderArray(IBinder[] val) {
1208         if (val != null) {
1209             int N = val.length;
1210             writeInt(N);
1211             for (int i=0; i<N; i++) {
1212                 writeStrongBinder(val[i]);
1213             }
1214         } else {
1215             writeInt(-1);
1216         }
1217     }
1218
1219     /**
1220      * @hide
1221      */
1222     public final void writeCharSequenceArray(CharSequence[] val) {
1223         if (val != null) {
1224             int N = val.length;
1225             writeInt(N);
1226             for (int i=0; i<N; i++) {
1227                 writeCharSequence(val[i]);
1228             }
1229         } else {
1230             writeInt(-1);
1231         }
1232     }
1233
1234     /**
1235      * @hide
1236      */
1237     public final void writeCharSequenceList(ArrayList<CharSequence> val) {
1238         if (val != null) {
1239             int N = val.size();
1240             writeInt(N);
1241             for (int i=0; i<N; i++) {
1242                 writeCharSequence(val.get(i));
1243             }
1244         } else {
1245             writeInt(-1);
1246         }
1247     }
1248
1249     public final IBinder[] createBinderArray() {
1250         int N = readInt();
1251         if (N >= 0) {
1252             IBinder[] val = new IBinder[N];
1253             for (int i=0; i<N; i++) {
1254                 val[i] = readStrongBinder();
1255             }
1256             return val;
1257         } else {
1258             return null;
1259         }
1260     }
1261
1262     public final void readBinderArray(IBinder[] val) {
1263         int N = readInt();
1264         if (N == val.length) {
1265             for (int i=0; i<N; i++) {
1266                 val[i] = readStrongBinder();
1267             }
1268         } else {
1269             throw new RuntimeException("bad array lengths");
1270         }
1271     }
1272
1273     /**
1274      * Flatten a List containing a particular object type into the parcel, at
1275      * the current dataPosition() and growing dataCapacity() if needed.  The
1276      * type of the objects in the list must be one that implements Parcelable.
1277      * Unlike the generic writeList() method, however, only the raw data of the
1278      * objects is written and not their type, so you must use the corresponding
1279      * readTypedList() to unmarshall them.
1280      *
1281      * @param val The list of objects to be written.
1282      *
1283      * @see #createTypedArrayList
1284      * @see #readTypedList
1285      * @see Parcelable
1286      */
1287     public final <T extends Parcelable> void writeTypedList(List<T> val) {
1288         if (val == null) {
1289             writeInt(-1);
1290             return;
1291         }
1292         int N = val.size();
1293         int i=0;
1294         writeInt(N);
1295         while (i < N) {
1296             T item = val.get(i);
1297             if (item != null) {
1298                 writeInt(1);
1299                 item.writeToParcel(this, 0);
1300             } else {
1301                 writeInt(0);
1302             }
1303             i++;
1304         }
1305     }
1306
1307     /**
1308      * Flatten a List containing String objects into the parcel, at
1309      * the current dataPosition() and growing dataCapacity() if needed.  They
1310      * can later be retrieved with {@link #createStringArrayList} or
1311      * {@link #readStringList}.
1312      *
1313      * @param val The list of strings to be written.
1314      *
1315      * @see #createStringArrayList
1316      * @see #readStringList
1317      */
1318     public final void writeStringList(List<String> val) {
1319         if (val == null) {
1320             writeInt(-1);
1321             return;
1322         }
1323         int N = val.size();
1324         int i=0;
1325         writeInt(N);
1326         while (i < N) {
1327             writeString(val.get(i));
1328             i++;
1329         }
1330     }
1331
1332     /**
1333      * Flatten a List containing IBinder objects into the parcel, at
1334      * the current dataPosition() and growing dataCapacity() if needed.  They
1335      * can later be retrieved with {@link #createBinderArrayList} or
1336      * {@link #readBinderList}.
1337      *
1338      * @param val The list of strings to be written.
1339      *
1340      * @see #createBinderArrayList
1341      * @see #readBinderList
1342      */
1343     public final void writeBinderList(List<IBinder> val) {
1344         if (val == null) {
1345             writeInt(-1);
1346             return;
1347         }
1348         int N = val.size();
1349         int i=0;
1350         writeInt(N);
1351         while (i < N) {
1352             writeStrongBinder(val.get(i));
1353             i++;
1354         }
1355     }
1356
1357     /**
1358      * Flatten a {@code List} containing arbitrary {@code Parcelable} objects into this parcel
1359      * at the current position. They can later be retrieved using
1360      * {@link #readParcelableList(List, ClassLoader)} if required.
1361      *
1362      * @see #readParcelableList(List, ClassLoader)
1363      * @hide
1364      */
1365     public final <T extends Parcelable> void writeParcelableList(List<T> val, int flags) {
1366         if (val == null) {
1367             writeInt(-1);
1368             return;
1369         }
1370
1371         int N = val.size();
1372         int i=0;
1373         writeInt(N);
1374         while (i < N) {
1375             writeParcelable(val.get(i), flags);
1376             i++;
1377         }
1378     }
1379
1380     /**
1381      * Flatten a homogeneous array containing a particular object type into
1382      * the parcel, at
1383      * the current dataPosition() and growing dataCapacity() if needed.  The
1384      * type of the objects in the array must be one that implements Parcelable.
1385      * Unlike the {@link #writeParcelableArray} method, however, only the
1386      * raw data of the objects is written and not their type, so you must use
1387      * {@link #readTypedArray} with the correct corresponding
1388      * {@link Parcelable.Creator} implementation to unmarshall them.
1389      *
1390      * @param val The array of objects to be written.
1391      * @param parcelableFlags Contextual flags as per
1392      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1393      *
1394      * @see #readTypedArray
1395      * @see #writeParcelableArray
1396      * @see Parcelable.Creator
1397      */
1398     public final <T extends Parcelable> void writeTypedArray(T[] val,
1399             int parcelableFlags) {
1400         if (val != null) {
1401             int N = val.length;
1402             writeInt(N);
1403             for (int i = 0; i < N; i++) {
1404                 T item = val[i];
1405                 if (item != null) {
1406                     writeInt(1);
1407                     item.writeToParcel(this, parcelableFlags);
1408                 } else {
1409                     writeInt(0);
1410                 }
1411             }
1412         } else {
1413             writeInt(-1);
1414         }
1415     }
1416
1417     /**
1418      * Write a uniform (all items are null or the same class) array list of
1419      * parcelables.
1420      *
1421      * @param list The list to write.
1422      *
1423      * @hide
1424      */
1425     public final <T extends Parcelable> void writeTypedArrayList(@Nullable ArrayList<T> list,
1426             int parcelableFlags) {
1427         if (list != null) {
1428             int N = list.size();
1429             writeInt(N);
1430             boolean wroteCreator = false;
1431             for (int i = 0; i < N; i++) {
1432                 T item = list.get(i);
1433                 if (item != null) {
1434                     writeInt(1);
1435                     if (!wroteCreator) {
1436                         writeParcelableCreator(item);
1437                         wroteCreator = true;
1438                     }
1439                     item.writeToParcel(this, parcelableFlags);
1440                 } else {
1441                     writeInt(0);
1442                 }
1443             }
1444         } else {
1445             writeInt(-1);
1446         }
1447     }
1448
1449     /**
1450      * Reads a uniform (all items are null or the same class) array list of
1451      * parcelables.
1452      *
1453      * @return The list or null.
1454      *
1455      * @hide
1456      */
1457     public final @Nullable <T> ArrayList<T> readTypedArrayList(@Nullable ClassLoader loader) {
1458         int N = readInt();
1459         if (N <= 0) {
1460             return null;
1461         }
1462         Parcelable.Creator<?> creator = null;
1463         ArrayList<T> result = new ArrayList<T>(N);
1464         for (int i = 0; i < N; i++) {
1465             if (readInt() != 0) {
1466                 if (creator == null) {
1467                     creator = readParcelableCreator(loader);
1468                     if (creator == null) {
1469                         return null;
1470                     }
1471                 }
1472                 final T parcelable;
1473                 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
1474                     Parcelable.ClassLoaderCreator<?> classLoaderCreator =
1475                             (Parcelable.ClassLoaderCreator<?>) creator;
1476                     parcelable = (T) classLoaderCreator.createFromParcel(this, loader);
1477                 } else {
1478                     parcelable = (T) creator.createFromParcel(this);
1479                 }
1480                 result.add(parcelable);
1481             } else {
1482                 result.add(null);
1483             }
1484         }
1485         return result;
1486     }
1487
1488     /**
1489      * Write a uniform (all items are null or the same class) array set of
1490      * parcelables.
1491      *
1492      * @param set The set to write.
1493      *
1494      * @hide
1495      */
1496     public final <T extends Parcelable> void writeTypedArraySet(@Nullable ArraySet<T> set,
1497             int parcelableFlags) {
1498         if (set != null) {
1499             int N = set.size();
1500             writeInt(N);
1501             boolean wroteCreator = false;
1502             for (int i = 0; i < N; i++) {
1503                 T item = set.valueAt(i);
1504                 if (item != null) {
1505                     writeInt(1);
1506                     if (!wroteCreator) {
1507                         writeParcelableCreator(item);
1508                         wroteCreator = true;
1509                     }
1510                     item.writeToParcel(this, parcelableFlags);
1511                 } else {
1512                     writeInt(0);
1513                 }
1514             }
1515         } else {
1516             writeInt(-1);
1517         }
1518     }
1519
1520     /**
1521      * Reads a uniform (all items are null or the same class) array set of
1522      * parcelables.
1523      *
1524      * @return The set or null.
1525      *
1526      * @hide
1527      */
1528     public final @Nullable <T> ArraySet<T> readTypedArraySet(@Nullable ClassLoader loader) {
1529         int N = readInt();
1530         if (N <= 0) {
1531             return null;
1532         }
1533         Parcelable.Creator<?> creator = null;
1534         ArraySet<T> result = new ArraySet<T>(N);
1535         for (int i = 0; i < N; i++) {
1536             T parcelable = null;
1537             if (readInt() != 0) {
1538                 if (creator == null) {
1539                     creator = readParcelableCreator(loader);
1540                     if (creator == null) {
1541                         return null;
1542                     }
1543                 }
1544                 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
1545                     Parcelable.ClassLoaderCreator<?> classLoaderCreator =
1546                             (Parcelable.ClassLoaderCreator<?>) creator;
1547                     parcelable = (T) classLoaderCreator.createFromParcel(this, loader);
1548                 } else {
1549                     parcelable = (T) creator.createFromParcel(this);
1550                 }
1551             }
1552             result.append(parcelable);
1553         }
1554         return result;
1555     }
1556
1557     /**
1558      * Flatten the Parcelable object into the parcel.
1559      *
1560      * @param val The Parcelable object to be written.
1561      * @param parcelableFlags Contextual flags as per
1562      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1563      *
1564      * @see #readTypedObject
1565      */
1566     public final <T extends Parcelable> void writeTypedObject(T val, int parcelableFlags) {
1567         if (val != null) {
1568             writeInt(1);
1569             val.writeToParcel(this, parcelableFlags);
1570         } else {
1571             writeInt(0);
1572         }
1573     }
1574
1575     /**
1576      * Flatten a generic object in to a parcel.  The given Object value may
1577      * currently be one of the following types:
1578      *
1579      * <ul>
1580      * <li> null
1581      * <li> String
1582      * <li> Byte
1583      * <li> Short
1584      * <li> Integer
1585      * <li> Long
1586      * <li> Float
1587      * <li> Double
1588      * <li> Boolean
1589      * <li> String[]
1590      * <li> boolean[]
1591      * <li> byte[]
1592      * <li> int[]
1593      * <li> long[]
1594      * <li> Object[] (supporting objects of the same type defined here).
1595      * <li> {@link Bundle}
1596      * <li> Map (as supported by {@link #writeMap}).
1597      * <li> Any object that implements the {@link Parcelable} protocol.
1598      * <li> Parcelable[]
1599      * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
1600      * <li> List (as supported by {@link #writeList}).
1601      * <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}).
1602      * <li> {@link IBinder}
1603      * <li> Any object that implements Serializable (but see
1604      *      {@link #writeSerializable} for caveats).  Note that all of the
1605      *      previous types have relatively efficient implementations for
1606      *      writing to a Parcel; having to rely on the generic serialization
1607      *      approach is much less efficient and should be avoided whenever
1608      *      possible.
1609      * </ul>
1610      *
1611      * <p class="caution">{@link Parcelable} objects are written with
1612      * {@link Parcelable#writeToParcel} using contextual flags of 0.  When
1613      * serializing objects containing {@link ParcelFileDescriptor}s,
1614      * this may result in file descriptor leaks when they are returned from
1615      * Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE}
1616      * should be used).</p>
1617      */
1618     public final void writeValue(Object v) {
1619         if (v == null) {
1620             writeInt(VAL_NULL);
1621         } else if (v instanceof String) {
1622             writeInt(VAL_STRING);
1623             writeString((String) v);
1624         } else if (v instanceof Integer) {
1625             writeInt(VAL_INTEGER);
1626             writeInt((Integer) v);
1627         } else if (v instanceof Map) {
1628             writeInt(VAL_MAP);
1629             writeMap((Map) v);
1630         } else if (v instanceof Bundle) {
1631             // Must be before Parcelable
1632             writeInt(VAL_BUNDLE);
1633             writeBundle((Bundle) v);
1634         } else if (v instanceof PersistableBundle) {
1635             writeInt(VAL_PERSISTABLEBUNDLE);
1636             writePersistableBundle((PersistableBundle) v);
1637         } else if (v instanceof Parcelable) {
1638             // IMPOTANT: cases for classes that implement Parcelable must
1639             // come before the Parcelable case, so that their specific VAL_*
1640             // types will be written.
1641             writeInt(VAL_PARCELABLE);
1642             writeParcelable((Parcelable) v, 0);
1643         } else if (v instanceof Short) {
1644             writeInt(VAL_SHORT);
1645             writeInt(((Short) v).intValue());
1646         } else if (v instanceof Long) {
1647             writeInt(VAL_LONG);
1648             writeLong((Long) v);
1649         } else if (v instanceof Float) {
1650             writeInt(VAL_FLOAT);
1651             writeFloat((Float) v);
1652         } else if (v instanceof Double) {
1653             writeInt(VAL_DOUBLE);
1654             writeDouble((Double) v);
1655         } else if (v instanceof Boolean) {
1656             writeInt(VAL_BOOLEAN);
1657             writeInt((Boolean) v ? 1 : 0);
1658         } else if (v instanceof CharSequence) {
1659             // Must be after String
1660             writeInt(VAL_CHARSEQUENCE);
1661             writeCharSequence((CharSequence) v);
1662         } else if (v instanceof List) {
1663             writeInt(VAL_LIST);
1664             writeList((List) v);
1665         } else if (v instanceof SparseArray) {
1666             writeInt(VAL_SPARSEARRAY);
1667             writeSparseArray((SparseArray) v);
1668         } else if (v instanceof boolean[]) {
1669             writeInt(VAL_BOOLEANARRAY);
1670             writeBooleanArray((boolean[]) v);
1671         } else if (v instanceof byte[]) {
1672             writeInt(VAL_BYTEARRAY);
1673             writeByteArray((byte[]) v);
1674         } else if (v instanceof String[]) {
1675             writeInt(VAL_STRINGARRAY);
1676             writeStringArray((String[]) v);
1677         } else if (v instanceof CharSequence[]) {
1678             // Must be after String[] and before Object[]
1679             writeInt(VAL_CHARSEQUENCEARRAY);
1680             writeCharSequenceArray((CharSequence[]) v);
1681         } else if (v instanceof IBinder) {
1682             writeInt(VAL_IBINDER);
1683             writeStrongBinder((IBinder) v);
1684         } else if (v instanceof Parcelable[]) {
1685             writeInt(VAL_PARCELABLEARRAY);
1686             writeParcelableArray((Parcelable[]) v, 0);
1687         } else if (v instanceof int[]) {
1688             writeInt(VAL_INTARRAY);
1689             writeIntArray((int[]) v);
1690         } else if (v instanceof long[]) {
1691             writeInt(VAL_LONGARRAY);
1692             writeLongArray((long[]) v);
1693         } else if (v instanceof Byte) {
1694             writeInt(VAL_BYTE);
1695             writeInt((Byte) v);
1696         } else if (v instanceof Size) {
1697             writeInt(VAL_SIZE);
1698             writeSize((Size) v);
1699         } else if (v instanceof SizeF) {
1700             writeInt(VAL_SIZEF);
1701             writeSizeF((SizeF) v);
1702         } else if (v instanceof double[]) {
1703             writeInt(VAL_DOUBLEARRAY);
1704             writeDoubleArray((double[]) v);
1705         } else {
1706             Class<?> clazz = v.getClass();
1707             if (clazz.isArray() && clazz.getComponentType() == Object.class) {
1708                 // Only pure Object[] are written here, Other arrays of non-primitive types are
1709                 // handled by serialization as this does not record the component type.
1710                 writeInt(VAL_OBJECTARRAY);
1711                 writeArray((Object[]) v);
1712             } else if (v instanceof Serializable) {
1713                 // Must be last
1714                 writeInt(VAL_SERIALIZABLE);
1715                 writeSerializable((Serializable) v);
1716             } else {
1717                 throw new RuntimeException("Parcel: unable to marshal value " + v);
1718             }
1719         }
1720     }
1721
1722     /**
1723      * Flatten the name of the class of the Parcelable and its contents
1724      * into the parcel.
1725      *
1726      * @param p The Parcelable object to be written.
1727      * @param parcelableFlags Contextual flags as per
1728      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1729      */
1730     public final void writeParcelable(Parcelable p, int parcelableFlags) {
1731         if (p == null) {
1732             writeString(null);
1733             return;
1734         }
1735         writeParcelableCreator(p);
1736         p.writeToParcel(this, parcelableFlags);
1737     }
1738
1739     /** @hide */
1740     public final void writeParcelableCreator(Parcelable p) {
1741         String name = p.getClass().getName();
1742         writeString(name);
1743     }
1744
1745     /**
1746      * Write a generic serializable object in to a Parcel.  It is strongly
1747      * recommended that this method be avoided, since the serialization
1748      * overhead is extremely large, and this approach will be much slower than
1749      * using the other approaches to writing data in to a Parcel.
1750      */
1751     public final void writeSerializable(Serializable s) {
1752         if (s == null) {
1753             writeString(null);
1754             return;
1755         }
1756         String name = s.getClass().getName();
1757         writeString(name);
1758
1759         ByteArrayOutputStream baos = new ByteArrayOutputStream();
1760         try {
1761             ObjectOutputStream oos = new ObjectOutputStream(baos);
1762             oos.writeObject(s);
1763             oos.close();
1764
1765             writeByteArray(baos.toByteArray());
1766         } catch (IOException ioe) {
1767             throw new RuntimeException("Parcelable encountered " +
1768                 "IOException writing serializable object (name = " + name +
1769                 ")", ioe);
1770         }
1771     }
1772
1773     /**
1774      * Special function for writing an exception result at the header of
1775      * a parcel, to be used when returning an exception from a transaction.
1776      * Note that this currently only supports a few exception types; any other
1777      * exception will be re-thrown by this function as a RuntimeException
1778      * (to be caught by the system's last-resort exception handling when
1779      * dispatching a transaction).
1780      *
1781      * <p>The supported exception types are:
1782      * <ul>
1783      * <li>{@link BadParcelableException}
1784      * <li>{@link IllegalArgumentException}
1785      * <li>{@link IllegalStateException}
1786      * <li>{@link NullPointerException}
1787      * <li>{@link SecurityException}
1788      * <li>{@link NetworkOnMainThreadException}
1789      * </ul>
1790      *
1791      * @param e The Exception to be written.
1792      *
1793      * @see #writeNoException
1794      * @see #readException
1795      */
1796     public final void writeException(Exception e) {
1797         int code = 0;
1798         if (e instanceof Parcelable
1799                 && (e.getClass().getClassLoader() == Parcelable.class.getClassLoader())) {
1800             // We only send Parcelable exceptions that are in the
1801             // BootClassLoader to ensure that the receiver can unpack them
1802             code = EX_PARCELABLE;
1803         } else if (e instanceof SecurityException) {
1804             code = EX_SECURITY;
1805         } else if (e instanceof BadParcelableException) {
1806             code = EX_BAD_PARCELABLE;
1807         } else if (e instanceof IllegalArgumentException) {
1808             code = EX_ILLEGAL_ARGUMENT;
1809         } else if (e instanceof NullPointerException) {
1810             code = EX_NULL_POINTER;
1811         } else if (e instanceof IllegalStateException) {
1812             code = EX_ILLEGAL_STATE;
1813         } else if (e instanceof NetworkOnMainThreadException) {
1814             code = EX_NETWORK_MAIN_THREAD;
1815         } else if (e instanceof UnsupportedOperationException) {
1816             code = EX_UNSUPPORTED_OPERATION;
1817         } else if (e instanceof ServiceSpecificException) {
1818             code = EX_SERVICE_SPECIFIC;
1819         }
1820         writeInt(code);
1821         StrictMode.clearGatheredViolations();
1822         if (code == 0) {
1823             if (e instanceof RuntimeException) {
1824                 throw (RuntimeException) e;
1825             }
1826             throw new RuntimeException(e);
1827         }
1828         writeString(e.getMessage());
1829         switch (code) {
1830             case EX_SERVICE_SPECIFIC:
1831                 writeInt(((ServiceSpecificException) e).errorCode);
1832                 break;
1833             case EX_PARCELABLE:
1834                 // Write parceled exception prefixed by length
1835                 final int sizePosition = dataPosition();
1836                 writeInt(0);
1837                 writeParcelable((Parcelable) e, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1838                 final int payloadPosition = dataPosition();
1839                 setDataPosition(sizePosition);
1840                 writeInt(payloadPosition - sizePosition);
1841                 setDataPosition(payloadPosition);
1842                 break;
1843         }
1844     }
1845
1846     /**
1847      * Special function for writing information at the front of the Parcel
1848      * indicating that no exception occurred.
1849      *
1850      * @see #writeException
1851      * @see #readException
1852      */
1853     public final void writeNoException() {
1854         // Despite the name of this function ("write no exception"),
1855         // it should instead be thought of as "write the RPC response
1856         // header", but because this function name is written out by
1857         // the AIDL compiler, we're not going to rename it.
1858         //
1859         // The response header, in the non-exception case (see also
1860         // writeException above, also called by the AIDL compiler), is
1861         // either a 0 (the default case), or EX_HAS_REPLY_HEADER if
1862         // StrictMode has gathered up violations that have occurred
1863         // during a Binder call, in which case we write out the number
1864         // of violations and their details, serialized, before the
1865         // actual RPC respons data.  The receiving end of this is
1866         // readException(), below.
1867         if (StrictMode.hasGatheredViolations()) {
1868             writeInt(EX_HAS_REPLY_HEADER);
1869             final int sizePosition = dataPosition();
1870             writeInt(0);  // total size of fat header, to be filled in later
1871             StrictMode.writeGatheredViolationsToParcel(this);
1872             final int payloadPosition = dataPosition();
1873             setDataPosition(sizePosition);
1874             writeInt(payloadPosition - sizePosition);  // header size
1875             setDataPosition(payloadPosition);
1876         } else {
1877             writeInt(0);
1878         }
1879     }
1880
1881     /**
1882      * Special function for reading an exception result from the header of
1883      * a parcel, to be used after receiving the result of a transaction.  This
1884      * will throw the exception for you if it had been written to the Parcel,
1885      * otherwise return and let you read the normal result data from the Parcel.
1886      *
1887      * @see #writeException
1888      * @see #writeNoException
1889      */
1890     public final void readException() {
1891         int code = readExceptionCode();
1892         if (code != 0) {
1893             String msg = readString();
1894             readException(code, msg);
1895         }
1896     }
1897
1898     /**
1899      * Parses the header of a Binder call's response Parcel and
1900      * returns the exception code.  Deals with lite or fat headers.
1901      * In the common successful case, this header is generally zero.
1902      * In less common cases, it's a small negative number and will be
1903      * followed by an error string.
1904      *
1905      * This exists purely for android.database.DatabaseUtils and
1906      * insulating it from having to handle fat headers as returned by
1907      * e.g. StrictMode-induced RPC responses.
1908      *
1909      * @hide
1910      */
1911     public final int readExceptionCode() {
1912         int code = readInt();
1913         if (code == EX_HAS_REPLY_HEADER) {
1914             int headerSize = readInt();
1915             if (headerSize == 0) {
1916                 Log.e(TAG, "Unexpected zero-sized Parcel reply header.");
1917             } else {
1918                 // Currently the only thing in the header is StrictMode stacks,
1919                 // but discussions around event/RPC tracing suggest we might
1920                 // put that here too.  If so, switch on sub-header tags here.
1921                 // But for now, just parse out the StrictMode stuff.
1922                 StrictMode.readAndHandleBinderCallViolations(this);
1923             }
1924             // And fat response headers are currently only used when
1925             // there are no exceptions, so return no error:
1926             return 0;
1927         }
1928         return code;
1929     }
1930
1931     /**
1932      * Throw an exception with the given message. Not intended for use
1933      * outside the Parcel class.
1934      *
1935      * @param code Used to determine which exception class to throw.
1936      * @param msg The exception message.
1937      */
1938     public final void readException(int code, String msg) {
1939         switch (code) {
1940             case EX_PARCELABLE:
1941                 if (readInt() > 0) {
1942                     SneakyThrow.sneakyThrow(
1943                             (Exception) readParcelable(Parcelable.class.getClassLoader()));
1944                 } else {
1945                     throw new RuntimeException(msg + " [missing Parcelable]");
1946                 }
1947             case EX_SECURITY:
1948                 throw new SecurityException(msg);
1949             case EX_BAD_PARCELABLE:
1950                 throw new BadParcelableException(msg);
1951             case EX_ILLEGAL_ARGUMENT:
1952                 throw new IllegalArgumentException(msg);
1953             case EX_NULL_POINTER:
1954                 throw new NullPointerException(msg);
1955             case EX_ILLEGAL_STATE:
1956                 throw new IllegalStateException(msg);
1957             case EX_NETWORK_MAIN_THREAD:
1958                 throw new NetworkOnMainThreadException();
1959             case EX_UNSUPPORTED_OPERATION:
1960                 throw new UnsupportedOperationException(msg);
1961             case EX_SERVICE_SPECIFIC:
1962                 throw new ServiceSpecificException(readInt(), msg);
1963         }
1964         throw new RuntimeException("Unknown exception code: " + code
1965                 + " msg " + msg);
1966     }
1967
1968     /**
1969      * Read an integer value from the parcel at the current dataPosition().
1970      */
1971     public final int readInt() {
1972         return nativeReadInt(mNativePtr);
1973     }
1974
1975     /**
1976      * Read a long integer value from the parcel at the current dataPosition().
1977      */
1978     public final long readLong() {
1979         return nativeReadLong(mNativePtr);
1980     }
1981
1982     /**
1983      * Read a floating point value from the parcel at the current
1984      * dataPosition().
1985      */
1986     public final float readFloat() {
1987         return nativeReadFloat(mNativePtr);
1988     }
1989
1990     /**
1991      * Read a double precision floating point value from the parcel at the
1992      * current dataPosition().
1993      */
1994     public final double readDouble() {
1995         return nativeReadDouble(mNativePtr);
1996     }
1997
1998     /**
1999      * Read a string value from the parcel at the current dataPosition().
2000      */
2001     public final String readString() {
2002         return nativeReadString(mNativePtr);
2003     }
2004
2005     /** @hide */
2006     public final boolean readBoolean() {
2007         return readInt() != 0;
2008     }
2009
2010     /**
2011      * Read a CharSequence value from the parcel at the current dataPosition().
2012      * @hide
2013      */
2014     public final CharSequence readCharSequence() {
2015         return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
2016     }
2017
2018     /**
2019      * Read an object from the parcel at the current dataPosition().
2020      */
2021     public final IBinder readStrongBinder() {
2022         return nativeReadStrongBinder(mNativePtr);
2023     }
2024
2025     /**
2026      * Read a FileDescriptor from the parcel at the current dataPosition().
2027      */
2028     public final ParcelFileDescriptor readFileDescriptor() {
2029         FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
2030         return fd != null ? new ParcelFileDescriptor(fd) : null;
2031     }
2032
2033     /** {@hide} */
2034     public final FileDescriptor readRawFileDescriptor() {
2035         return nativeReadFileDescriptor(mNativePtr);
2036     }
2037
2038     /**
2039      * {@hide}
2040      * Read and return a new array of FileDescriptors from the parcel.
2041      * @return the FileDescriptor array, or null if the array is null.
2042      **/
2043     public final FileDescriptor[] createRawFileDescriptorArray() {
2044         int N = readInt();
2045         if (N < 0) {
2046             return null;
2047         }
2048         FileDescriptor[] f = new FileDescriptor[N];
2049         for (int i = 0; i < N; i++) {
2050             f[i] = readRawFileDescriptor();
2051         }
2052         return f;
2053     }
2054
2055     /**
2056      * {@hide}
2057      * Read an array of FileDescriptors from a parcel.
2058      * The passed array must be exactly the length of the array in the parcel.
2059      * @return the FileDescriptor array, or null if the array is null.
2060      **/
2061     public final void readRawFileDescriptorArray(FileDescriptor[] val) {
2062         int N = readInt();
2063         if (N == val.length) {
2064             for (int i=0; i<N; i++) {
2065                 val[i] = readRawFileDescriptor();
2066             }
2067         } else {
2068             throw new RuntimeException("bad array lengths");
2069         }
2070     }
2071
2072     /** @deprecated use {@link android.system.Os#open(String, int, int)} */
2073     @Deprecated
2074     static native FileDescriptor openFileDescriptor(String file, int mode)
2075             throws FileNotFoundException;
2076
2077     /** @deprecated use {@link android.system.Os#dup(FileDescriptor)} */
2078     @Deprecated
2079     static native FileDescriptor dupFileDescriptor(FileDescriptor orig) throws IOException;
2080
2081     /** @deprecated use {@link android.system.Os#close(FileDescriptor)} */
2082     @Deprecated
2083     static native void closeFileDescriptor(FileDescriptor desc) throws IOException;
2084
2085     static native void clearFileDescriptor(FileDescriptor desc);
2086
2087     /**
2088      * Read a byte value from the parcel at the current dataPosition().
2089      */
2090     public final byte readByte() {
2091         return (byte)(readInt() & 0xff);
2092     }
2093
2094     /**
2095      * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2096      * been written with {@link #writeBundle}.  Read into an existing Map object
2097      * from the parcel at the current dataPosition().
2098      */
2099     public final void readMap(Map outVal, ClassLoader loader) {
2100         int N = readInt();
2101         readMapInternal(outVal, N, loader);
2102     }
2103
2104     /**
2105      * Read into an existing List object from the parcel at the current
2106      * dataPosition(), using the given class loader to load any enclosed
2107      * Parcelables.  If it is null, the default class loader is used.
2108      */
2109     public final void readList(List outVal, ClassLoader loader) {
2110         int N = readInt();
2111         readListInternal(outVal, N, loader);
2112     }
2113
2114     /**
2115      * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2116      * been written with {@link #writeBundle}.  Read and return a new HashMap
2117      * object from the parcel at the current dataPosition(), using the given
2118      * class loader to load any enclosed Parcelables.  Returns null if
2119      * the previously written map object was null.
2120      */
2121     public final HashMap readHashMap(ClassLoader loader)
2122     {
2123         int N = readInt();
2124         if (N < 0) {
2125             return null;
2126         }
2127         HashMap m = new HashMap(N);
2128         readMapInternal(m, N, loader);
2129         return m;
2130     }
2131
2132     /**
2133      * Read and return a new Bundle object from the parcel at the current
2134      * dataPosition().  Returns null if the previously written Bundle object was
2135      * null.
2136      */
2137     public final Bundle readBundle() {
2138         return readBundle(null);
2139     }
2140
2141     /**
2142      * Read and return a new Bundle object from the parcel at the current
2143      * dataPosition(), using the given class loader to initialize the class
2144      * loader of the Bundle for later retrieval of Parcelable objects.
2145      * Returns null if the previously written Bundle object was null.
2146      */
2147     public final Bundle readBundle(ClassLoader loader) {
2148         int length = readInt();
2149         if (length < 0) {
2150             if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2151             return null;
2152         }
2153
2154         final Bundle bundle = new Bundle(this, length);
2155         if (loader != null) {
2156             bundle.setClassLoader(loader);
2157         }
2158         return bundle;
2159     }
2160
2161     /**
2162      * Read and return a new Bundle object from the parcel at the current
2163      * dataPosition().  Returns null if the previously written Bundle object was
2164      * null.
2165      */
2166     public final PersistableBundle readPersistableBundle() {
2167         return readPersistableBundle(null);
2168     }
2169
2170     /**
2171      * Read and return a new Bundle object from the parcel at the current
2172      * dataPosition(), using the given class loader to initialize the class
2173      * loader of the Bundle for later retrieval of Parcelable objects.
2174      * Returns null if the previously written Bundle object was null.
2175      */
2176     public final PersistableBundle readPersistableBundle(ClassLoader loader) {
2177         int length = readInt();
2178         if (length < 0) {
2179             if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2180             return null;
2181         }
2182
2183         final PersistableBundle bundle = new PersistableBundle(this, length);
2184         if (loader != null) {
2185             bundle.setClassLoader(loader);
2186         }
2187         return bundle;
2188     }
2189
2190     /**
2191      * Read a Size from the parcel at the current dataPosition().
2192      */
2193     public final Size readSize() {
2194         final int width = readInt();
2195         final int height = readInt();
2196         return new Size(width, height);
2197     }
2198
2199     /**
2200      * Read a SizeF from the parcel at the current dataPosition().
2201      */
2202     public final SizeF readSizeF() {
2203         final float width = readFloat();
2204         final float height = readFloat();
2205         return new SizeF(width, height);
2206     }
2207
2208     /**
2209      * Read and return a byte[] object from the parcel.
2210      */
2211     public final byte[] createByteArray() {
2212         return nativeCreateByteArray(mNativePtr);
2213     }
2214
2215     /**
2216      * Read a byte[] object from the parcel and copy it into the
2217      * given byte array.
2218      */
2219     public final void readByteArray(byte[] val) {
2220         // TODO: make this a native method to avoid the extra copy.
2221         byte[] ba = createByteArray();
2222         if (ba.length == val.length) {
2223            System.arraycopy(ba, 0, val, 0, ba.length);
2224         } else {
2225             throw new RuntimeException("bad array lengths");
2226         }
2227     }
2228
2229     /**
2230      * Read a blob of data from the parcel and return it as a byte array.
2231      * {@hide}
2232      * {@SystemApi}
2233      */
2234     public final byte[] readBlob() {
2235         return nativeReadBlob(mNativePtr);
2236     }
2237
2238     /**
2239      * Read and return a String[] object from the parcel.
2240      * {@hide}
2241      */
2242     public final String[] readStringArray() {
2243         String[] array = null;
2244
2245         int length = readInt();
2246         if (length >= 0)
2247         {
2248             array = new String[length];
2249
2250             for (int i = 0 ; i < length ; i++)
2251             {
2252                 array[i] = readString();
2253             }
2254         }
2255
2256         return array;
2257     }
2258
2259     /**
2260      * Read and return a CharSequence[] object from the parcel.
2261      * {@hide}
2262      */
2263     public final CharSequence[] readCharSequenceArray() {
2264         CharSequence[] array = null;
2265
2266         int length = readInt();
2267         if (length >= 0)
2268         {
2269             array = new CharSequence[length];
2270
2271             for (int i = 0 ; i < length ; i++)
2272             {
2273                 array[i] = readCharSequence();
2274             }
2275         }
2276
2277         return array;
2278     }
2279
2280     /**
2281      * Read and return an ArrayList&lt;CharSequence&gt; object from the parcel.
2282      * {@hide}
2283      */
2284     public final ArrayList<CharSequence> readCharSequenceList() {
2285         ArrayList<CharSequence> array = null;
2286
2287         int length = readInt();
2288         if (length >= 0) {
2289             array = new ArrayList<CharSequence>(length);
2290
2291             for (int i = 0 ; i < length ; i++) {
2292                 array.add(readCharSequence());
2293             }
2294         }
2295
2296         return array;
2297     }
2298
2299     /**
2300      * Read and return a new ArrayList object from the parcel at the current
2301      * dataPosition().  Returns null if the previously written list object was
2302      * null.  The given class loader will be used to load any enclosed
2303      * Parcelables.
2304      */
2305     public final ArrayList readArrayList(ClassLoader loader) {
2306         int N = readInt();
2307         if (N < 0) {
2308             return null;
2309         }
2310         ArrayList l = new ArrayList(N);
2311         readListInternal(l, N, loader);
2312         return l;
2313     }
2314
2315     /**
2316      * Read and return a new Object array from the parcel at the current
2317      * dataPosition().  Returns null if the previously written array was
2318      * null.  The given class loader will be used to load any enclosed
2319      * Parcelables.
2320      */
2321     public final Object[] readArray(ClassLoader loader) {
2322         int N = readInt();
2323         if (N < 0) {
2324             return null;
2325         }
2326         Object[] l = new Object[N];
2327         readArrayInternal(l, N, loader);
2328         return l;
2329     }
2330
2331     /**
2332      * Read and return a new SparseArray object from the parcel at the current
2333      * dataPosition().  Returns null if the previously written list object was
2334      * null.  The given class loader will be used to load any enclosed
2335      * Parcelables.
2336      */
2337     public final SparseArray readSparseArray(ClassLoader loader) {
2338         int N = readInt();
2339         if (N < 0) {
2340             return null;
2341         }
2342         SparseArray sa = new SparseArray(N);
2343         readSparseArrayInternal(sa, N, loader);
2344         return sa;
2345     }
2346
2347     /**
2348      * Read and return a new SparseBooleanArray object from the parcel at the current
2349      * dataPosition().  Returns null if the previously written list object was
2350      * null.
2351      */
2352     public final SparseBooleanArray readSparseBooleanArray() {
2353         int N = readInt();
2354         if (N < 0) {
2355             return null;
2356         }
2357         SparseBooleanArray sa = new SparseBooleanArray(N);
2358         readSparseBooleanArrayInternal(sa, N);
2359         return sa;
2360     }
2361
2362     /**
2363      * Read and return a new SparseIntArray object from the parcel at the current
2364      * dataPosition(). Returns null if the previously written array object was null.
2365      * @hide
2366      */
2367     public final SparseIntArray readSparseIntArray() {
2368         int N = readInt();
2369         if (N < 0) {
2370             return null;
2371         }
2372         SparseIntArray sa = new SparseIntArray(N);
2373         readSparseIntArrayInternal(sa, N);
2374         return sa;
2375     }
2376
2377     /**
2378      * Read and return a new ArrayList containing a particular object type from
2379      * the parcel that was written with {@link #writeTypedList} at the
2380      * current dataPosition().  Returns null if the
2381      * previously written list object was null.  The list <em>must</em> have
2382      * previously been written via {@link #writeTypedList} with the same object
2383      * type.
2384      *
2385      * @return A newly created ArrayList containing objects with the same data
2386      *         as those that were previously written.
2387      *
2388      * @see #writeTypedList
2389      */
2390     public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
2391         int N = readInt();
2392         if (N < 0) {
2393             return null;
2394         }
2395         ArrayList<T> l = new ArrayList<T>(N);
2396         while (N > 0) {
2397             if (readInt() != 0) {
2398                 l.add(c.createFromParcel(this));
2399             } else {
2400                 l.add(null);
2401             }
2402             N--;
2403         }
2404         return l;
2405     }
2406
2407     /**
2408      * Read into the given List items containing a particular object type
2409      * that were written with {@link #writeTypedList} at the
2410      * current dataPosition().  The list <em>must</em> have
2411      * previously been written via {@link #writeTypedList} with the same object
2412      * type.
2413      *
2414      * @return A newly created ArrayList containing objects with the same data
2415      *         as those that were previously written.
2416      *
2417      * @see #writeTypedList
2418      */
2419     public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
2420         int M = list.size();
2421         int N = readInt();
2422         int i = 0;
2423         for (; i < M && i < N; i++) {
2424             if (readInt() != 0) {
2425                 list.set(i, c.createFromParcel(this));
2426             } else {
2427                 list.set(i, null);
2428             }
2429         }
2430         for (; i<N; i++) {
2431             if (readInt() != 0) {
2432                 list.add(c.createFromParcel(this));
2433             } else {
2434                 list.add(null);
2435             }
2436         }
2437         for (; i<M; i++) {
2438             list.remove(N);
2439         }
2440     }
2441
2442     /**
2443      * Read and return a new ArrayList containing String objects from
2444      * the parcel that was written with {@link #writeStringList} at the
2445      * current dataPosition().  Returns null if the
2446      * previously written list object was null.
2447      *
2448      * @return A newly created ArrayList containing strings with the same data
2449      *         as those that were previously written.
2450      *
2451      * @see #writeStringList
2452      */
2453     public final ArrayList<String> createStringArrayList() {
2454         int N = readInt();
2455         if (N < 0) {
2456             return null;
2457         }
2458         ArrayList<String> l = new ArrayList<String>(N);
2459         while (N > 0) {
2460             l.add(readString());
2461             N--;
2462         }
2463         return l;
2464     }
2465
2466     /**
2467      * Read and return a new ArrayList containing IBinder objects from
2468      * the parcel that was written with {@link #writeBinderList} at the
2469      * current dataPosition().  Returns null if the
2470      * previously written list object was null.
2471      *
2472      * @return A newly created ArrayList containing strings with the same data
2473      *         as those that were previously written.
2474      *
2475      * @see #writeBinderList
2476      */
2477     public final ArrayList<IBinder> createBinderArrayList() {
2478         int N = readInt();
2479         if (N < 0) {
2480             return null;
2481         }
2482         ArrayList<IBinder> l = new ArrayList<IBinder>(N);
2483         while (N > 0) {
2484             l.add(readStrongBinder());
2485             N--;
2486         }
2487         return l;
2488     }
2489
2490     /**
2491      * Read into the given List items String objects that were written with
2492      * {@link #writeStringList} at the current dataPosition().
2493      *
2494      * @return A newly created ArrayList containing strings with the same data
2495      *         as those that were previously written.
2496      *
2497      * @see #writeStringList
2498      */
2499     public final void readStringList(List<String> list) {
2500         int M = list.size();
2501         int N = readInt();
2502         int i = 0;
2503         for (; i < M && i < N; i++) {
2504             list.set(i, readString());
2505         }
2506         for (; i<N; i++) {
2507             list.add(readString());
2508         }
2509         for (; i<M; i++) {
2510             list.remove(N);
2511         }
2512     }
2513
2514     /**
2515      * Read into the given List items IBinder objects that were written with
2516      * {@link #writeBinderList} at the current dataPosition().
2517      *
2518      * @see #writeBinderList
2519      */
2520     public final void readBinderList(List<IBinder> list) {
2521         int M = list.size();
2522         int N = readInt();
2523         int i = 0;
2524         for (; i < M && i < N; i++) {
2525             list.set(i, readStrongBinder());
2526         }
2527         for (; i<N; i++) {
2528             list.add(readStrongBinder());
2529         }
2530         for (; i<M; i++) {
2531             list.remove(N);
2532         }
2533     }
2534
2535     /**
2536      * Read the list of {@code Parcelable} objects at the current data position into the
2537      * given {@code list}. The contents of the {@code list} are replaced. If the serialized
2538      * list was {@code null}, {@code list} is cleared.
2539      *
2540      * @see #writeParcelableList(List, int)
2541      * @hide
2542      */
2543     public final <T extends Parcelable> List<T> readParcelableList(List<T> list, ClassLoader cl) {
2544         final int N = readInt();
2545         if (N == -1) {
2546             list.clear();
2547             return list;
2548         }
2549
2550         final int M = list.size();
2551         int i = 0;
2552         for (; i < M && i < N; i++) {
2553             list.set(i, (T) readParcelable(cl));
2554         }
2555         for (; i<N; i++) {
2556             list.add((T) readParcelable(cl));
2557         }
2558         for (; i<M; i++) {
2559             list.remove(N);
2560         }
2561         return list;
2562     }
2563
2564     /**
2565      * Read and return a new array containing a particular object type from
2566      * the parcel at the current dataPosition().  Returns null if the
2567      * previously written array was null.  The array <em>must</em> have
2568      * previously been written via {@link #writeTypedArray} with the same
2569      * object type.
2570      *
2571      * @return A newly created array containing objects with the same data
2572      *         as those that were previously written.
2573      *
2574      * @see #writeTypedArray
2575      */
2576     public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
2577         int N = readInt();
2578         if (N < 0) {
2579             return null;
2580         }
2581         T[] l = c.newArray(N);
2582         for (int i=0; i<N; i++) {
2583             if (readInt() != 0) {
2584                 l[i] = c.createFromParcel(this);
2585             }
2586         }
2587         return l;
2588     }
2589
2590     public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
2591         int N = readInt();
2592         if (N == val.length) {
2593             for (int i=0; i<N; i++) {
2594                 if (readInt() != 0) {
2595                     val[i] = c.createFromParcel(this);
2596                 } else {
2597                     val[i] = null;
2598                 }
2599             }
2600         } else {
2601             throw new RuntimeException("bad array lengths");
2602         }
2603     }
2604
2605     /**
2606      * @deprecated
2607      * @hide
2608      */
2609     @Deprecated
2610     public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
2611         return createTypedArray(c);
2612     }
2613
2614     /**
2615      * Read and return a typed Parcelable object from a parcel.
2616      * Returns null if the previous written object was null.
2617      * The object <em>must</em> have previous been written via
2618      * {@link #writeTypedObject} with the same object type.
2619      *
2620      * @return A newly created object of the type that was previously
2621      *         written.
2622      *
2623      * @see #writeTypedObject
2624      */
2625     public final <T> T readTypedObject(Parcelable.Creator<T> c) {
2626         if (readInt() != 0) {
2627             return c.createFromParcel(this);
2628         } else {
2629             return null;
2630         }
2631     }
2632
2633     /**
2634      * Write a heterogeneous array of Parcelable objects into the Parcel.
2635      * Each object in the array is written along with its class name, so
2636      * that the correct class can later be instantiated.  As a result, this
2637      * has significantly more overhead than {@link #writeTypedArray}, but will
2638      * correctly handle an array containing more than one type of object.
2639      *
2640      * @param value The array of objects to be written.
2641      * @param parcelableFlags Contextual flags as per
2642      * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2643      *
2644      * @see #writeTypedArray
2645      */
2646     public final <T extends Parcelable> void writeParcelableArray(T[] value,
2647             int parcelableFlags) {
2648         if (value != null) {
2649             int N = value.length;
2650             writeInt(N);
2651             for (int i=0; i<N; i++) {
2652                 writeParcelable(value[i], parcelableFlags);
2653             }
2654         } else {
2655             writeInt(-1);
2656         }
2657     }
2658
2659     /**
2660      * Read a typed object from a parcel.  The given class loader will be
2661      * used to load any enclosed Parcelables.  If it is null, the default class
2662      * loader will be used.
2663      */
2664     public final Object readValue(ClassLoader loader) {
2665         int type = readInt();
2666
2667         switch (type) {
2668         case VAL_NULL:
2669             return null;
2670
2671         case VAL_STRING:
2672             return readString();
2673
2674         case VAL_INTEGER:
2675             return readInt();
2676
2677         case VAL_MAP:
2678             return readHashMap(loader);
2679
2680         case VAL_PARCELABLE:
2681             return readParcelable(loader);
2682
2683         case VAL_SHORT:
2684             return (short) readInt();
2685
2686         case VAL_LONG:
2687             return readLong();
2688
2689         case VAL_FLOAT:
2690             return readFloat();
2691
2692         case VAL_DOUBLE:
2693             return readDouble();
2694
2695         case VAL_BOOLEAN:
2696             return readInt() == 1;
2697
2698         case VAL_CHARSEQUENCE:
2699             return readCharSequence();
2700
2701         case VAL_LIST:
2702             return readArrayList(loader);
2703
2704         case VAL_BOOLEANARRAY:
2705             return createBooleanArray();
2706
2707         case VAL_BYTEARRAY:
2708             return createByteArray();
2709
2710         case VAL_STRINGARRAY:
2711             return readStringArray();
2712
2713         case VAL_CHARSEQUENCEARRAY:
2714             return readCharSequenceArray();
2715
2716         case VAL_IBINDER:
2717             return readStrongBinder();
2718
2719         case VAL_OBJECTARRAY:
2720             return readArray(loader);
2721
2722         case VAL_INTARRAY:
2723             return createIntArray();
2724
2725         case VAL_LONGARRAY:
2726             return createLongArray();
2727
2728         case VAL_BYTE:
2729             return readByte();
2730
2731         case VAL_SERIALIZABLE:
2732             return readSerializable(loader);
2733
2734         case VAL_PARCELABLEARRAY:
2735             return readParcelableArray(loader);
2736
2737         case VAL_SPARSEARRAY:
2738             return readSparseArray(loader);
2739
2740         case VAL_SPARSEBOOLEANARRAY:
2741             return readSparseBooleanArray();
2742
2743         case VAL_BUNDLE:
2744             return readBundle(loader); // loading will be deferred
2745
2746         case VAL_PERSISTABLEBUNDLE:
2747             return readPersistableBundle(loader);
2748
2749         case VAL_SIZE:
2750             return readSize();
2751
2752         case VAL_SIZEF:
2753             return readSizeF();
2754
2755         case VAL_DOUBLEARRAY:
2756             return createDoubleArray();
2757
2758         default:
2759             int off = dataPosition() - 4;
2760             throw new RuntimeException(
2761                 "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
2762         }
2763     }
2764
2765     /**
2766      * Read and return a new Parcelable from the parcel.  The given class loader
2767      * will be used to load any enclosed Parcelables.  If it is null, the default
2768      * class loader will be used.
2769      * @param loader A ClassLoader from which to instantiate the Parcelable
2770      * object, or null for the default class loader.
2771      * @return Returns the newly created Parcelable, or null if a null
2772      * object has been written.
2773      * @throws BadParcelableException Throws BadParcelableException if there
2774      * was an error trying to instantiate the Parcelable.
2775      */
2776     @SuppressWarnings("unchecked")
2777     public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
2778         Parcelable.Creator<?> creator = readParcelableCreator(loader);
2779         if (creator == null) {
2780             return null;
2781         }
2782         if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2783           Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2784               (Parcelable.ClassLoaderCreator<?>) creator;
2785           return (T) classLoaderCreator.createFromParcel(this, loader);
2786         }
2787         return (T) creator.createFromParcel(this);
2788     }
2789
2790     /** @hide */
2791     @SuppressWarnings("unchecked")
2792     public final <T extends Parcelable> T readCreator(Parcelable.Creator<?> creator,
2793             ClassLoader loader) {
2794         if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2795           Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2796               (Parcelable.ClassLoaderCreator<?>) creator;
2797           return (T) classLoaderCreator.createFromParcel(this, loader);
2798         }
2799         return (T) creator.createFromParcel(this);
2800     }
2801
2802     /** @hide */
2803     public final Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) {
2804         String name = readString();
2805         if (name == null) {
2806             return null;
2807         }
2808         Parcelable.Creator<?> creator;
2809         synchronized (mCreators) {
2810             HashMap<String,Parcelable.Creator<?>> map = mCreators.get(loader);
2811             if (map == null) {
2812                 map = new HashMap<>();
2813                 mCreators.put(loader, map);
2814             }
2815             creator = map.get(name);
2816             if (creator == null) {
2817                 try {
2818                     // If loader == null, explicitly emulate Class.forName(String) "caller
2819                     // classloader" behavior.
2820                     ClassLoader parcelableClassLoader =
2821                             (loader == null ? getClass().getClassLoader() : loader);
2822                     // Avoid initializing the Parcelable class until we know it implements
2823                     // Parcelable and has the necessary CREATOR field. http://b/1171613.
2824                     Class<?> parcelableClass = Class.forName(name, false /* initialize */,
2825                             parcelableClassLoader);
2826                     if (!Parcelable.class.isAssignableFrom(parcelableClass)) {
2827                         throw new BadParcelableException("Parcelable protocol requires that the "
2828                                 + "class implements Parcelable");
2829                     }
2830                     Field f = parcelableClass.getField("CREATOR");
2831                     if ((f.getModifiers() & Modifier.STATIC) == 0) {
2832                         throw new BadParcelableException("Parcelable protocol requires "
2833                                 + "the CREATOR object to be static on class " + name);
2834                     }
2835                     Class<?> creatorType = f.getType();
2836                     if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) {
2837                         // Fail before calling Field.get(), not after, to avoid initializing
2838                         // parcelableClass unnecessarily.
2839                         throw new BadParcelableException("Parcelable protocol requires a "
2840                                 + "Parcelable.Creator object called "
2841                                 + "CREATOR on class " + name);
2842                     }
2843                     creator = (Parcelable.Creator<?>) f.get(null);
2844                 }
2845                 catch (IllegalAccessException e) {
2846                     Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
2847                     throw new BadParcelableException(
2848                             "IllegalAccessException when unmarshalling: " + name);
2849                 }
2850                 catch (ClassNotFoundException e) {
2851                     Log.e(TAG, "Class not found when unmarshalling: " + name, e);
2852                     throw new BadParcelableException(
2853                             "ClassNotFoundException when unmarshalling: " + name);
2854                 }
2855                 catch (NoSuchFieldException e) {
2856                     throw new BadParcelableException("Parcelable protocol requires a "
2857                             + "Parcelable.Creator object called "
2858                             + "CREATOR on class " + name);
2859                 }
2860                 if (creator == null) {
2861                     throw new BadParcelableException("Parcelable protocol requires a "
2862                             + "non-null Parcelable.Creator object called "
2863                             + "CREATOR on class " + name);
2864                 }
2865
2866                 map.put(name, creator);
2867             }
2868         }
2869
2870         return creator;
2871     }
2872
2873     /**
2874      * Read and return a new Parcelable array from the parcel.
2875      * The given class loader will be used to load any enclosed
2876      * Parcelables.
2877      * @return the Parcelable array, or null if the array is null
2878      */
2879     public final Parcelable[] readParcelableArray(ClassLoader loader) {
2880         int N = readInt();
2881         if (N < 0) {
2882             return null;
2883         }
2884         Parcelable[] p = new Parcelable[N];
2885         for (int i = 0; i < N; i++) {
2886             p[i] = readParcelable(loader);
2887         }
2888         return p;
2889     }
2890
2891     /** @hide */
2892     public final <T extends Parcelable> T[] readParcelableArray(ClassLoader loader,
2893             Class<T> clazz) {
2894         int N = readInt();
2895         if (N < 0) {
2896             return null;
2897         }
2898         T[] p = (T[]) Array.newInstance(clazz, N);
2899         for (int i = 0; i < N; i++) {
2900             p[i] = readParcelable(loader);
2901         }
2902         return p;
2903     }
2904
2905     /**
2906      * Read and return a new Serializable object from the parcel.
2907      * @return the Serializable object, or null if the Serializable name
2908      * wasn't found in the parcel.
2909      */
2910     public final Serializable readSerializable() {
2911         return readSerializable(null);
2912     }
2913
2914     private final Serializable readSerializable(final ClassLoader loader) {
2915         String name = readString();
2916         if (name == null) {
2917             // For some reason we were unable to read the name of the Serializable (either there
2918             // is nothing left in the Parcel to read, or the next value wasn't a String), so
2919             // return null, which indicates that the name wasn't found in the parcel.
2920             return null;
2921         }
2922
2923         byte[] serializedData = createByteArray();
2924         ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
2925         try {
2926             ObjectInputStream ois = new ObjectInputStream(bais) {
2927                 @Override
2928                 protected Class<?> resolveClass(ObjectStreamClass osClass)
2929                         throws IOException, ClassNotFoundException {
2930                     // try the custom classloader if provided
2931                     if (loader != null) {
2932                         Class<?> c = Class.forName(osClass.getName(), false, loader);
2933                         if (c != null) {
2934                             return c;
2935                         }
2936                     }
2937                     return super.resolveClass(osClass);
2938                 }
2939             };
2940             return (Serializable) ois.readObject();
2941         } catch (IOException ioe) {
2942             throw new RuntimeException("Parcelable encountered " +
2943                 "IOException reading a Serializable object (name = " + name +
2944                 ")", ioe);
2945         } catch (ClassNotFoundException cnfe) {
2946             throw new RuntimeException("Parcelable encountered " +
2947                 "ClassNotFoundException reading a Serializable object (name = "
2948                 + name + ")", cnfe);
2949         }
2950     }
2951
2952     // Cache of previously looked up CREATOR.createFromParcel() methods for
2953     // particular classes.  Keys are the names of the classes, values are
2954     // Method objects.
2955     private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator<?>>>
2956         mCreators = new HashMap<>();
2957
2958     /** @hide for internal use only. */
2959     static protected final Parcel obtain(int obj) {
2960         throw new UnsupportedOperationException();
2961     }
2962
2963     /** @hide */
2964     static protected final Parcel obtain(long obj) {
2965         final Parcel[] pool = sHolderPool;
2966         synchronized (pool) {
2967             Parcel p;
2968             for (int i=0; i<POOL_SIZE; i++) {
2969                 p = pool[i];
2970                 if (p != null) {
2971                     pool[i] = null;
2972                     if (DEBUG_RECYCLE) {
2973                         p.mStack = new RuntimeException();
2974                     }
2975                     p.init(obj);
2976                     return p;
2977                 }
2978             }
2979         }
2980         return new Parcel(obj);
2981     }
2982
2983     private Parcel(long nativePtr) {
2984         if (DEBUG_RECYCLE) {
2985             mStack = new RuntimeException();
2986         }
2987         //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
2988         init(nativePtr);
2989     }
2990
2991     private void init(long nativePtr) {
2992         if (nativePtr != 0) {
2993             mNativePtr = nativePtr;
2994             mOwnsNativeParcelObject = false;
2995         } else {
2996             mNativePtr = nativeCreate();
2997             mOwnsNativeParcelObject = true;
2998         }
2999     }
3000
3001     private void freeBuffer() {
3002         if (mOwnsNativeParcelObject) {
3003             updateNativeSize(nativeFreeBuffer(mNativePtr));
3004         }
3005     }
3006
3007     private void destroy() {
3008         if (mNativePtr != 0) {
3009             if (mOwnsNativeParcelObject) {
3010                 nativeDestroy(mNativePtr);
3011                 updateNativeSize(0);
3012             }
3013             mNativePtr = 0;
3014         }
3015     }
3016
3017     @Override
3018     protected void finalize() throws Throwable {
3019         if (DEBUG_RECYCLE) {
3020             if (mStack != null) {
3021                 Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
3022             }
3023         }
3024         destroy();
3025     }
3026
3027     /* package */ void readMapInternal(Map outVal, int N,
3028         ClassLoader loader) {
3029         while (N > 0) {
3030             Object key = readValue(loader);
3031             Object value = readValue(loader);
3032             outVal.put(key, value);
3033             N--;
3034         }
3035     }
3036
3037     /* package */ void readArrayMapInternal(ArrayMap outVal, int N,
3038         ClassLoader loader) {
3039         if (DEBUG_ARRAY_MAP) {
3040             RuntimeException here =  new RuntimeException("here");
3041             here.fillInStackTrace();
3042             Log.d(TAG, "Reading " + N + " ArrayMap entries", here);
3043         }
3044         int startPos;
3045         while (N > 0) {
3046             if (DEBUG_ARRAY_MAP) startPos = dataPosition();
3047             String key = readString();
3048             Object value = readValue(loader);
3049             if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Read #" + (N-1) + " "
3050                     + (dataPosition()-startPos) + " bytes: key=0x"
3051                     + Integer.toHexString((key != null ? key.hashCode() : 0)) + " " + key);
3052             outVal.append(key, value);
3053             N--;
3054         }
3055         outVal.validate();
3056     }
3057
3058     /* package */ void readArrayMapSafelyInternal(ArrayMap outVal, int N,
3059         ClassLoader loader) {
3060         if (DEBUG_ARRAY_MAP) {
3061             RuntimeException here =  new RuntimeException("here");
3062             here.fillInStackTrace();
3063             Log.d(TAG, "Reading safely " + N + " ArrayMap entries", here);
3064         }
3065         while (N > 0) {
3066             String key = readString();
3067             if (DEBUG_ARRAY_MAP) Log.d(TAG, "  Read safe #" + (N-1) + ": key=0x"
3068                     + (key != null ? key.hashCode() : 0) + " " + key);
3069             Object value = readValue(loader);
3070             outVal.put(key, value);
3071             N--;
3072         }
3073     }
3074
3075     /**
3076      * @hide For testing only.
3077      */
3078     public void readArrayMap(ArrayMap outVal, ClassLoader loader) {
3079         final int N = readInt();
3080         if (N < 0) {
3081             return;
3082         }
3083         readArrayMapInternal(outVal, N, loader);
3084     }
3085
3086     /**
3087      * Reads an array set.
3088      *
3089      * @param loader The class loader to use.
3090      *
3091      * @hide
3092      */
3093     public @Nullable ArraySet<? extends Object> readArraySet(ClassLoader loader) {
3094         final int size = readInt();
3095         if (size < 0) {
3096             return null;
3097         }
3098         ArraySet<Object> result = new ArraySet<>(size);
3099         for (int i = 0; i < size; i++) {
3100             Object value = readValue(loader);
3101             result.append(value);
3102         }
3103         return result;
3104     }
3105
3106     private void readListInternal(List outVal, int N,
3107         ClassLoader loader) {
3108         while (N > 0) {
3109             Object value = readValue(loader);
3110             //Log.d(TAG, "Unmarshalling value=" + value);
3111             outVal.add(value);
3112             N--;
3113         }
3114     }
3115
3116     private void readArrayInternal(Object[] outVal, int N,
3117         ClassLoader loader) {
3118         for (int i = 0; i < N; i++) {
3119             Object value = readValue(loader);
3120             //Log.d(TAG, "Unmarshalling value=" + value);
3121             outVal[i] = value;
3122         }
3123     }
3124
3125     private void readSparseArrayInternal(SparseArray outVal, int N,
3126         ClassLoader loader) {
3127         while (N > 0) {
3128             int key = readInt();
3129             Object value = readValue(loader);
3130             //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3131             outVal.append(key, value);
3132             N--;
3133         }
3134     }
3135
3136
3137     private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
3138         while (N > 0) {
3139             int key = readInt();
3140             boolean value = this.readByte() == 1;
3141             //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3142             outVal.append(key, value);
3143             N--;
3144         }
3145     }
3146
3147     private void readSparseIntArrayInternal(SparseIntArray outVal, int N) {
3148         while (N > 0) {
3149             int key = readInt();
3150             int value = readInt();
3151             outVal.append(key, value);
3152             N--;
3153         }
3154     }
3155
3156     /**
3157      * @hide For testing
3158      */
3159     public long getBlobAshmemSize() {
3160         return nativeGetBlobAshmemSize(mNativePtr);
3161     }
3162 }