2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
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;
30 import dalvik.annotation.optimization.FastNative;
31 import dalvik.system.VMRuntime;
33 import libcore.util.SneakyThrow;
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;
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.
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>
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>
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>
84 * <h3>Primitive Arrays</h3>
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>
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()}.
114 * <h3>Parcelables</h3>
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
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}
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)}.
149 * <h3>Active Objects</h3>
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>
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>
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()}.
179 * <h3>Untyped Containers</h3>
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)}.
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";
197 @SuppressWarnings({"UnusedDeclaration"})
198 private long mNativePtr; // used by native code
201 * Flag indicating if {@link #mNativePtr} was allocated by this object,
202 * indicating that we're responsible for its lifecycle.
204 private boolean mOwnsNativeParcelObject;
205 private long mNativeSize;
207 private ArrayMap<Class, Object> mClassCookies;
209 private RuntimeException mStack;
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];
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;
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;
264 private static native int nativeDataSize(long nativePtr);
266 private static native int nativeDataAvail(long nativePtr);
268 private static native int nativeDataPosition(long nativePtr);
270 private static native int nativeDataCapacity(long nativePtr);
272 private static native long nativeSetDataSize(long nativePtr, int size);
274 private static native void nativeSetDataPosition(long nativePtr, int pos);
276 private static native void nativeSetDataCapacity(long nativePtr, int size);
279 private static native boolean nativePushAllowFds(long nativePtr, boolean allowFds);
281 private static native void nativeRestoreAllowFds(long nativePtr, boolean lastValue);
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);
286 private static native void nativeWriteInt(long nativePtr, int val);
288 private static native void nativeWriteLong(long nativePtr, long val);
290 private static native void nativeWriteFloat(long nativePtr, float val);
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);
297 private static native byte[] nativeCreateByteArray(long nativePtr);
298 private static native boolean nativeReadByteArray(long nativePtr, byte[] dest, int destLen);
299 private static native byte[] nativeReadBlob(long nativePtr);
301 private static native int nativeReadInt(long nativePtr);
303 private static native long nativeReadLong(long nativePtr);
305 private static native float nativeReadFloat(long nativePtr);
307 private static native double nativeReadDouble(long nativePtr);
308 private static native String nativeReadString(long nativePtr);
309 private static native IBinder nativeReadStrongBinder(long nativePtr);
310 private static native FileDescriptor nativeReadFileDescriptor(long nativePtr);
312 private static native long nativeCreate();
313 private static native long nativeFreeBuffer(long nativePtr);
314 private static native void nativeDestroy(long nativePtr);
316 private static native byte[] nativeMarshall(long nativePtr);
317 private static native long nativeUnmarshall(
318 long nativePtr, byte[] data, int offset, int length);
319 private static native int nativeCompareData(long thisNativePtr, long otherNativePtr);
320 private static native long nativeAppendFrom(
321 long thisNativePtr, long otherNativePtr, int offset, int length);
323 private static native boolean nativeHasFileDescriptors(long nativePtr);
324 private static native void nativeWriteInterfaceToken(long nativePtr, String interfaceName);
325 private static native void nativeEnforceInterface(long nativePtr, String interfaceName);
327 private static native long nativeGetBlobAshmemSize(long nativePtr);
329 public final static Parcelable.Creator<String> STRING_CREATOR
330 = new Parcelable.Creator<String>() {
331 public String createFromParcel(Parcel source) {
332 return source.readString();
334 public String[] newArray(int size) {
335 return new String[size];
340 * Retrieve a new Parcel object from the pool.
342 public static Parcel obtain() {
343 final Parcel[] pool = sOwnedPool;
344 synchronized (pool) {
346 for (int i=0; i<POOL_SIZE; i++) {
351 p.mStack = new RuntimeException();
357 return new Parcel(0);
361 * Put a Parcel object back into the pool. You must not touch
362 * the object after this call.
364 public final void recycle() {
365 if (DEBUG_RECYCLE) mStack = null;
369 if (mOwnsNativeParcelObject) {
376 synchronized (pool) {
377 for (int i=0; i<POOL_SIZE; i++) {
378 if (pool[i] == null) {
387 public static native long getGlobalAllocSize();
390 public static native long getGlobalAllocCount();
393 * Returns the total amount of data contained in the parcel.
395 public final int dataSize() {
396 return nativeDataSize(mNativePtr);
400 * Returns the amount of data remaining to be read from the
401 * parcel. That is, {@link #dataSize}-{@link #dataPosition}.
403 public final int dataAvail() {
404 return nativeDataAvail(mNativePtr);
408 * Returns the current position in the parcel data. Never
409 * more than {@link #dataSize}.
411 public final int dataPosition() {
412 return nativeDataPosition(mNativePtr);
416 * Returns the total amount of space in the parcel. This is always
417 * >= {@link #dataSize}. The difference between it and dataSize() is the
418 * amount of room left until the parcel needs to re-allocate its
421 public final int dataCapacity() {
422 return nativeDataCapacity(mNativePtr);
426 * Change the amount of data in the parcel. Can be either smaller or
427 * larger than the current size. If larger than the current capacity,
428 * more memory will be allocated.
430 * @param size The new number of bytes in the Parcel.
432 public final void setDataSize(int size) {
433 // STOPSHIP: Try/catch for exception is for temporary debug. Remove once bug resolved
435 updateNativeSize(nativeSetDataSize(mNativePtr, size));
436 } catch (IllegalArgumentException iae) {
437 Log.e(TAG,"Caught Exception representing a known bug in Parcel",iae);
438 Log.wtfStack(TAG, "This flow is using SetDataSize incorrectly");
443 * Move the current read/write position in the parcel.
444 * @param pos New offset in the parcel; must be between 0 and
447 public final void setDataPosition(int pos) {
448 nativeSetDataPosition(mNativePtr, pos);
452 * Change the capacity (current available space) of the parcel.
454 * @param size The new capacity of the parcel, in bytes. Can not be
455 * less than {@link #dataSize} -- that is, you can not drop existing data
458 public final void setDataCapacity(int size) {
459 nativeSetDataCapacity(mNativePtr, size);
463 public final boolean pushAllowFds(boolean allowFds) {
464 return nativePushAllowFds(mNativePtr, allowFds);
468 public final void restoreAllowFds(boolean lastValue) {
469 nativeRestoreAllowFds(mNativePtr, lastValue);
473 * Returns the raw bytes of the parcel.
475 * <p class="note">The data you retrieve here <strong>must not</strong>
476 * be placed in any kind of persistent storage (on local disk, across
477 * a network, etc). For that, you should use standard serialization
478 * or another kind of general serialization mechanism. The Parcel
479 * marshalled representation is highly optimized for local IPC, and as
480 * such does not attempt to maintain compatibility with data created
481 * in different versions of the platform.
483 public final byte[] marshall() {
484 return nativeMarshall(mNativePtr);
488 * Set the bytes in data to be the raw bytes of this Parcel.
490 public final void unmarshall(byte[] data, int offset, int length) {
491 updateNativeSize(nativeUnmarshall(mNativePtr, data, offset, length));
494 public final void appendFrom(Parcel parcel, int offset, int length) {
495 updateNativeSize(nativeAppendFrom(mNativePtr, parcel.mNativePtr, offset, length));
499 public final int compareData(Parcel other) {
500 return nativeCompareData(mNativePtr, other.mNativePtr);
504 public final void setClassCookie(Class clz, Object cookie) {
505 if (mClassCookies == null) {
506 mClassCookies = new ArrayMap<>();
508 mClassCookies.put(clz, cookie);
512 public final Object getClassCookie(Class clz) {
513 return mClassCookies != null ? mClassCookies.get(clz) : null;
517 public final void adoptClassCookies(Parcel from) {
518 mClassCookies = from.mClassCookies;
522 * Report whether the parcel contains any marshalled file descriptors.
524 public final boolean hasFileDescriptors() {
525 return nativeHasFileDescriptors(mNativePtr);
529 * Store or read an IBinder interface token in the parcel at the current
530 * {@link #dataPosition}. This is used to validate that the marshalled
531 * transaction is intended for the target interface.
533 public final void writeInterfaceToken(String interfaceName) {
534 nativeWriteInterfaceToken(mNativePtr, interfaceName);
537 public final void enforceInterface(String interfaceName) {
538 nativeEnforceInterface(mNativePtr, interfaceName);
542 * Write a byte array into the parcel at the current {@link #dataPosition},
543 * growing {@link #dataCapacity} if needed.
544 * @param b Bytes to place into the parcel.
546 public final void writeByteArray(byte[] b) {
547 writeByteArray(b, 0, (b != null) ? b.length : 0);
551 * Write a byte array into the parcel at the current {@link #dataPosition},
552 * growing {@link #dataCapacity} if needed.
553 * @param b Bytes to place into the parcel.
554 * @param offset Index of first byte to be written.
555 * @param len Number of bytes to write.
557 public final void writeByteArray(byte[] b, int offset, int len) {
562 Arrays.checkOffsetAndCount(b.length, offset, len);
563 nativeWriteByteArray(mNativePtr, b, offset, len);
567 * Write a blob of data into the parcel at the current {@link #dataPosition},
568 * growing {@link #dataCapacity} if needed.
569 * @param b Bytes to place into the parcel.
573 public final void writeBlob(byte[] b) {
574 writeBlob(b, 0, (b != null) ? b.length : 0);
578 * Write a blob of data into the parcel at the current {@link #dataPosition},
579 * growing {@link #dataCapacity} if needed.
580 * @param b Bytes to place into the parcel.
581 * @param offset Index of first byte to be written.
582 * @param len Number of bytes to write.
586 public final void writeBlob(byte[] b, int offset, int len) {
591 Arrays.checkOffsetAndCount(b.length, offset, len);
592 nativeWriteBlob(mNativePtr, b, offset, len);
596 * Write an integer value into the parcel at the current dataPosition(),
597 * growing dataCapacity() if needed.
599 public final void writeInt(int val) {
600 nativeWriteInt(mNativePtr, val);
604 * Write a long integer value into the parcel at the current dataPosition(),
605 * growing dataCapacity() if needed.
607 public final void writeLong(long val) {
608 nativeWriteLong(mNativePtr, val);
612 * Write a floating point value into the parcel at the current
613 * dataPosition(), growing dataCapacity() if needed.
615 public final void writeFloat(float val) {
616 nativeWriteFloat(mNativePtr, val);
620 * Write a double precision floating point value into the parcel at the
621 * current dataPosition(), growing dataCapacity() if needed.
623 public final void writeDouble(double val) {
624 nativeWriteDouble(mNativePtr, val);
628 * Write a string value into the parcel at the current dataPosition(),
629 * growing dataCapacity() if needed.
631 public final void writeString(String val) {
632 nativeWriteString(mNativePtr, val);
636 public final void writeBoolean(boolean val) {
637 writeInt(val ? 1 : 0);
641 * Write a CharSequence value into the parcel at the current dataPosition(),
642 * growing dataCapacity() if needed.
645 public final void writeCharSequence(CharSequence val) {
646 TextUtils.writeToParcel(val, this, 0);
650 * Write an object into the parcel at the current dataPosition(),
651 * growing dataCapacity() if needed.
653 public final void writeStrongBinder(IBinder val) {
654 nativeWriteStrongBinder(mNativePtr, val);
658 * Write an object into the parcel at the current dataPosition(),
659 * growing dataCapacity() if needed.
661 public final void writeStrongInterface(IInterface val) {
662 writeStrongBinder(val == null ? null : val.asBinder());
666 * Write a FileDescriptor into the parcel at the current dataPosition(),
667 * growing dataCapacity() if needed.
669 * <p class="caution">The file descriptor will not be closed, which may
670 * result in file descriptor leaks when objects are returned from Binder
671 * calls. Use {@link ParcelFileDescriptor#writeToParcel} instead, which
672 * accepts contextual flags and will close the original file descriptor
673 * if {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set.</p>
675 public final void writeFileDescriptor(FileDescriptor val) {
676 updateNativeSize(nativeWriteFileDescriptor(mNativePtr, val));
679 private void updateNativeSize(long newNativeSize) {
680 if (mOwnsNativeParcelObject) {
681 if (newNativeSize > Integer.MAX_VALUE) {
682 newNativeSize = Integer.MAX_VALUE;
684 if (newNativeSize != mNativeSize) {
685 int delta = (int) (newNativeSize - mNativeSize);
687 VMRuntime.getRuntime().registerNativeAllocation(delta);
689 VMRuntime.getRuntime().registerNativeFree(-delta);
691 mNativeSize = newNativeSize;
698 * This will be the new name for writeFileDescriptor, for consistency.
700 public final void writeRawFileDescriptor(FileDescriptor val) {
701 nativeWriteFileDescriptor(mNativePtr, val);
706 * Write an array of FileDescriptor objects into the Parcel.
708 * @param value The array of objects to be written.
710 public final void writeRawFileDescriptorArray(FileDescriptor[] value) {
712 int N = value.length;
714 for (int i=0; i<N; i++) {
715 writeRawFileDescriptor(value[i]);
723 * Write a byte value into the parcel at the current dataPosition(),
724 * growing dataCapacity() if needed.
726 public final void writeByte(byte val) {
731 * Please use {@link #writeBundle} instead. Flattens a Map into the parcel
732 * at the current dataPosition(),
733 * growing dataCapacity() if needed. The Map keys must be String objects.
734 * The Map values are written using {@link #writeValue} and must follow
735 * the specification there.
737 * <p>It is strongly recommended to use {@link #writeBundle} instead of
738 * this method, since the Bundle class provides a type-safe API that
739 * allows you to avoid mysterious type errors at the point of marshalling.
741 public final void writeMap(Map val) {
742 writeMapInternal((Map<String, Object>) val);
746 * Flatten a Map into the parcel at the current dataPosition(),
747 * growing dataCapacity() if needed. The Map keys must be String objects.
749 /* package */ void writeMapInternal(Map<String,Object> val) {
754 Set<Map.Entry<String,Object>> entries = val.entrySet();
755 writeInt(entries.size());
756 for (Map.Entry<String,Object> e : entries) {
757 writeValue(e.getKey());
758 writeValue(e.getValue());
763 * Flatten an ArrayMap into the parcel at the current dataPosition(),
764 * growing dataCapacity() if needed. The Map keys must be String objects.
766 /* package */ void writeArrayMapInternal(ArrayMap<String, Object> val) {
771 // Keep the format of this Parcel in sync with writeToParcelInner() in
772 // frameworks/native/libs/binder/PersistableBundle.cpp.
773 final int N = val.size();
775 if (DEBUG_ARRAY_MAP) {
776 RuntimeException here = new RuntimeException("here");
777 here.fillInStackTrace();
778 Log.d(TAG, "Writing " + N + " ArrayMap entries", here);
781 for (int i=0; i<N; i++) {
782 if (DEBUG_ARRAY_MAP) startPos = dataPosition();
783 writeString(val.keyAt(i));
784 writeValue(val.valueAt(i));
785 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Write #" + i + " "
786 + (dataPosition()-startPos) + " bytes: key=0x"
787 + Integer.toHexString(val.keyAt(i) != null ? val.keyAt(i).hashCode() : 0)
788 + " " + val.keyAt(i));
793 * @hide For testing only.
795 public void writeArrayMap(ArrayMap<String, Object> val) {
796 writeArrayMapInternal(val);
800 * Write an array set to the parcel.
802 * @param val The array set to write.
806 public void writeArraySet(@Nullable ArraySet<? extends Object> val) {
807 final int size = (val != null) ? val.size() : -1;
809 for (int i = 0; i < size; i++) {
810 writeValue(val.valueAt(i));
815 * Flatten a Bundle into the parcel at the current dataPosition(),
816 * growing dataCapacity() if needed.
818 public final void writeBundle(Bundle val) {
824 val.writeToParcel(this, 0);
828 * Flatten a PersistableBundle into the parcel at the current dataPosition(),
829 * growing dataCapacity() if needed.
831 public final void writePersistableBundle(PersistableBundle val) {
837 val.writeToParcel(this, 0);
841 * Flatten a Size into the parcel at the current dataPosition(),
842 * growing dataCapacity() if needed.
844 public final void writeSize(Size val) {
845 writeInt(val.getWidth());
846 writeInt(val.getHeight());
850 * Flatten a SizeF into the parcel at the current dataPosition(),
851 * growing dataCapacity() if needed.
853 public final void writeSizeF(SizeF val) {
854 writeFloat(val.getWidth());
855 writeFloat(val.getHeight());
859 * Flatten a List into the parcel at the current dataPosition(), growing
860 * dataCapacity() if needed. The List values are written using
861 * {@link #writeValue} and must follow the specification there.
863 public final void writeList(List val) {
872 writeValue(val.get(i));
878 * Flatten an Object array into the parcel at the current dataPosition(),
879 * growing dataCapacity() if needed. The array values are written using
880 * {@link #writeValue} and must follow the specification there.
882 public final void writeArray(Object[] val) {
897 * Flatten a generic SparseArray into the parcel at the current
898 * dataPosition(), growing dataCapacity() if needed. The SparseArray
899 * values are written using {@link #writeValue} and must follow the
900 * specification there.
902 public final void writeSparseArray(SparseArray<Object> val) {
911 writeInt(val.keyAt(i));
912 writeValue(val.valueAt(i));
917 public final void writeSparseBooleanArray(SparseBooleanArray val) {
926 writeInt(val.keyAt(i));
927 writeByte((byte)(val.valueAt(i) ? 1 : 0));
935 public final void writeSparseIntArray(SparseIntArray val) {
944 writeInt(val.keyAt(i));
945 writeInt(val.valueAt(i));
950 public final void writeBooleanArray(boolean[] val) {
954 for (int i=0; i<N; i++) {
955 writeInt(val[i] ? 1 : 0);
962 public final boolean[] createBooleanArray() {
964 // >>2 as a fast divide-by-4 works in the create*Array() functions
965 // because dataAvail() will never return a negative number. 4 is
966 // the size of a stored boolean in the stream.
967 if (N >= 0 && N <= (dataAvail() >> 2)) {
968 boolean[] val = new boolean[N];
969 for (int i=0; i<N; i++) {
970 val[i] = readInt() != 0;
978 public final void readBooleanArray(boolean[] val) {
980 if (N == val.length) {
981 for (int i=0; i<N; i++) {
982 val[i] = readInt() != 0;
985 throw new RuntimeException("bad array lengths");
989 public final void writeCharArray(char[] val) {
993 for (int i=0; i<N; i++) {
994 writeInt((int)val[i]);
1001 public final char[] createCharArray() {
1003 if (N >= 0 && N <= (dataAvail() >> 2)) {
1004 char[] val = new char[N];
1005 for (int i=0; i<N; i++) {
1006 val[i] = (char)readInt();
1014 public final void readCharArray(char[] val) {
1016 if (N == val.length) {
1017 for (int i=0; i<N; i++) {
1018 val[i] = (char)readInt();
1021 throw new RuntimeException("bad array lengths");
1025 public final void writeIntArray(int[] val) {
1029 for (int i=0; i<N; i++) {
1037 public final int[] createIntArray() {
1039 if (N >= 0 && N <= (dataAvail() >> 2)) {
1040 int[] val = new int[N];
1041 for (int i=0; i<N; i++) {
1050 public final void readIntArray(int[] val) {
1052 if (N == val.length) {
1053 for (int i=0; i<N; i++) {
1057 throw new RuntimeException("bad array lengths");
1061 public final void writeLongArray(long[] val) {
1065 for (int i=0; i<N; i++) {
1073 public final long[] createLongArray() {
1075 // >>3 because stored longs are 64 bits
1076 if (N >= 0 && N <= (dataAvail() >> 3)) {
1077 long[] val = new long[N];
1078 for (int i=0; i<N; i++) {
1079 val[i] = readLong();
1087 public final void readLongArray(long[] val) {
1089 if (N == val.length) {
1090 for (int i=0; i<N; i++) {
1091 val[i] = readLong();
1094 throw new RuntimeException("bad array lengths");
1098 public final void writeFloatArray(float[] val) {
1102 for (int i=0; i<N; i++) {
1110 public final float[] createFloatArray() {
1112 // >>2 because stored floats are 4 bytes
1113 if (N >= 0 && N <= (dataAvail() >> 2)) {
1114 float[] val = new float[N];
1115 for (int i=0; i<N; i++) {
1116 val[i] = readFloat();
1124 public final void readFloatArray(float[] val) {
1126 if (N == val.length) {
1127 for (int i=0; i<N; i++) {
1128 val[i] = readFloat();
1131 throw new RuntimeException("bad array lengths");
1135 public final void writeDoubleArray(double[] val) {
1139 for (int i=0; i<N; i++) {
1140 writeDouble(val[i]);
1147 public final double[] createDoubleArray() {
1149 // >>3 because stored doubles are 8 bytes
1150 if (N >= 0 && N <= (dataAvail() >> 3)) {
1151 double[] val = new double[N];
1152 for (int i=0; i<N; i++) {
1153 val[i] = readDouble();
1161 public final void readDoubleArray(double[] val) {
1163 if (N == val.length) {
1164 for (int i=0; i<N; i++) {
1165 val[i] = readDouble();
1168 throw new RuntimeException("bad array lengths");
1172 public final void writeStringArray(String[] val) {
1176 for (int i=0; i<N; i++) {
1177 writeString(val[i]);
1184 public final String[] createStringArray() {
1187 String[] val = new String[N];
1188 for (int i=0; i<N; i++) {
1189 val[i] = readString();
1197 public final void readStringArray(String[] val) {
1199 if (N == val.length) {
1200 for (int i=0; i<N; i++) {
1201 val[i] = readString();
1204 throw new RuntimeException("bad array lengths");
1208 public final void writeBinderArray(IBinder[] val) {
1212 for (int i=0; i<N; i++) {
1213 writeStrongBinder(val[i]);
1223 public final void writeCharSequenceArray(CharSequence[] val) {
1227 for (int i=0; i<N; i++) {
1228 writeCharSequence(val[i]);
1238 public final void writeCharSequenceList(ArrayList<CharSequence> val) {
1242 for (int i=0; i<N; i++) {
1243 writeCharSequence(val.get(i));
1250 public final IBinder[] createBinderArray() {
1253 IBinder[] val = new IBinder[N];
1254 for (int i=0; i<N; i++) {
1255 val[i] = readStrongBinder();
1263 public final void readBinderArray(IBinder[] val) {
1265 if (N == val.length) {
1266 for (int i=0; i<N; i++) {
1267 val[i] = readStrongBinder();
1270 throw new RuntimeException("bad array lengths");
1275 * Flatten a List containing a particular object type into the parcel, at
1276 * the current dataPosition() and growing dataCapacity() if needed. The
1277 * type of the objects in the list must be one that implements Parcelable.
1278 * Unlike the generic writeList() method, however, only the raw data of the
1279 * objects is written and not their type, so you must use the corresponding
1280 * readTypedList() to unmarshall them.
1282 * @param val The list of objects to be written.
1284 * @see #createTypedArrayList
1285 * @see #readTypedList
1288 public final <T extends Parcelable> void writeTypedList(List<T> val) {
1297 T item = val.get(i);
1300 item.writeToParcel(this, 0);
1309 * Flatten a List containing String objects into the parcel, at
1310 * the current dataPosition() and growing dataCapacity() if needed. They
1311 * can later be retrieved with {@link #createStringArrayList} or
1312 * {@link #readStringList}.
1314 * @param val The list of strings to be written.
1316 * @see #createStringArrayList
1317 * @see #readStringList
1319 public final void writeStringList(List<String> val) {
1328 writeString(val.get(i));
1334 * Flatten a List containing IBinder objects into the parcel, at
1335 * the current dataPosition() and growing dataCapacity() if needed. They
1336 * can later be retrieved with {@link #createBinderArrayList} or
1337 * {@link #readBinderList}.
1339 * @param val The list of strings to be written.
1341 * @see #createBinderArrayList
1342 * @see #readBinderList
1344 public final void writeBinderList(List<IBinder> val) {
1353 writeStrongBinder(val.get(i));
1359 * Flatten a {@code List} containing arbitrary {@code Parcelable} objects into this parcel
1360 * at the current position. They can later be retrieved using
1361 * {@link #readParcelableList(List, ClassLoader)} if required.
1363 * @see #readParcelableList(List, ClassLoader)
1366 public final <T extends Parcelable> void writeParcelableList(List<T> val, int flags) {
1376 writeParcelable(val.get(i), flags);
1382 * Flatten a homogeneous array containing a particular object type into
1384 * the current dataPosition() and growing dataCapacity() if needed. The
1385 * type of the objects in the array must be one that implements Parcelable.
1386 * Unlike the {@link #writeParcelableArray} method, however, only the
1387 * raw data of the objects is written and not their type, so you must use
1388 * {@link #readTypedArray} with the correct corresponding
1389 * {@link Parcelable.Creator} implementation to unmarshall them.
1391 * @param val The array of objects to be written.
1392 * @param parcelableFlags Contextual flags as per
1393 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1395 * @see #readTypedArray
1396 * @see #writeParcelableArray
1397 * @see Parcelable.Creator
1399 public final <T extends Parcelable> void writeTypedArray(T[] val,
1400 int parcelableFlags) {
1404 for (int i = 0; i < N; i++) {
1408 item.writeToParcel(this, parcelableFlags);
1419 * Write a uniform (all items are null or the same class) array list of
1422 * @param list The list to write.
1426 public final <T extends Parcelable> void writeTypedArrayList(@Nullable ArrayList<T> list,
1427 int parcelableFlags) {
1429 int N = list.size();
1431 boolean wroteCreator = false;
1432 for (int i = 0; i < N; i++) {
1433 T item = list.get(i);
1436 if (!wroteCreator) {
1437 writeParcelableCreator(item);
1438 wroteCreator = true;
1440 item.writeToParcel(this, parcelableFlags);
1451 * Reads a uniform (all items are null or the same class) array list of
1454 * @return The list or null.
1458 public final @Nullable <T> ArrayList<T> readTypedArrayList(@Nullable ClassLoader loader) {
1463 Parcelable.Creator<?> creator = null;
1464 ArrayList<T> result = new ArrayList<T>(N);
1465 for (int i = 0; i < N; i++) {
1466 if (readInt() != 0) {
1467 if (creator == null) {
1468 creator = readParcelableCreator(loader);
1469 if (creator == null) {
1474 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
1475 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
1476 (Parcelable.ClassLoaderCreator<?>) creator;
1477 parcelable = (T) classLoaderCreator.createFromParcel(this, loader);
1479 parcelable = (T) creator.createFromParcel(this);
1481 result.add(parcelable);
1490 * Write a uniform (all items are null or the same class) array set of
1493 * @param set The set to write.
1497 public final <T extends Parcelable> void writeTypedArraySet(@Nullable ArraySet<T> set,
1498 int parcelableFlags) {
1502 boolean wroteCreator = false;
1503 for (int i = 0; i < N; i++) {
1504 T item = set.valueAt(i);
1507 if (!wroteCreator) {
1508 writeParcelableCreator(item);
1509 wroteCreator = true;
1511 item.writeToParcel(this, parcelableFlags);
1522 * Reads a uniform (all items are null or the same class) array set of
1525 * @return The set or null.
1529 public final @Nullable <T> ArraySet<T> readTypedArraySet(@Nullable ClassLoader loader) {
1534 Parcelable.Creator<?> creator = null;
1535 ArraySet<T> result = new ArraySet<T>(N);
1536 for (int i = 0; i < N; i++) {
1537 T parcelable = null;
1538 if (readInt() != 0) {
1539 if (creator == null) {
1540 creator = readParcelableCreator(loader);
1541 if (creator == null) {
1545 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
1546 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
1547 (Parcelable.ClassLoaderCreator<?>) creator;
1548 parcelable = (T) classLoaderCreator.createFromParcel(this, loader);
1550 parcelable = (T) creator.createFromParcel(this);
1553 result.append(parcelable);
1559 * Flatten the Parcelable object into the parcel.
1561 * @param val The Parcelable object to be written.
1562 * @param parcelableFlags Contextual flags as per
1563 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1565 * @see #readTypedObject
1567 public final <T extends Parcelable> void writeTypedObject(T val, int parcelableFlags) {
1570 val.writeToParcel(this, parcelableFlags);
1577 * Flatten a generic object in to a parcel. The given Object value may
1578 * currently be one of the following types:
1595 * <li> Object[] (supporting objects of the same type defined here).
1596 * <li> {@link Bundle}
1597 * <li> Map (as supported by {@link #writeMap}).
1598 * <li> Any object that implements the {@link Parcelable} protocol.
1600 * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
1601 * <li> List (as supported by {@link #writeList}).
1602 * <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}).
1603 * <li> {@link IBinder}
1604 * <li> Any object that implements Serializable (but see
1605 * {@link #writeSerializable} for caveats). Note that all of the
1606 * previous types have relatively efficient implementations for
1607 * writing to a Parcel; having to rely on the generic serialization
1608 * approach is much less efficient and should be avoided whenever
1612 * <p class="caution">{@link Parcelable} objects are written with
1613 * {@link Parcelable#writeToParcel} using contextual flags of 0. When
1614 * serializing objects containing {@link ParcelFileDescriptor}s,
1615 * this may result in file descriptor leaks when they are returned from
1616 * Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE}
1617 * should be used).</p>
1619 public final void writeValue(Object v) {
1622 } else if (v instanceof String) {
1623 writeInt(VAL_STRING);
1624 writeString((String) v);
1625 } else if (v instanceof Integer) {
1626 writeInt(VAL_INTEGER);
1627 writeInt((Integer) v);
1628 } else if (v instanceof Map) {
1631 } else if (v instanceof Bundle) {
1632 // Must be before Parcelable
1633 writeInt(VAL_BUNDLE);
1634 writeBundle((Bundle) v);
1635 } else if (v instanceof PersistableBundle) {
1636 writeInt(VAL_PERSISTABLEBUNDLE);
1637 writePersistableBundle((PersistableBundle) v);
1638 } else if (v instanceof Parcelable) {
1639 // IMPOTANT: cases for classes that implement Parcelable must
1640 // come before the Parcelable case, so that their specific VAL_*
1641 // types will be written.
1642 writeInt(VAL_PARCELABLE);
1643 writeParcelable((Parcelable) v, 0);
1644 } else if (v instanceof Short) {
1645 writeInt(VAL_SHORT);
1646 writeInt(((Short) v).intValue());
1647 } else if (v instanceof Long) {
1649 writeLong((Long) v);
1650 } else if (v instanceof Float) {
1651 writeInt(VAL_FLOAT);
1652 writeFloat((Float) v);
1653 } else if (v instanceof Double) {
1654 writeInt(VAL_DOUBLE);
1655 writeDouble((Double) v);
1656 } else if (v instanceof Boolean) {
1657 writeInt(VAL_BOOLEAN);
1658 writeInt((Boolean) v ? 1 : 0);
1659 } else if (v instanceof CharSequence) {
1660 // Must be after String
1661 writeInt(VAL_CHARSEQUENCE);
1662 writeCharSequence((CharSequence) v);
1663 } else if (v instanceof List) {
1665 writeList((List) v);
1666 } else if (v instanceof SparseArray) {
1667 writeInt(VAL_SPARSEARRAY);
1668 writeSparseArray((SparseArray) v);
1669 } else if (v instanceof boolean[]) {
1670 writeInt(VAL_BOOLEANARRAY);
1671 writeBooleanArray((boolean[]) v);
1672 } else if (v instanceof byte[]) {
1673 writeInt(VAL_BYTEARRAY);
1674 writeByteArray((byte[]) v);
1675 } else if (v instanceof String[]) {
1676 writeInt(VAL_STRINGARRAY);
1677 writeStringArray((String[]) v);
1678 } else if (v instanceof CharSequence[]) {
1679 // Must be after String[] and before Object[]
1680 writeInt(VAL_CHARSEQUENCEARRAY);
1681 writeCharSequenceArray((CharSequence[]) v);
1682 } else if (v instanceof IBinder) {
1683 writeInt(VAL_IBINDER);
1684 writeStrongBinder((IBinder) v);
1685 } else if (v instanceof Parcelable[]) {
1686 writeInt(VAL_PARCELABLEARRAY);
1687 writeParcelableArray((Parcelable[]) v, 0);
1688 } else if (v instanceof int[]) {
1689 writeInt(VAL_INTARRAY);
1690 writeIntArray((int[]) v);
1691 } else if (v instanceof long[]) {
1692 writeInt(VAL_LONGARRAY);
1693 writeLongArray((long[]) v);
1694 } else if (v instanceof Byte) {
1697 } else if (v instanceof Size) {
1699 writeSize((Size) v);
1700 } else if (v instanceof SizeF) {
1701 writeInt(VAL_SIZEF);
1702 writeSizeF((SizeF) v);
1703 } else if (v instanceof double[]) {
1704 writeInt(VAL_DOUBLEARRAY);
1705 writeDoubleArray((double[]) v);
1707 Class<?> clazz = v.getClass();
1708 if (clazz.isArray() && clazz.getComponentType() == Object.class) {
1709 // Only pure Object[] are written here, Other arrays of non-primitive types are
1710 // handled by serialization as this does not record the component type.
1711 writeInt(VAL_OBJECTARRAY);
1712 writeArray((Object[]) v);
1713 } else if (v instanceof Serializable) {
1715 writeInt(VAL_SERIALIZABLE);
1716 writeSerializable((Serializable) v);
1718 throw new RuntimeException("Parcel: unable to marshal value " + v);
1724 * Flatten the name of the class of the Parcelable and its contents
1727 * @param p The Parcelable object to be written.
1728 * @param parcelableFlags Contextual flags as per
1729 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1731 public final void writeParcelable(Parcelable p, int parcelableFlags) {
1736 writeParcelableCreator(p);
1737 p.writeToParcel(this, parcelableFlags);
1741 public final void writeParcelableCreator(Parcelable p) {
1742 String name = p.getClass().getName();
1747 * Write a generic serializable object in to a Parcel. It is strongly
1748 * recommended that this method be avoided, since the serialization
1749 * overhead is extremely large, and this approach will be much slower than
1750 * using the other approaches to writing data in to a Parcel.
1752 public final void writeSerializable(Serializable s) {
1757 String name = s.getClass().getName();
1760 ByteArrayOutputStream baos = new ByteArrayOutputStream();
1762 ObjectOutputStream oos = new ObjectOutputStream(baos);
1766 writeByteArray(baos.toByteArray());
1767 } catch (IOException ioe) {
1768 throw new RuntimeException("Parcelable encountered " +
1769 "IOException writing serializable object (name = " + name +
1775 * Special function for writing an exception result at the header of
1776 * a parcel, to be used when returning an exception from a transaction.
1777 * Note that this currently only supports a few exception types; any other
1778 * exception will be re-thrown by this function as a RuntimeException
1779 * (to be caught by the system's last-resort exception handling when
1780 * dispatching a transaction).
1782 * <p>The supported exception types are:
1784 * <li>{@link BadParcelableException}
1785 * <li>{@link IllegalArgumentException}
1786 * <li>{@link IllegalStateException}
1787 * <li>{@link NullPointerException}
1788 * <li>{@link SecurityException}
1789 * <li>{@link NetworkOnMainThreadException}
1792 * @param e The Exception to be written.
1794 * @see #writeNoException
1795 * @see #readException
1797 public final void writeException(Exception e) {
1799 if (e instanceof Parcelable
1800 && (e.getClass().getClassLoader() == Parcelable.class.getClassLoader())) {
1801 // We only send Parcelable exceptions that are in the
1802 // BootClassLoader to ensure that the receiver can unpack them
1803 code = EX_PARCELABLE;
1804 } else if (e instanceof SecurityException) {
1806 } else if (e instanceof BadParcelableException) {
1807 code = EX_BAD_PARCELABLE;
1808 } else if (e instanceof IllegalArgumentException) {
1809 code = EX_ILLEGAL_ARGUMENT;
1810 } else if (e instanceof NullPointerException) {
1811 code = EX_NULL_POINTER;
1812 } else if (e instanceof IllegalStateException) {
1813 code = EX_ILLEGAL_STATE;
1814 } else if (e instanceof NetworkOnMainThreadException) {
1815 code = EX_NETWORK_MAIN_THREAD;
1816 } else if (e instanceof UnsupportedOperationException) {
1817 code = EX_UNSUPPORTED_OPERATION;
1818 } else if (e instanceof ServiceSpecificException) {
1819 code = EX_SERVICE_SPECIFIC;
1822 StrictMode.clearGatheredViolations();
1824 if (e instanceof RuntimeException) {
1825 throw (RuntimeException) e;
1827 throw new RuntimeException(e);
1829 writeString(e.getMessage());
1831 case EX_SERVICE_SPECIFIC:
1832 writeInt(((ServiceSpecificException) e).errorCode);
1835 // Write parceled exception prefixed by length
1836 final int sizePosition = dataPosition();
1838 writeParcelable((Parcelable) e, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1839 final int payloadPosition = dataPosition();
1840 setDataPosition(sizePosition);
1841 writeInt(payloadPosition - sizePosition);
1842 setDataPosition(payloadPosition);
1848 * Special function for writing information at the front of the Parcel
1849 * indicating that no exception occurred.
1851 * @see #writeException
1852 * @see #readException
1854 public final void writeNoException() {
1855 // Despite the name of this function ("write no exception"),
1856 // it should instead be thought of as "write the RPC response
1857 // header", but because this function name is written out by
1858 // the AIDL compiler, we're not going to rename it.
1860 // The response header, in the non-exception case (see also
1861 // writeException above, also called by the AIDL compiler), is
1862 // either a 0 (the default case), or EX_HAS_REPLY_HEADER if
1863 // StrictMode has gathered up violations that have occurred
1864 // during a Binder call, in which case we write out the number
1865 // of violations and their details, serialized, before the
1866 // actual RPC respons data. The receiving end of this is
1867 // readException(), below.
1868 if (StrictMode.hasGatheredViolations()) {
1869 writeInt(EX_HAS_REPLY_HEADER);
1870 final int sizePosition = dataPosition();
1871 writeInt(0); // total size of fat header, to be filled in later
1872 StrictMode.writeGatheredViolationsToParcel(this);
1873 final int payloadPosition = dataPosition();
1874 setDataPosition(sizePosition);
1875 writeInt(payloadPosition - sizePosition); // header size
1876 setDataPosition(payloadPosition);
1883 * Special function for reading an exception result from the header of
1884 * a parcel, to be used after receiving the result of a transaction. This
1885 * will throw the exception for you if it had been written to the Parcel,
1886 * otherwise return and let you read the normal result data from the Parcel.
1888 * @see #writeException
1889 * @see #writeNoException
1891 public final void readException() {
1892 int code = readExceptionCode();
1894 String msg = readString();
1895 readException(code, msg);
1900 * Parses the header of a Binder call's response Parcel and
1901 * returns the exception code. Deals with lite or fat headers.
1902 * In the common successful case, this header is generally zero.
1903 * In less common cases, it's a small negative number and will be
1904 * followed by an error string.
1906 * This exists purely for android.database.DatabaseUtils and
1907 * insulating it from having to handle fat headers as returned by
1908 * e.g. StrictMode-induced RPC responses.
1912 public final int readExceptionCode() {
1913 int code = readInt();
1914 if (code == EX_HAS_REPLY_HEADER) {
1915 int headerSize = readInt();
1916 if (headerSize == 0) {
1917 Log.e(TAG, "Unexpected zero-sized Parcel reply header.");
1919 // Currently the only thing in the header is StrictMode stacks,
1920 // but discussions around event/RPC tracing suggest we might
1921 // put that here too. If so, switch on sub-header tags here.
1922 // But for now, just parse out the StrictMode stuff.
1923 StrictMode.readAndHandleBinderCallViolations(this);
1925 // And fat response headers are currently only used when
1926 // there are no exceptions, so return no error:
1933 * Throw an exception with the given message. Not intended for use
1934 * outside the Parcel class.
1936 * @param code Used to determine which exception class to throw.
1937 * @param msg The exception message.
1939 public final void readException(int code, String msg) {
1942 if (readInt() > 0) {
1943 SneakyThrow.sneakyThrow(
1944 (Exception) readParcelable(Parcelable.class.getClassLoader()));
1946 throw new RuntimeException(msg + " [missing Parcelable]");
1949 throw new SecurityException(msg);
1950 case EX_BAD_PARCELABLE:
1951 throw new BadParcelableException(msg);
1952 case EX_ILLEGAL_ARGUMENT:
1953 throw new IllegalArgumentException(msg);
1954 case EX_NULL_POINTER:
1955 throw new NullPointerException(msg);
1956 case EX_ILLEGAL_STATE:
1957 throw new IllegalStateException(msg);
1958 case EX_NETWORK_MAIN_THREAD:
1959 throw new NetworkOnMainThreadException();
1960 case EX_UNSUPPORTED_OPERATION:
1961 throw new UnsupportedOperationException(msg);
1962 case EX_SERVICE_SPECIFIC:
1963 throw new ServiceSpecificException(readInt(), msg);
1965 throw new RuntimeException("Unknown exception code: " + code
1970 * Read an integer value from the parcel at the current dataPosition().
1972 public final int readInt() {
1973 return nativeReadInt(mNativePtr);
1977 * Read a long integer value from the parcel at the current dataPosition().
1979 public final long readLong() {
1980 return nativeReadLong(mNativePtr);
1984 * Read a floating point value from the parcel at the current
1987 public final float readFloat() {
1988 return nativeReadFloat(mNativePtr);
1992 * Read a double precision floating point value from the parcel at the
1993 * current dataPosition().
1995 public final double readDouble() {
1996 return nativeReadDouble(mNativePtr);
2000 * Read a string value from the parcel at the current dataPosition().
2002 public final String readString() {
2003 return nativeReadString(mNativePtr);
2007 public final boolean readBoolean() {
2008 return readInt() != 0;
2012 * Read a CharSequence value from the parcel at the current dataPosition().
2015 public final CharSequence readCharSequence() {
2016 return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
2020 * Read an object from the parcel at the current dataPosition().
2022 public final IBinder readStrongBinder() {
2023 return nativeReadStrongBinder(mNativePtr);
2027 * Read a FileDescriptor from the parcel at the current dataPosition().
2029 public final ParcelFileDescriptor readFileDescriptor() {
2030 FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
2031 return fd != null ? new ParcelFileDescriptor(fd) : null;
2035 public final FileDescriptor readRawFileDescriptor() {
2036 return nativeReadFileDescriptor(mNativePtr);
2041 * Read and return a new array of FileDescriptors from the parcel.
2042 * @return the FileDescriptor array, or null if the array is null.
2044 public final FileDescriptor[] createRawFileDescriptorArray() {
2049 FileDescriptor[] f = new FileDescriptor[N];
2050 for (int i = 0; i < N; i++) {
2051 f[i] = readRawFileDescriptor();
2058 * Read an array of FileDescriptors from a parcel.
2059 * The passed array must be exactly the length of the array in the parcel.
2060 * @return the FileDescriptor array, or null if the array is null.
2062 public final void readRawFileDescriptorArray(FileDescriptor[] val) {
2064 if (N == val.length) {
2065 for (int i=0; i<N; i++) {
2066 val[i] = readRawFileDescriptor();
2069 throw new RuntimeException("bad array lengths");
2073 /** @deprecated use {@link android.system.Os#open(String, int, int)} */
2075 static native FileDescriptor openFileDescriptor(String file, int mode)
2076 throws FileNotFoundException;
2078 /** @deprecated use {@link android.system.Os#dup(FileDescriptor)} */
2080 static native FileDescriptor dupFileDescriptor(FileDescriptor orig) throws IOException;
2082 /** @deprecated use {@link android.system.Os#close(FileDescriptor)} */
2084 static native void closeFileDescriptor(FileDescriptor desc) throws IOException;
2086 static native void clearFileDescriptor(FileDescriptor desc);
2089 * Read a byte value from the parcel at the current dataPosition().
2091 public final byte readByte() {
2092 return (byte)(readInt() & 0xff);
2096 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2097 * been written with {@link #writeBundle}. Read into an existing Map object
2098 * from the parcel at the current dataPosition().
2100 public final void readMap(Map outVal, ClassLoader loader) {
2102 readMapInternal(outVal, N, loader);
2106 * Read into an existing List object from the parcel at the current
2107 * dataPosition(), using the given class loader to load any enclosed
2108 * Parcelables. If it is null, the default class loader is used.
2110 public final void readList(List outVal, ClassLoader loader) {
2112 readListInternal(outVal, N, loader);
2116 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2117 * been written with {@link #writeBundle}. Read and return a new HashMap
2118 * object from the parcel at the current dataPosition(), using the given
2119 * class loader to load any enclosed Parcelables. Returns null if
2120 * the previously written map object was null.
2122 public final HashMap readHashMap(ClassLoader loader)
2128 HashMap m = new HashMap(N);
2129 readMapInternal(m, N, loader);
2134 * Read and return a new Bundle object from the parcel at the current
2135 * dataPosition(). Returns null if the previously written Bundle object was
2138 public final Bundle readBundle() {
2139 return readBundle(null);
2143 * Read and return a new Bundle object from the parcel at the current
2144 * dataPosition(), using the given class loader to initialize the class
2145 * loader of the Bundle for later retrieval of Parcelable objects.
2146 * Returns null if the previously written Bundle object was null.
2148 public final Bundle readBundle(ClassLoader loader) {
2149 int length = readInt();
2151 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2155 final Bundle bundle = new Bundle(this, length);
2156 if (loader != null) {
2157 bundle.setClassLoader(loader);
2163 * Read and return a new Bundle object from the parcel at the current
2164 * dataPosition(). Returns null if the previously written Bundle object was
2167 public final PersistableBundle readPersistableBundle() {
2168 return readPersistableBundle(null);
2172 * Read and return a new Bundle object from the parcel at the current
2173 * dataPosition(), using the given class loader to initialize the class
2174 * loader of the Bundle for later retrieval of Parcelable objects.
2175 * Returns null if the previously written Bundle object was null.
2177 public final PersistableBundle readPersistableBundle(ClassLoader loader) {
2178 int length = readInt();
2180 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2184 final PersistableBundle bundle = new PersistableBundle(this, length);
2185 if (loader != null) {
2186 bundle.setClassLoader(loader);
2192 * Read a Size from the parcel at the current dataPosition().
2194 public final Size readSize() {
2195 final int width = readInt();
2196 final int height = readInt();
2197 return new Size(width, height);
2201 * Read a SizeF from the parcel at the current dataPosition().
2203 public final SizeF readSizeF() {
2204 final float width = readFloat();
2205 final float height = readFloat();
2206 return new SizeF(width, height);
2210 * Read and return a byte[] object from the parcel.
2212 public final byte[] createByteArray() {
2213 return nativeCreateByteArray(mNativePtr);
2217 * Read a byte[] object from the parcel and copy it into the
2220 public final void readByteArray(byte[] val) {
2221 boolean valid = nativeReadByteArray(mNativePtr, val, (val != null) ? val.length : 0);
2223 throw new RuntimeException("bad array lengths");
2228 * Read a blob of data from the parcel and return it as a byte array.
2232 public final byte[] readBlob() {
2233 return nativeReadBlob(mNativePtr);
2237 * Read and return a String[] object from the parcel.
2240 public final String[] readStringArray() {
2241 String[] array = null;
2243 int length = readInt();
2246 array = new String[length];
2248 for (int i = 0 ; i < length ; i++)
2250 array[i] = readString();
2258 * Read and return a CharSequence[] object from the parcel.
2261 public final CharSequence[] readCharSequenceArray() {
2262 CharSequence[] array = null;
2264 int length = readInt();
2267 array = new CharSequence[length];
2269 for (int i = 0 ; i < length ; i++)
2271 array[i] = readCharSequence();
2279 * Read and return an ArrayList<CharSequence> object from the parcel.
2282 public final ArrayList<CharSequence> readCharSequenceList() {
2283 ArrayList<CharSequence> array = null;
2285 int length = readInt();
2287 array = new ArrayList<CharSequence>(length);
2289 for (int i = 0 ; i < length ; i++) {
2290 array.add(readCharSequence());
2298 * Read and return a new ArrayList object from the parcel at the current
2299 * dataPosition(). Returns null if the previously written list object was
2300 * null. The given class loader will be used to load any enclosed
2303 public final ArrayList readArrayList(ClassLoader loader) {
2308 ArrayList l = new ArrayList(N);
2309 readListInternal(l, N, loader);
2314 * Read and return a new Object array from the parcel at the current
2315 * dataPosition(). Returns null if the previously written array was
2316 * null. The given class loader will be used to load any enclosed
2319 public final Object[] readArray(ClassLoader loader) {
2324 Object[] l = new Object[N];
2325 readArrayInternal(l, N, loader);
2330 * Read and return a new SparseArray object from the parcel at the current
2331 * dataPosition(). Returns null if the previously written list object was
2332 * null. The given class loader will be used to load any enclosed
2335 public final SparseArray readSparseArray(ClassLoader loader) {
2340 SparseArray sa = new SparseArray(N);
2341 readSparseArrayInternal(sa, N, loader);
2346 * Read and return a new SparseBooleanArray object from the parcel at the current
2347 * dataPosition(). Returns null if the previously written list object was
2350 public final SparseBooleanArray readSparseBooleanArray() {
2355 SparseBooleanArray sa = new SparseBooleanArray(N);
2356 readSparseBooleanArrayInternal(sa, N);
2361 * Read and return a new SparseIntArray object from the parcel at the current
2362 * dataPosition(). Returns null if the previously written array object was null.
2365 public final SparseIntArray readSparseIntArray() {
2370 SparseIntArray sa = new SparseIntArray(N);
2371 readSparseIntArrayInternal(sa, N);
2376 * Read and return a new ArrayList containing a particular object type from
2377 * the parcel that was written with {@link #writeTypedList} at the
2378 * current dataPosition(). Returns null if the
2379 * previously written list object was null. The list <em>must</em> have
2380 * previously been written via {@link #writeTypedList} with the same object
2383 * @return A newly created ArrayList containing objects with the same data
2384 * as those that were previously written.
2386 * @see #writeTypedList
2388 public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
2393 ArrayList<T> l = new ArrayList<T>(N);
2395 if (readInt() != 0) {
2396 l.add(c.createFromParcel(this));
2406 * Read into the given List items containing a particular object type
2407 * that were written with {@link #writeTypedList} at the
2408 * current dataPosition(). The list <em>must</em> have
2409 * previously been written via {@link #writeTypedList} with the same object
2412 * @return A newly created ArrayList containing objects with the same data
2413 * as those that were previously written.
2415 * @see #writeTypedList
2417 public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
2418 int M = list.size();
2421 for (; i < M && i < N; i++) {
2422 if (readInt() != 0) {
2423 list.set(i, c.createFromParcel(this));
2429 if (readInt() != 0) {
2430 list.add(c.createFromParcel(this));
2441 * Read and return a new ArrayList containing String objects from
2442 * the parcel that was written with {@link #writeStringList} at the
2443 * current dataPosition(). Returns null if the
2444 * previously written list object was null.
2446 * @return A newly created ArrayList containing strings with the same data
2447 * as those that were previously written.
2449 * @see #writeStringList
2451 public final ArrayList<String> createStringArrayList() {
2456 ArrayList<String> l = new ArrayList<String>(N);
2458 l.add(readString());
2465 * Read and return a new ArrayList containing IBinder objects from
2466 * the parcel that was written with {@link #writeBinderList} at the
2467 * current dataPosition(). Returns null if the
2468 * previously written list object was null.
2470 * @return A newly created ArrayList containing strings with the same data
2471 * as those that were previously written.
2473 * @see #writeBinderList
2475 public final ArrayList<IBinder> createBinderArrayList() {
2480 ArrayList<IBinder> l = new ArrayList<IBinder>(N);
2482 l.add(readStrongBinder());
2489 * Read into the given List items String objects that were written with
2490 * {@link #writeStringList} at the current dataPosition().
2492 * @return A newly created ArrayList containing strings with the same data
2493 * as those that were previously written.
2495 * @see #writeStringList
2497 public final void readStringList(List<String> list) {
2498 int M = list.size();
2501 for (; i < M && i < N; i++) {
2502 list.set(i, readString());
2505 list.add(readString());
2513 * Read into the given List items IBinder objects that were written with
2514 * {@link #writeBinderList} at the current dataPosition().
2516 * @see #writeBinderList
2518 public final void readBinderList(List<IBinder> list) {
2519 int M = list.size();
2522 for (; i < M && i < N; i++) {
2523 list.set(i, readStrongBinder());
2526 list.add(readStrongBinder());
2534 * Read the list of {@code Parcelable} objects at the current data position into the
2535 * given {@code list}. The contents of the {@code list} are replaced. If the serialized
2536 * list was {@code null}, {@code list} is cleared.
2538 * @see #writeParcelableList(List, int)
2541 public final <T extends Parcelable> List<T> readParcelableList(List<T> list, ClassLoader cl) {
2542 final int N = readInt();
2548 final int M = list.size();
2550 for (; i < M && i < N; i++) {
2551 list.set(i, (T) readParcelable(cl));
2554 list.add((T) readParcelable(cl));
2563 * Read and return a new array containing a particular object type from
2564 * the parcel at the current dataPosition(). Returns null if the
2565 * previously written array was null. The array <em>must</em> have
2566 * previously been written via {@link #writeTypedArray} with the same
2569 * @return A newly created array containing objects with the same data
2570 * as those that were previously written.
2572 * @see #writeTypedArray
2574 public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
2579 T[] l = c.newArray(N);
2580 for (int i=0; i<N; i++) {
2581 if (readInt() != 0) {
2582 l[i] = c.createFromParcel(this);
2588 public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
2590 if (N == val.length) {
2591 for (int i=0; i<N; i++) {
2592 if (readInt() != 0) {
2593 val[i] = c.createFromParcel(this);
2599 throw new RuntimeException("bad array lengths");
2608 public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
2609 return createTypedArray(c);
2613 * Read and return a typed Parcelable object from a parcel.
2614 * Returns null if the previous written object was null.
2615 * The object <em>must</em> have previous been written via
2616 * {@link #writeTypedObject} with the same object type.
2618 * @return A newly created object of the type that was previously
2621 * @see #writeTypedObject
2623 public final <T> T readTypedObject(Parcelable.Creator<T> c) {
2624 if (readInt() != 0) {
2625 return c.createFromParcel(this);
2632 * Write a heterogeneous array of Parcelable objects into the Parcel.
2633 * Each object in the array is written along with its class name, so
2634 * that the correct class can later be instantiated. As a result, this
2635 * has significantly more overhead than {@link #writeTypedArray}, but will
2636 * correctly handle an array containing more than one type of object.
2638 * @param value The array of objects to be written.
2639 * @param parcelableFlags Contextual flags as per
2640 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2642 * @see #writeTypedArray
2644 public final <T extends Parcelable> void writeParcelableArray(T[] value,
2645 int parcelableFlags) {
2646 if (value != null) {
2647 int N = value.length;
2649 for (int i=0; i<N; i++) {
2650 writeParcelable(value[i], parcelableFlags);
2658 * Read a typed object from a parcel. The given class loader will be
2659 * used to load any enclosed Parcelables. If it is null, the default class
2660 * loader will be used.
2662 public final Object readValue(ClassLoader loader) {
2663 int type = readInt();
2670 return readString();
2676 return readHashMap(loader);
2678 case VAL_PARCELABLE:
2679 return readParcelable(loader);
2682 return (short) readInt();
2691 return readDouble();
2694 return readInt() == 1;
2696 case VAL_CHARSEQUENCE:
2697 return readCharSequence();
2700 return readArrayList(loader);
2702 case VAL_BOOLEANARRAY:
2703 return createBooleanArray();
2706 return createByteArray();
2708 case VAL_STRINGARRAY:
2709 return readStringArray();
2711 case VAL_CHARSEQUENCEARRAY:
2712 return readCharSequenceArray();
2715 return readStrongBinder();
2717 case VAL_OBJECTARRAY:
2718 return readArray(loader);
2721 return createIntArray();
2724 return createLongArray();
2729 case VAL_SERIALIZABLE:
2730 return readSerializable(loader);
2732 case VAL_PARCELABLEARRAY:
2733 return readParcelableArray(loader);
2735 case VAL_SPARSEARRAY:
2736 return readSparseArray(loader);
2738 case VAL_SPARSEBOOLEANARRAY:
2739 return readSparseBooleanArray();
2742 return readBundle(loader); // loading will be deferred
2744 case VAL_PERSISTABLEBUNDLE:
2745 return readPersistableBundle(loader);
2753 case VAL_DOUBLEARRAY:
2754 return createDoubleArray();
2757 int off = dataPosition() - 4;
2758 throw new RuntimeException(
2759 "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
2764 * Read and return a new Parcelable from the parcel. The given class loader
2765 * will be used to load any enclosed Parcelables. If it is null, the default
2766 * class loader will be used.
2767 * @param loader A ClassLoader from which to instantiate the Parcelable
2768 * object, or null for the default class loader.
2769 * @return Returns the newly created Parcelable, or null if a null
2770 * object has been written.
2771 * @throws BadParcelableException Throws BadParcelableException if there
2772 * was an error trying to instantiate the Parcelable.
2774 @SuppressWarnings("unchecked")
2775 public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
2776 Parcelable.Creator<?> creator = readParcelableCreator(loader);
2777 if (creator == null) {
2780 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2781 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2782 (Parcelable.ClassLoaderCreator<?>) creator;
2783 return (T) classLoaderCreator.createFromParcel(this, loader);
2785 return (T) creator.createFromParcel(this);
2789 @SuppressWarnings("unchecked")
2790 public final <T extends Parcelable> T readCreator(Parcelable.Creator<?> creator,
2791 ClassLoader loader) {
2792 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2793 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2794 (Parcelable.ClassLoaderCreator<?>) creator;
2795 return (T) classLoaderCreator.createFromParcel(this, loader);
2797 return (T) creator.createFromParcel(this);
2801 public final Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) {
2802 String name = readString();
2806 Parcelable.Creator<?> creator;
2807 synchronized (mCreators) {
2808 HashMap<String,Parcelable.Creator<?>> map = mCreators.get(loader);
2810 map = new HashMap<>();
2811 mCreators.put(loader, map);
2813 creator = map.get(name);
2814 if (creator == null) {
2816 // If loader == null, explicitly emulate Class.forName(String) "caller
2817 // classloader" behavior.
2818 ClassLoader parcelableClassLoader =
2819 (loader == null ? getClass().getClassLoader() : loader);
2820 // Avoid initializing the Parcelable class until we know it implements
2821 // Parcelable and has the necessary CREATOR field. http://b/1171613.
2822 Class<?> parcelableClass = Class.forName(name, false /* initialize */,
2823 parcelableClassLoader);
2824 if (!Parcelable.class.isAssignableFrom(parcelableClass)) {
2825 throw new BadParcelableException("Parcelable protocol requires that the "
2826 + "class implements Parcelable");
2828 Field f = parcelableClass.getField("CREATOR");
2829 if ((f.getModifiers() & Modifier.STATIC) == 0) {
2830 throw new BadParcelableException("Parcelable protocol requires "
2831 + "the CREATOR object to be static on class " + name);
2833 Class<?> creatorType = f.getType();
2834 if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) {
2835 // Fail before calling Field.get(), not after, to avoid initializing
2836 // parcelableClass unnecessarily.
2837 throw new BadParcelableException("Parcelable protocol requires a "
2838 + "Parcelable.Creator object called "
2839 + "CREATOR on class " + name);
2841 creator = (Parcelable.Creator<?>) f.get(null);
2843 catch (IllegalAccessException e) {
2844 Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
2845 throw new BadParcelableException(
2846 "IllegalAccessException when unmarshalling: " + name);
2848 catch (ClassNotFoundException e) {
2849 Log.e(TAG, "Class not found when unmarshalling: " + name, e);
2850 throw new BadParcelableException(
2851 "ClassNotFoundException when unmarshalling: " + name);
2853 catch (NoSuchFieldException e) {
2854 throw new BadParcelableException("Parcelable protocol requires a "
2855 + "Parcelable.Creator object called "
2856 + "CREATOR on class " + name);
2858 if (creator == null) {
2859 throw new BadParcelableException("Parcelable protocol requires a "
2860 + "non-null Parcelable.Creator object called "
2861 + "CREATOR on class " + name);
2864 map.put(name, creator);
2872 * Read and return a new Parcelable array from the parcel.
2873 * The given class loader will be used to load any enclosed
2875 * @return the Parcelable array, or null if the array is null
2877 public final Parcelable[] readParcelableArray(ClassLoader loader) {
2882 Parcelable[] p = new Parcelable[N];
2883 for (int i = 0; i < N; i++) {
2884 p[i] = readParcelable(loader);
2890 public final <T extends Parcelable> T[] readParcelableArray(ClassLoader loader,
2896 T[] p = (T[]) Array.newInstance(clazz, N);
2897 for (int i = 0; i < N; i++) {
2898 p[i] = readParcelable(loader);
2904 * Read and return a new Serializable object from the parcel.
2905 * @return the Serializable object, or null if the Serializable name
2906 * wasn't found in the parcel.
2908 public final Serializable readSerializable() {
2909 return readSerializable(null);
2912 private final Serializable readSerializable(final ClassLoader loader) {
2913 String name = readString();
2915 // For some reason we were unable to read the name of the Serializable (either there
2916 // is nothing left in the Parcel to read, or the next value wasn't a String), so
2917 // return null, which indicates that the name wasn't found in the parcel.
2921 byte[] serializedData = createByteArray();
2922 ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
2924 ObjectInputStream ois = new ObjectInputStream(bais) {
2926 protected Class<?> resolveClass(ObjectStreamClass osClass)
2927 throws IOException, ClassNotFoundException {
2928 // try the custom classloader if provided
2929 if (loader != null) {
2930 Class<?> c = Class.forName(osClass.getName(), false, loader);
2935 return super.resolveClass(osClass);
2938 return (Serializable) ois.readObject();
2939 } catch (IOException ioe) {
2940 throw new RuntimeException("Parcelable encountered " +
2941 "IOException reading a Serializable object (name = " + name +
2943 } catch (ClassNotFoundException cnfe) {
2944 throw new RuntimeException("Parcelable encountered " +
2945 "ClassNotFoundException reading a Serializable object (name = "
2946 + name + ")", cnfe);
2950 // Cache of previously looked up CREATOR.createFromParcel() methods for
2951 // particular classes. Keys are the names of the classes, values are
2953 private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator<?>>>
2954 mCreators = new HashMap<>();
2956 /** @hide for internal use only. */
2957 static protected final Parcel obtain(int obj) {
2958 throw new UnsupportedOperationException();
2962 static protected final Parcel obtain(long obj) {
2963 final Parcel[] pool = sHolderPool;
2964 synchronized (pool) {
2966 for (int i=0; i<POOL_SIZE; i++) {
2970 if (DEBUG_RECYCLE) {
2971 p.mStack = new RuntimeException();
2978 return new Parcel(obj);
2981 private Parcel(long nativePtr) {
2982 if (DEBUG_RECYCLE) {
2983 mStack = new RuntimeException();
2985 //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
2989 private void init(long nativePtr) {
2990 if (nativePtr != 0) {
2991 mNativePtr = nativePtr;
2992 mOwnsNativeParcelObject = false;
2994 mNativePtr = nativeCreate();
2995 mOwnsNativeParcelObject = true;
2999 private void freeBuffer() {
3000 if (mOwnsNativeParcelObject) {
3001 updateNativeSize(nativeFreeBuffer(mNativePtr));
3005 private void destroy() {
3006 if (mNativePtr != 0) {
3007 if (mOwnsNativeParcelObject) {
3008 nativeDestroy(mNativePtr);
3009 updateNativeSize(0);
3016 protected void finalize() throws Throwable {
3017 if (DEBUG_RECYCLE) {
3018 if (mStack != null) {
3019 Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
3025 /* package */ void readMapInternal(Map outVal, int N,
3026 ClassLoader loader) {
3028 Object key = readValue(loader);
3029 Object value = readValue(loader);
3030 outVal.put(key, value);
3035 /* package */ void readArrayMapInternal(ArrayMap outVal, int N,
3036 ClassLoader loader) {
3037 if (DEBUG_ARRAY_MAP) {
3038 RuntimeException here = new RuntimeException("here");
3039 here.fillInStackTrace();
3040 Log.d(TAG, "Reading " + N + " ArrayMap entries", here);
3044 if (DEBUG_ARRAY_MAP) startPos = dataPosition();
3045 String key = readString();
3046 Object value = readValue(loader);
3047 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Read #" + (N-1) + " "
3048 + (dataPosition()-startPos) + " bytes: key=0x"
3049 + Integer.toHexString((key != null ? key.hashCode() : 0)) + " " + key);
3050 outVal.append(key, value);
3056 /* package */ void readArrayMapSafelyInternal(ArrayMap outVal, int N,
3057 ClassLoader loader) {
3058 if (DEBUG_ARRAY_MAP) {
3059 RuntimeException here = new RuntimeException("here");
3060 here.fillInStackTrace();
3061 Log.d(TAG, "Reading safely " + N + " ArrayMap entries", here);
3064 String key = readString();
3065 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Read safe #" + (N-1) + ": key=0x"
3066 + (key != null ? key.hashCode() : 0) + " " + key);
3067 Object value = readValue(loader);
3068 outVal.put(key, value);
3074 * @hide For testing only.
3076 public void readArrayMap(ArrayMap outVal, ClassLoader loader) {
3077 final int N = readInt();
3081 readArrayMapInternal(outVal, N, loader);
3085 * Reads an array set.
3087 * @param loader The class loader to use.
3091 public @Nullable ArraySet<? extends Object> readArraySet(ClassLoader loader) {
3092 final int size = readInt();
3096 ArraySet<Object> result = new ArraySet<>(size);
3097 for (int i = 0; i < size; i++) {
3098 Object value = readValue(loader);
3099 result.append(value);
3104 private void readListInternal(List outVal, int N,
3105 ClassLoader loader) {
3107 Object value = readValue(loader);
3108 //Log.d(TAG, "Unmarshalling value=" + value);
3114 private void readArrayInternal(Object[] outVal, int N,
3115 ClassLoader loader) {
3116 for (int i = 0; i < N; i++) {
3117 Object value = readValue(loader);
3118 //Log.d(TAG, "Unmarshalling value=" + value);
3123 private void readSparseArrayInternal(SparseArray outVal, int N,
3124 ClassLoader loader) {
3126 int key = readInt();
3127 Object value = readValue(loader);
3128 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3129 outVal.append(key, value);
3135 private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
3137 int key = readInt();
3138 boolean value = this.readByte() == 1;
3139 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3140 outVal.append(key, value);
3145 private void readSparseIntArrayInternal(SparseIntArray outVal, int N) {
3147 int key = readInt();
3148 int value = readInt();
3149 outVal.append(key, value);
3157 public long getBlobAshmemSize() {
3158 return nativeGetBlobAshmemSize(mNativePtr);