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 byte[] nativeReadBlob(long nativePtr);
300 private static native int nativeReadInt(long nativePtr);
302 private static native long nativeReadLong(long nativePtr);
304 private static native float nativeReadFloat(long nativePtr);
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);
311 private static native long nativeCreate();
312 private static native long nativeFreeBuffer(long nativePtr);
313 private static native void nativeDestroy(long nativePtr);
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);
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);
326 private static native long nativeGetBlobAshmemSize(long nativePtr);
328 public final static Parcelable.Creator<String> STRING_CREATOR
329 = new Parcelable.Creator<String>() {
330 public String createFromParcel(Parcel source) {
331 return source.readString();
333 public String[] newArray(int size) {
334 return new String[size];
339 * Retrieve a new Parcel object from the pool.
341 public static Parcel obtain() {
342 final Parcel[] pool = sOwnedPool;
343 synchronized (pool) {
345 for (int i=0; i<POOL_SIZE; i++) {
350 p.mStack = new RuntimeException();
356 return new Parcel(0);
360 * Put a Parcel object back into the pool. You must not touch
361 * the object after this call.
363 public final void recycle() {
364 if (DEBUG_RECYCLE) mStack = null;
368 if (mOwnsNativeParcelObject) {
375 synchronized (pool) {
376 for (int i=0; i<POOL_SIZE; i++) {
377 if (pool[i] == null) {
386 public static native long getGlobalAllocSize();
389 public static native long getGlobalAllocCount();
392 * Returns the total amount of data contained in the parcel.
394 public final int dataSize() {
395 return nativeDataSize(mNativePtr);
399 * Returns the amount of data remaining to be read from the
400 * parcel. That is, {@link #dataSize}-{@link #dataPosition}.
402 public final int dataAvail() {
403 return nativeDataAvail(mNativePtr);
407 * Returns the current position in the parcel data. Never
408 * more than {@link #dataSize}.
410 public final int dataPosition() {
411 return nativeDataPosition(mNativePtr);
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
420 public final int dataCapacity() {
421 return nativeDataCapacity(mNativePtr);
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.
429 * @param size The new number of bytes in the Parcel.
431 public final void setDataSize(int size) {
432 // STOPSHIP: Try/catch for exception is for temporary debug. Remove once bug resolved
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");
442 * Move the current read/write position in the parcel.
443 * @param pos New offset in the parcel; must be between 0 and
446 public final void setDataPosition(int pos) {
447 nativeSetDataPosition(mNativePtr, pos);
451 * Change the capacity (current available space) of the parcel.
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
457 public final void setDataCapacity(int size) {
458 nativeSetDataCapacity(mNativePtr, size);
462 public final boolean pushAllowFds(boolean allowFds) {
463 return nativePushAllowFds(mNativePtr, allowFds);
467 public final void restoreAllowFds(boolean lastValue) {
468 nativeRestoreAllowFds(mNativePtr, lastValue);
472 * Returns the raw bytes of the parcel.
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.
482 public final byte[] marshall() {
483 return nativeMarshall(mNativePtr);
487 * Set the bytes in data to be the raw bytes of this Parcel.
489 public final void unmarshall(byte[] data, int offset, int length) {
490 updateNativeSize(nativeUnmarshall(mNativePtr, data, offset, length));
493 public final void appendFrom(Parcel parcel, int offset, int length) {
494 updateNativeSize(nativeAppendFrom(mNativePtr, parcel.mNativePtr, offset, length));
498 public final int compareData(Parcel other) {
499 return nativeCompareData(mNativePtr, other.mNativePtr);
503 public final void setClassCookie(Class clz, Object cookie) {
504 if (mClassCookies == null) {
505 mClassCookies = new ArrayMap<>();
507 mClassCookies.put(clz, cookie);
511 public final Object getClassCookie(Class clz) {
512 return mClassCookies != null ? mClassCookies.get(clz) : null;
516 public final void adoptClassCookies(Parcel from) {
517 mClassCookies = from.mClassCookies;
521 * Report whether the parcel contains any marshalled file descriptors.
523 public final boolean hasFileDescriptors() {
524 return nativeHasFileDescriptors(mNativePtr);
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.
532 public final void writeInterfaceToken(String interfaceName) {
533 nativeWriteInterfaceToken(mNativePtr, interfaceName);
536 public final void enforceInterface(String interfaceName) {
537 nativeEnforceInterface(mNativePtr, interfaceName);
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.
545 public final void writeByteArray(byte[] b) {
546 writeByteArray(b, 0, (b != null) ? b.length : 0);
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.
556 public final void writeByteArray(byte[] b, int offset, int len) {
561 Arrays.checkOffsetAndCount(b.length, offset, len);
562 nativeWriteByteArray(mNativePtr, b, offset, len);
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.
572 public final void writeBlob(byte[] b) {
573 writeBlob(b, 0, (b != null) ? b.length : 0);
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.
585 public final void writeBlob(byte[] b, int offset, int len) {
590 Arrays.checkOffsetAndCount(b.length, offset, len);
591 nativeWriteBlob(mNativePtr, b, offset, len);
595 * Write an integer value into the parcel at the current dataPosition(),
596 * growing dataCapacity() if needed.
598 public final void writeInt(int val) {
599 nativeWriteInt(mNativePtr, val);
603 * Write a long integer value into the parcel at the current dataPosition(),
604 * growing dataCapacity() if needed.
606 public final void writeLong(long val) {
607 nativeWriteLong(mNativePtr, val);
611 * Write a floating point value into the parcel at the current
612 * dataPosition(), growing dataCapacity() if needed.
614 public final void writeFloat(float val) {
615 nativeWriteFloat(mNativePtr, val);
619 * Write a double precision floating point value into the parcel at the
620 * current dataPosition(), growing dataCapacity() if needed.
622 public final void writeDouble(double val) {
623 nativeWriteDouble(mNativePtr, val);
627 * Write a string value into the parcel at the current dataPosition(),
628 * growing dataCapacity() if needed.
630 public final void writeString(String val) {
631 nativeWriteString(mNativePtr, val);
635 public final void writeBoolean(boolean val) {
636 writeInt(val ? 1 : 0);
640 * Write a CharSequence value into the parcel at the current dataPosition(),
641 * growing dataCapacity() if needed.
644 public final void writeCharSequence(CharSequence val) {
645 TextUtils.writeToParcel(val, this, 0);
649 * Write an object into the parcel at the current dataPosition(),
650 * growing dataCapacity() if needed.
652 public final void writeStrongBinder(IBinder val) {
653 nativeWriteStrongBinder(mNativePtr, val);
657 * Write an object into the parcel at the current dataPosition(),
658 * growing dataCapacity() if needed.
660 public final void writeStrongInterface(IInterface val) {
661 writeStrongBinder(val == null ? null : val.asBinder());
665 * Write a FileDescriptor into the parcel at the current dataPosition(),
666 * growing dataCapacity() if needed.
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>
674 public final void writeFileDescriptor(FileDescriptor val) {
675 updateNativeSize(nativeWriteFileDescriptor(mNativePtr, val));
678 private void updateNativeSize(long newNativeSize) {
679 if (mOwnsNativeParcelObject) {
680 if (newNativeSize > Integer.MAX_VALUE) {
681 newNativeSize = Integer.MAX_VALUE;
683 if (newNativeSize != mNativeSize) {
684 int delta = (int) (newNativeSize - mNativeSize);
686 VMRuntime.getRuntime().registerNativeAllocation(delta);
688 VMRuntime.getRuntime().registerNativeFree(-delta);
690 mNativeSize = newNativeSize;
697 * This will be the new name for writeFileDescriptor, for consistency.
699 public final void writeRawFileDescriptor(FileDescriptor val) {
700 nativeWriteFileDescriptor(mNativePtr, val);
705 * Write an array of FileDescriptor objects into the Parcel.
707 * @param value The array of objects to be written.
709 public final void writeRawFileDescriptorArray(FileDescriptor[] value) {
711 int N = value.length;
713 for (int i=0; i<N; i++) {
714 writeRawFileDescriptor(value[i]);
722 * Write a byte value into the parcel at the current dataPosition(),
723 * growing dataCapacity() if needed.
725 public final void writeByte(byte val) {
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.
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.
740 public final void writeMap(Map val) {
741 writeMapInternal((Map<String, Object>) val);
745 * Flatten a Map into the parcel at the current dataPosition(),
746 * growing dataCapacity() if needed. The Map keys must be String objects.
748 /* package */ void writeMapInternal(Map<String,Object> val) {
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());
762 * Flatten an ArrayMap into the parcel at the current dataPosition(),
763 * growing dataCapacity() if needed. The Map keys must be String objects.
765 /* package */ void writeArrayMapInternal(ArrayMap<String, Object> val) {
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();
774 if (DEBUG_ARRAY_MAP) {
775 RuntimeException here = new RuntimeException("here");
776 here.fillInStackTrace();
777 Log.d(TAG, "Writing " + N + " ArrayMap entries", here);
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));
792 * @hide For testing only.
794 public void writeArrayMap(ArrayMap<String, Object> val) {
795 writeArrayMapInternal(val);
799 * Write an array set to the parcel.
801 * @param val The array set to write.
805 public void writeArraySet(@Nullable ArraySet<? extends Object> val) {
806 final int size = (val != null) ? val.size() : -1;
808 for (int i = 0; i < size; i++) {
809 writeValue(val.valueAt(i));
814 * Flatten a Bundle into the parcel at the current dataPosition(),
815 * growing dataCapacity() if needed.
817 public final void writeBundle(Bundle val) {
823 val.writeToParcel(this, 0);
827 * Flatten a PersistableBundle into the parcel at the current dataPosition(),
828 * growing dataCapacity() if needed.
830 public final void writePersistableBundle(PersistableBundle val) {
836 val.writeToParcel(this, 0);
840 * Flatten a Size into the parcel at the current dataPosition(),
841 * growing dataCapacity() if needed.
843 public final void writeSize(Size val) {
844 writeInt(val.getWidth());
845 writeInt(val.getHeight());
849 * Flatten a SizeF into the parcel at the current dataPosition(),
850 * growing dataCapacity() if needed.
852 public final void writeSizeF(SizeF val) {
853 writeFloat(val.getWidth());
854 writeFloat(val.getHeight());
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.
862 public final void writeList(List val) {
871 writeValue(val.get(i));
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.
881 public final void writeArray(Object[] val) {
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.
901 public final void writeSparseArray(SparseArray<Object> val) {
910 writeInt(val.keyAt(i));
911 writeValue(val.valueAt(i));
916 public final void writeSparseBooleanArray(SparseBooleanArray val) {
925 writeInt(val.keyAt(i));
926 writeByte((byte)(val.valueAt(i) ? 1 : 0));
934 public final void writeSparseIntArray(SparseIntArray val) {
943 writeInt(val.keyAt(i));
944 writeInt(val.valueAt(i));
949 public final void writeBooleanArray(boolean[] val) {
953 for (int i=0; i<N; i++) {
954 writeInt(val[i] ? 1 : 0);
961 public final boolean[] createBooleanArray() {
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;
977 public final void readBooleanArray(boolean[] val) {
979 if (N == val.length) {
980 for (int i=0; i<N; i++) {
981 val[i] = readInt() != 0;
984 throw new RuntimeException("bad array lengths");
988 public final void writeCharArray(char[] val) {
992 for (int i=0; i<N; i++) {
993 writeInt((int)val[i]);
1000 public final char[] createCharArray() {
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();
1013 public final void readCharArray(char[] val) {
1015 if (N == val.length) {
1016 for (int i=0; i<N; i++) {
1017 val[i] = (char)readInt();
1020 throw new RuntimeException("bad array lengths");
1024 public final void writeIntArray(int[] val) {
1028 for (int i=0; i<N; i++) {
1036 public final int[] createIntArray() {
1038 if (N >= 0 && N <= (dataAvail() >> 2)) {
1039 int[] val = new int[N];
1040 for (int i=0; i<N; i++) {
1049 public final void readIntArray(int[] val) {
1051 if (N == val.length) {
1052 for (int i=0; i<N; i++) {
1056 throw new RuntimeException("bad array lengths");
1060 public final void writeLongArray(long[] val) {
1064 for (int i=0; i<N; i++) {
1072 public final long[] createLongArray() {
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();
1086 public final void readLongArray(long[] val) {
1088 if (N == val.length) {
1089 for (int i=0; i<N; i++) {
1090 val[i] = readLong();
1093 throw new RuntimeException("bad array lengths");
1097 public final void writeFloatArray(float[] val) {
1101 for (int i=0; i<N; i++) {
1109 public final float[] createFloatArray() {
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();
1123 public final void readFloatArray(float[] val) {
1125 if (N == val.length) {
1126 for (int i=0; i<N; i++) {
1127 val[i] = readFloat();
1130 throw new RuntimeException("bad array lengths");
1134 public final void writeDoubleArray(double[] val) {
1138 for (int i=0; i<N; i++) {
1139 writeDouble(val[i]);
1146 public final double[] createDoubleArray() {
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();
1160 public final void readDoubleArray(double[] val) {
1162 if (N == val.length) {
1163 for (int i=0; i<N; i++) {
1164 val[i] = readDouble();
1167 throw new RuntimeException("bad array lengths");
1171 public final void writeStringArray(String[] val) {
1175 for (int i=0; i<N; i++) {
1176 writeString(val[i]);
1183 public final String[] createStringArray() {
1186 String[] val = new String[N];
1187 for (int i=0; i<N; i++) {
1188 val[i] = readString();
1196 public final void readStringArray(String[] val) {
1198 if (N == val.length) {
1199 for (int i=0; i<N; i++) {
1200 val[i] = readString();
1203 throw new RuntimeException("bad array lengths");
1207 public final void writeBinderArray(IBinder[] val) {
1211 for (int i=0; i<N; i++) {
1212 writeStrongBinder(val[i]);
1222 public final void writeCharSequenceArray(CharSequence[] val) {
1226 for (int i=0; i<N; i++) {
1227 writeCharSequence(val[i]);
1237 public final void writeCharSequenceList(ArrayList<CharSequence> val) {
1241 for (int i=0; i<N; i++) {
1242 writeCharSequence(val.get(i));
1249 public final IBinder[] createBinderArray() {
1252 IBinder[] val = new IBinder[N];
1253 for (int i=0; i<N; i++) {
1254 val[i] = readStrongBinder();
1262 public final void readBinderArray(IBinder[] val) {
1264 if (N == val.length) {
1265 for (int i=0; i<N; i++) {
1266 val[i] = readStrongBinder();
1269 throw new RuntimeException("bad array lengths");
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.
1281 * @param val The list of objects to be written.
1283 * @see #createTypedArrayList
1284 * @see #readTypedList
1287 public final <T extends Parcelable> void writeTypedList(List<T> val) {
1296 T item = val.get(i);
1299 item.writeToParcel(this, 0);
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}.
1313 * @param val The list of strings to be written.
1315 * @see #createStringArrayList
1316 * @see #readStringList
1318 public final void writeStringList(List<String> val) {
1327 writeString(val.get(i));
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}.
1338 * @param val The list of strings to be written.
1340 * @see #createBinderArrayList
1341 * @see #readBinderList
1343 public final void writeBinderList(List<IBinder> val) {
1352 writeStrongBinder(val.get(i));
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.
1362 * @see #readParcelableList(List, ClassLoader)
1365 public final <T extends Parcelable> void writeParcelableList(List<T> val, int flags) {
1375 writeParcelable(val.get(i), flags);
1381 * Flatten a homogeneous array containing a particular object type into
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.
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()}.
1394 * @see #readTypedArray
1395 * @see #writeParcelableArray
1396 * @see Parcelable.Creator
1398 public final <T extends Parcelable> void writeTypedArray(T[] val,
1399 int parcelableFlags) {
1403 for (int i = 0; i < N; i++) {
1407 item.writeToParcel(this, parcelableFlags);
1418 * Write a uniform (all items are null or the same class) array list of
1421 * @param list The list to write.
1425 public final <T extends Parcelable> void writeTypedArrayList(@Nullable ArrayList<T> list,
1426 int parcelableFlags) {
1428 int N = list.size();
1430 boolean wroteCreator = false;
1431 for (int i = 0; i < N; i++) {
1432 T item = list.get(i);
1435 if (!wroteCreator) {
1436 writeParcelableCreator(item);
1437 wroteCreator = true;
1439 item.writeToParcel(this, parcelableFlags);
1450 * Reads a uniform (all items are null or the same class) array list of
1453 * @return The list or null.
1457 public final @Nullable <T> ArrayList<T> readTypedArrayList(@Nullable ClassLoader loader) {
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) {
1473 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
1474 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
1475 (Parcelable.ClassLoaderCreator<?>) creator;
1476 parcelable = (T) classLoaderCreator.createFromParcel(this, loader);
1478 parcelable = (T) creator.createFromParcel(this);
1480 result.add(parcelable);
1489 * Write a uniform (all items are null or the same class) array set of
1492 * @param set The set to write.
1496 public final <T extends Parcelable> void writeTypedArraySet(@Nullable ArraySet<T> set,
1497 int parcelableFlags) {
1501 boolean wroteCreator = false;
1502 for (int i = 0; i < N; i++) {
1503 T item = set.valueAt(i);
1506 if (!wroteCreator) {
1507 writeParcelableCreator(item);
1508 wroteCreator = true;
1510 item.writeToParcel(this, parcelableFlags);
1521 * Reads a uniform (all items are null or the same class) array set of
1524 * @return The set or null.
1528 public final @Nullable <T> ArraySet<T> readTypedArraySet(@Nullable ClassLoader loader) {
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) {
1544 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
1545 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
1546 (Parcelable.ClassLoaderCreator<?>) creator;
1547 parcelable = (T) classLoaderCreator.createFromParcel(this, loader);
1549 parcelable = (T) creator.createFromParcel(this);
1552 result.append(parcelable);
1558 * Flatten the Parcelable object into the parcel.
1560 * @param val The Parcelable object to be written.
1561 * @param parcelableFlags Contextual flags as per
1562 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1564 * @see #readTypedObject
1566 public final <T extends Parcelable> void writeTypedObject(T val, int parcelableFlags) {
1569 val.writeToParcel(this, parcelableFlags);
1576 * Flatten a generic object in to a parcel. The given Object value may
1577 * currently be one of the following types:
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.
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
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>
1618 public final void writeValue(Object v) {
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) {
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) {
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) {
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) {
1696 } else if (v instanceof 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);
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) {
1714 writeInt(VAL_SERIALIZABLE);
1715 writeSerializable((Serializable) v);
1717 throw new RuntimeException("Parcel: unable to marshal value " + v);
1723 * Flatten the name of the class of the Parcelable and its contents
1726 * @param p The Parcelable object to be written.
1727 * @param parcelableFlags Contextual flags as per
1728 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1730 public final void writeParcelable(Parcelable p, int parcelableFlags) {
1735 writeParcelableCreator(p);
1736 p.writeToParcel(this, parcelableFlags);
1740 public final void writeParcelableCreator(Parcelable p) {
1741 String name = p.getClass().getName();
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.
1751 public final void writeSerializable(Serializable s) {
1756 String name = s.getClass().getName();
1759 ByteArrayOutputStream baos = new ByteArrayOutputStream();
1761 ObjectOutputStream oos = new ObjectOutputStream(baos);
1765 writeByteArray(baos.toByteArray());
1766 } catch (IOException ioe) {
1767 throw new RuntimeException("Parcelable encountered " +
1768 "IOException writing serializable object (name = " + name +
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).
1781 * <p>The supported exception types are:
1783 * <li>{@link BadParcelableException}
1784 * <li>{@link IllegalArgumentException}
1785 * <li>{@link IllegalStateException}
1786 * <li>{@link NullPointerException}
1787 * <li>{@link SecurityException}
1788 * <li>{@link NetworkOnMainThreadException}
1791 * @param e The Exception to be written.
1793 * @see #writeNoException
1794 * @see #readException
1796 public final void writeException(Exception e) {
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) {
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;
1821 StrictMode.clearGatheredViolations();
1823 if (e instanceof RuntimeException) {
1824 throw (RuntimeException) e;
1826 throw new RuntimeException(e);
1828 writeString(e.getMessage());
1830 case EX_SERVICE_SPECIFIC:
1831 writeInt(((ServiceSpecificException) e).errorCode);
1834 // Write parceled exception prefixed by length
1835 final int sizePosition = dataPosition();
1837 writeParcelable((Parcelable) e, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1838 final int payloadPosition = dataPosition();
1839 setDataPosition(sizePosition);
1840 writeInt(payloadPosition - sizePosition);
1841 setDataPosition(payloadPosition);
1847 * Special function for writing information at the front of the Parcel
1848 * indicating that no exception occurred.
1850 * @see #writeException
1851 * @see #readException
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.
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);
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.
1887 * @see #writeException
1888 * @see #writeNoException
1890 public final void readException() {
1891 int code = readExceptionCode();
1893 String msg = readString();
1894 readException(code, msg);
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.
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.
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.");
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);
1924 // And fat response headers are currently only used when
1925 // there are no exceptions, so return no error:
1932 * Throw an exception with the given message. Not intended for use
1933 * outside the Parcel class.
1935 * @param code Used to determine which exception class to throw.
1936 * @param msg The exception message.
1938 public final void readException(int code, String msg) {
1941 if (readInt() > 0) {
1942 SneakyThrow.sneakyThrow(
1943 (Exception) readParcelable(Parcelable.class.getClassLoader()));
1945 throw new RuntimeException(msg + " [missing Parcelable]");
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);
1964 throw new RuntimeException("Unknown exception code: " + code
1969 * Read an integer value from the parcel at the current dataPosition().
1971 public final int readInt() {
1972 return nativeReadInt(mNativePtr);
1976 * Read a long integer value from the parcel at the current dataPosition().
1978 public final long readLong() {
1979 return nativeReadLong(mNativePtr);
1983 * Read a floating point value from the parcel at the current
1986 public final float readFloat() {
1987 return nativeReadFloat(mNativePtr);
1991 * Read a double precision floating point value from the parcel at the
1992 * current dataPosition().
1994 public final double readDouble() {
1995 return nativeReadDouble(mNativePtr);
1999 * Read a string value from the parcel at the current dataPosition().
2001 public final String readString() {
2002 return nativeReadString(mNativePtr);
2006 public final boolean readBoolean() {
2007 return readInt() != 0;
2011 * Read a CharSequence value from the parcel at the current dataPosition().
2014 public final CharSequence readCharSequence() {
2015 return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
2019 * Read an object from the parcel at the current dataPosition().
2021 public final IBinder readStrongBinder() {
2022 return nativeReadStrongBinder(mNativePtr);
2026 * Read a FileDescriptor from the parcel at the current dataPosition().
2028 public final ParcelFileDescriptor readFileDescriptor() {
2029 FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
2030 return fd != null ? new ParcelFileDescriptor(fd) : null;
2034 public final FileDescriptor readRawFileDescriptor() {
2035 return nativeReadFileDescriptor(mNativePtr);
2040 * Read and return a new array of FileDescriptors from the parcel.
2041 * @return the FileDescriptor array, or null if the array is null.
2043 public final FileDescriptor[] createRawFileDescriptorArray() {
2048 FileDescriptor[] f = new FileDescriptor[N];
2049 for (int i = 0; i < N; i++) {
2050 f[i] = readRawFileDescriptor();
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.
2061 public final void readRawFileDescriptorArray(FileDescriptor[] val) {
2063 if (N == val.length) {
2064 for (int i=0; i<N; i++) {
2065 val[i] = readRawFileDescriptor();
2068 throw new RuntimeException("bad array lengths");
2072 /** @deprecated use {@link android.system.Os#open(String, int, int)} */
2074 static native FileDescriptor openFileDescriptor(String file, int mode)
2075 throws FileNotFoundException;
2077 /** @deprecated use {@link android.system.Os#dup(FileDescriptor)} */
2079 static native FileDescriptor dupFileDescriptor(FileDescriptor orig) throws IOException;
2081 /** @deprecated use {@link android.system.Os#close(FileDescriptor)} */
2083 static native void closeFileDescriptor(FileDescriptor desc) throws IOException;
2085 static native void clearFileDescriptor(FileDescriptor desc);
2088 * Read a byte value from the parcel at the current dataPosition().
2090 public final byte readByte() {
2091 return (byte)(readInt() & 0xff);
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().
2099 public final void readMap(Map outVal, ClassLoader loader) {
2101 readMapInternal(outVal, N, loader);
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.
2109 public final void readList(List outVal, ClassLoader loader) {
2111 readListInternal(outVal, N, loader);
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.
2121 public final HashMap readHashMap(ClassLoader loader)
2127 HashMap m = new HashMap(N);
2128 readMapInternal(m, N, loader);
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
2137 public final Bundle readBundle() {
2138 return readBundle(null);
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.
2147 public final Bundle readBundle(ClassLoader loader) {
2148 int length = readInt();
2150 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2154 final Bundle bundle = new Bundle(this, length);
2155 if (loader != null) {
2156 bundle.setClassLoader(loader);
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
2166 public final PersistableBundle readPersistableBundle() {
2167 return readPersistableBundle(null);
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.
2176 public final PersistableBundle readPersistableBundle(ClassLoader loader) {
2177 int length = readInt();
2179 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2183 final PersistableBundle bundle = new PersistableBundle(this, length);
2184 if (loader != null) {
2185 bundle.setClassLoader(loader);
2191 * Read a Size from the parcel at the current dataPosition().
2193 public final Size readSize() {
2194 final int width = readInt();
2195 final int height = readInt();
2196 return new Size(width, height);
2200 * Read a SizeF from the parcel at the current dataPosition().
2202 public final SizeF readSizeF() {
2203 final float width = readFloat();
2204 final float height = readFloat();
2205 return new SizeF(width, height);
2209 * Read and return a byte[] object from the parcel.
2211 public final byte[] createByteArray() {
2212 return nativeCreateByteArray(mNativePtr);
2216 * Read a byte[] object from the parcel and copy it into the
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);
2225 throw new RuntimeException("bad array lengths");
2230 * Read a blob of data from the parcel and return it as a byte array.
2234 public final byte[] readBlob() {
2235 return nativeReadBlob(mNativePtr);
2239 * Read and return a String[] object from the parcel.
2242 public final String[] readStringArray() {
2243 String[] array = null;
2245 int length = readInt();
2248 array = new String[length];
2250 for (int i = 0 ; i < length ; i++)
2252 array[i] = readString();
2260 * Read and return a CharSequence[] object from the parcel.
2263 public final CharSequence[] readCharSequenceArray() {
2264 CharSequence[] array = null;
2266 int length = readInt();
2269 array = new CharSequence[length];
2271 for (int i = 0 ; i < length ; i++)
2273 array[i] = readCharSequence();
2281 * Read and return an ArrayList<CharSequence> object from the parcel.
2284 public final ArrayList<CharSequence> readCharSequenceList() {
2285 ArrayList<CharSequence> array = null;
2287 int length = readInt();
2289 array = new ArrayList<CharSequence>(length);
2291 for (int i = 0 ; i < length ; i++) {
2292 array.add(readCharSequence());
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
2305 public final ArrayList readArrayList(ClassLoader loader) {
2310 ArrayList l = new ArrayList(N);
2311 readListInternal(l, N, loader);
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
2321 public final Object[] readArray(ClassLoader loader) {
2326 Object[] l = new Object[N];
2327 readArrayInternal(l, N, loader);
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
2337 public final SparseArray readSparseArray(ClassLoader loader) {
2342 SparseArray sa = new SparseArray(N);
2343 readSparseArrayInternal(sa, N, loader);
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
2352 public final SparseBooleanArray readSparseBooleanArray() {
2357 SparseBooleanArray sa = new SparseBooleanArray(N);
2358 readSparseBooleanArrayInternal(sa, N);
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.
2367 public final SparseIntArray readSparseIntArray() {
2372 SparseIntArray sa = new SparseIntArray(N);
2373 readSparseIntArrayInternal(sa, N);
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
2385 * @return A newly created ArrayList containing objects with the same data
2386 * as those that were previously written.
2388 * @see #writeTypedList
2390 public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
2395 ArrayList<T> l = new ArrayList<T>(N);
2397 if (readInt() != 0) {
2398 l.add(c.createFromParcel(this));
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
2414 * @return A newly created ArrayList containing objects with the same data
2415 * as those that were previously written.
2417 * @see #writeTypedList
2419 public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
2420 int M = list.size();
2423 for (; i < M && i < N; i++) {
2424 if (readInt() != 0) {
2425 list.set(i, c.createFromParcel(this));
2431 if (readInt() != 0) {
2432 list.add(c.createFromParcel(this));
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.
2448 * @return A newly created ArrayList containing strings with the same data
2449 * as those that were previously written.
2451 * @see #writeStringList
2453 public final ArrayList<String> createStringArrayList() {
2458 ArrayList<String> l = new ArrayList<String>(N);
2460 l.add(readString());
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.
2472 * @return A newly created ArrayList containing strings with the same data
2473 * as those that were previously written.
2475 * @see #writeBinderList
2477 public final ArrayList<IBinder> createBinderArrayList() {
2482 ArrayList<IBinder> l = new ArrayList<IBinder>(N);
2484 l.add(readStrongBinder());
2491 * Read into the given List items String objects that were written with
2492 * {@link #writeStringList} at the current dataPosition().
2494 * @return A newly created ArrayList containing strings with the same data
2495 * as those that were previously written.
2497 * @see #writeStringList
2499 public final void readStringList(List<String> list) {
2500 int M = list.size();
2503 for (; i < M && i < N; i++) {
2504 list.set(i, readString());
2507 list.add(readString());
2515 * Read into the given List items IBinder objects that were written with
2516 * {@link #writeBinderList} at the current dataPosition().
2518 * @see #writeBinderList
2520 public final void readBinderList(List<IBinder> list) {
2521 int M = list.size();
2524 for (; i < M && i < N; i++) {
2525 list.set(i, readStrongBinder());
2528 list.add(readStrongBinder());
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.
2540 * @see #writeParcelableList(List, int)
2543 public final <T extends Parcelable> List<T> readParcelableList(List<T> list, ClassLoader cl) {
2544 final int N = readInt();
2550 final int M = list.size();
2552 for (; i < M && i < N; i++) {
2553 list.set(i, (T) readParcelable(cl));
2556 list.add((T) readParcelable(cl));
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
2571 * @return A newly created array containing objects with the same data
2572 * as those that were previously written.
2574 * @see #writeTypedArray
2576 public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
2581 T[] l = c.newArray(N);
2582 for (int i=0; i<N; i++) {
2583 if (readInt() != 0) {
2584 l[i] = c.createFromParcel(this);
2590 public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
2592 if (N == val.length) {
2593 for (int i=0; i<N; i++) {
2594 if (readInt() != 0) {
2595 val[i] = c.createFromParcel(this);
2601 throw new RuntimeException("bad array lengths");
2610 public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
2611 return createTypedArray(c);
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.
2620 * @return A newly created object of the type that was previously
2623 * @see #writeTypedObject
2625 public final <T> T readTypedObject(Parcelable.Creator<T> c) {
2626 if (readInt() != 0) {
2627 return c.createFromParcel(this);
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.
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()}.
2644 * @see #writeTypedArray
2646 public final <T extends Parcelable> void writeParcelableArray(T[] value,
2647 int parcelableFlags) {
2648 if (value != null) {
2649 int N = value.length;
2651 for (int i=0; i<N; i++) {
2652 writeParcelable(value[i], parcelableFlags);
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.
2664 public final Object readValue(ClassLoader loader) {
2665 int type = readInt();
2672 return readString();
2678 return readHashMap(loader);
2680 case VAL_PARCELABLE:
2681 return readParcelable(loader);
2684 return (short) readInt();
2693 return readDouble();
2696 return readInt() == 1;
2698 case VAL_CHARSEQUENCE:
2699 return readCharSequence();
2702 return readArrayList(loader);
2704 case VAL_BOOLEANARRAY:
2705 return createBooleanArray();
2708 return createByteArray();
2710 case VAL_STRINGARRAY:
2711 return readStringArray();
2713 case VAL_CHARSEQUENCEARRAY:
2714 return readCharSequenceArray();
2717 return readStrongBinder();
2719 case VAL_OBJECTARRAY:
2720 return readArray(loader);
2723 return createIntArray();
2726 return createLongArray();
2731 case VAL_SERIALIZABLE:
2732 return readSerializable(loader);
2734 case VAL_PARCELABLEARRAY:
2735 return readParcelableArray(loader);
2737 case VAL_SPARSEARRAY:
2738 return readSparseArray(loader);
2740 case VAL_SPARSEBOOLEANARRAY:
2741 return readSparseBooleanArray();
2744 return readBundle(loader); // loading will be deferred
2746 case VAL_PERSISTABLEBUNDLE:
2747 return readPersistableBundle(loader);
2755 case VAL_DOUBLEARRAY:
2756 return createDoubleArray();
2759 int off = dataPosition() - 4;
2760 throw new RuntimeException(
2761 "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
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.
2776 @SuppressWarnings("unchecked")
2777 public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
2778 Parcelable.Creator<?> creator = readParcelableCreator(loader);
2779 if (creator == null) {
2782 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2783 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2784 (Parcelable.ClassLoaderCreator<?>) creator;
2785 return (T) classLoaderCreator.createFromParcel(this, loader);
2787 return (T) creator.createFromParcel(this);
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);
2799 return (T) creator.createFromParcel(this);
2803 public final Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) {
2804 String name = readString();
2808 Parcelable.Creator<?> creator;
2809 synchronized (mCreators) {
2810 HashMap<String,Parcelable.Creator<?>> map = mCreators.get(loader);
2812 map = new HashMap<>();
2813 mCreators.put(loader, map);
2815 creator = map.get(name);
2816 if (creator == null) {
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");
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);
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);
2843 creator = (Parcelable.Creator<?>) f.get(null);
2845 catch (IllegalAccessException e) {
2846 Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
2847 throw new BadParcelableException(
2848 "IllegalAccessException when unmarshalling: " + name);
2850 catch (ClassNotFoundException e) {
2851 Log.e(TAG, "Class not found when unmarshalling: " + name, e);
2852 throw new BadParcelableException(
2853 "ClassNotFoundException when unmarshalling: " + name);
2855 catch (NoSuchFieldException e) {
2856 throw new BadParcelableException("Parcelable protocol requires a "
2857 + "Parcelable.Creator object called "
2858 + "CREATOR on class " + name);
2860 if (creator == null) {
2861 throw new BadParcelableException("Parcelable protocol requires a "
2862 + "non-null Parcelable.Creator object called "
2863 + "CREATOR on class " + name);
2866 map.put(name, creator);
2874 * Read and return a new Parcelable array from the parcel.
2875 * The given class loader will be used to load any enclosed
2877 * @return the Parcelable array, or null if the array is null
2879 public final Parcelable[] readParcelableArray(ClassLoader loader) {
2884 Parcelable[] p = new Parcelable[N];
2885 for (int i = 0; i < N; i++) {
2886 p[i] = readParcelable(loader);
2892 public final <T extends Parcelable> T[] readParcelableArray(ClassLoader loader,
2898 T[] p = (T[]) Array.newInstance(clazz, N);
2899 for (int i = 0; i < N; i++) {
2900 p[i] = readParcelable(loader);
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.
2910 public final Serializable readSerializable() {
2911 return readSerializable(null);
2914 private final Serializable readSerializable(final ClassLoader loader) {
2915 String name = readString();
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.
2923 byte[] serializedData = createByteArray();
2924 ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
2926 ObjectInputStream ois = new ObjectInputStream(bais) {
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);
2937 return super.resolveClass(osClass);
2940 return (Serializable) ois.readObject();
2941 } catch (IOException ioe) {
2942 throw new RuntimeException("Parcelable encountered " +
2943 "IOException reading a Serializable object (name = " + name +
2945 } catch (ClassNotFoundException cnfe) {
2946 throw new RuntimeException("Parcelable encountered " +
2947 "ClassNotFoundException reading a Serializable object (name = "
2948 + name + ")", cnfe);
2952 // Cache of previously looked up CREATOR.createFromParcel() methods for
2953 // particular classes. Keys are the names of the classes, values are
2955 private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator<?>>>
2956 mCreators = new HashMap<>();
2958 /** @hide for internal use only. */
2959 static protected final Parcel obtain(int obj) {
2960 throw new UnsupportedOperationException();
2964 static protected final Parcel obtain(long obj) {
2965 final Parcel[] pool = sHolderPool;
2966 synchronized (pool) {
2968 for (int i=0; i<POOL_SIZE; i++) {
2972 if (DEBUG_RECYCLE) {
2973 p.mStack = new RuntimeException();
2980 return new Parcel(obj);
2983 private Parcel(long nativePtr) {
2984 if (DEBUG_RECYCLE) {
2985 mStack = new RuntimeException();
2987 //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
2991 private void init(long nativePtr) {
2992 if (nativePtr != 0) {
2993 mNativePtr = nativePtr;
2994 mOwnsNativeParcelObject = false;
2996 mNativePtr = nativeCreate();
2997 mOwnsNativeParcelObject = true;
3001 private void freeBuffer() {
3002 if (mOwnsNativeParcelObject) {
3003 updateNativeSize(nativeFreeBuffer(mNativePtr));
3007 private void destroy() {
3008 if (mNativePtr != 0) {
3009 if (mOwnsNativeParcelObject) {
3010 nativeDestroy(mNativePtr);
3011 updateNativeSize(0);
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);
3027 /* package */ void readMapInternal(Map outVal, int N,
3028 ClassLoader loader) {
3030 Object key = readValue(loader);
3031 Object value = readValue(loader);
3032 outVal.put(key, value);
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);
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);
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);
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);
3076 * @hide For testing only.
3078 public void readArrayMap(ArrayMap outVal, ClassLoader loader) {
3079 final int N = readInt();
3083 readArrayMapInternal(outVal, N, loader);
3087 * Reads an array set.
3089 * @param loader The class loader to use.
3093 public @Nullable ArraySet<? extends Object> readArraySet(ClassLoader loader) {
3094 final int size = readInt();
3098 ArraySet<Object> result = new ArraySet<>(size);
3099 for (int i = 0; i < size; i++) {
3100 Object value = readValue(loader);
3101 result.append(value);
3106 private void readListInternal(List outVal, int N,
3107 ClassLoader loader) {
3109 Object value = readValue(loader);
3110 //Log.d(TAG, "Unmarshalling value=" + value);
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);
3125 private void readSparseArrayInternal(SparseArray outVal, int N,
3126 ClassLoader loader) {
3128 int key = readInt();
3129 Object value = readValue(loader);
3130 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3131 outVal.append(key, value);
3137 private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
3139 int key = readInt();
3140 boolean value = this.readByte() == 1;
3141 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3142 outVal.append(key, value);
3147 private void readSparseIntArrayInternal(SparseIntArray outVal, int N) {
3149 int key = readInt();
3150 int value = readInt();
3151 outVal.append(key, value);
3159 public long getBlobAshmemSize() {
3160 return nativeGetBlobAshmemSize(mNativePtr);