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.CriticalNative;
31 import dalvik.annotation.optimization.FastNative;
32 import dalvik.system.VMRuntime;
34 import libcore.util.SneakyThrow;
36 import java.io.ByteArrayInputStream;
37 import java.io.ByteArrayOutputStream;
38 import java.io.FileDescriptor;
39 import java.io.FileNotFoundException;
40 import java.io.IOException;
41 import java.io.ObjectInputStream;
42 import java.io.ObjectOutputStream;
43 import java.io.ObjectStreamClass;
44 import java.io.Serializable;
45 import java.lang.reflect.Array;
46 import java.lang.reflect.Field;
47 import java.lang.reflect.Modifier;
48 import java.util.ArrayList;
49 import java.util.Arrays;
50 import java.util.HashMap;
51 import java.util.List;
56 * Container for a message (data and object references) that can
57 * be sent through an IBinder. A Parcel can contain both flattened data
58 * that will be unflattened on the other side of the IPC (using the various
59 * methods here for writing specific types, or the general
60 * {@link Parcelable} interface), and references to live {@link IBinder}
61 * objects that will result in the other side receiving a proxy IBinder
62 * connected with the original IBinder in the Parcel.
64 * <p class="note">Parcel is <strong>not</strong> a general-purpose
65 * serialization mechanism. This class (and the corresponding
66 * {@link Parcelable} API for placing arbitrary objects into a Parcel) is
67 * designed as a high-performance IPC transport. As such, it is not
68 * appropriate to place any Parcel data in to persistent storage: changes
69 * in the underlying implementation of any of the data in the Parcel can
70 * render older data unreadable.</p>
72 * <p>The bulk of the Parcel API revolves around reading and writing data
73 * of various types. There are six major classes of such functions available.</p>
77 * <p>The most basic data functions are for writing and reading primitive
78 * data types: {@link #writeByte}, {@link #readByte}, {@link #writeDouble},
79 * {@link #readDouble}, {@link #writeFloat}, {@link #readFloat}, {@link #writeInt},
80 * {@link #readInt}, {@link #writeLong}, {@link #readLong},
81 * {@link #writeString}, {@link #readString}. Most other
82 * data operations are built on top of these. The given data is written and
83 * read using the endianess of the host CPU.</p>
85 * <h3>Primitive Arrays</h3>
87 * <p>There are a variety of methods for reading and writing raw arrays
88 * of primitive objects, which generally result in writing a 4-byte length
89 * followed by the primitive data items. The methods for reading can either
90 * read the data into an existing array, or create and return a new array.
91 * These available types are:</p>
94 * <li> {@link #writeBooleanArray(boolean[])},
95 * {@link #readBooleanArray(boolean[])}, {@link #createBooleanArray()}
96 * <li> {@link #writeByteArray(byte[])},
97 * {@link #writeByteArray(byte[], int, int)}, {@link #readByteArray(byte[])},
98 * {@link #createByteArray()}
99 * <li> {@link #writeCharArray(char[])}, {@link #readCharArray(char[])},
100 * {@link #createCharArray()}
101 * <li> {@link #writeDoubleArray(double[])}, {@link #readDoubleArray(double[])},
102 * {@link #createDoubleArray()}
103 * <li> {@link #writeFloatArray(float[])}, {@link #readFloatArray(float[])},
104 * {@link #createFloatArray()}
105 * <li> {@link #writeIntArray(int[])}, {@link #readIntArray(int[])},
106 * {@link #createIntArray()}
107 * <li> {@link #writeLongArray(long[])}, {@link #readLongArray(long[])},
108 * {@link #createLongArray()}
109 * <li> {@link #writeStringArray(String[])}, {@link #readStringArray(String[])},
110 * {@link #createStringArray()}.
111 * <li> {@link #writeSparseBooleanArray(SparseBooleanArray)},
112 * {@link #readSparseBooleanArray()}.
115 * <h3>Parcelables</h3>
117 * <p>The {@link Parcelable} protocol provides an extremely efficient (but
118 * low-level) protocol for objects to write and read themselves from Parcels.
119 * You can use the direct methods {@link #writeParcelable(Parcelable, int)}
120 * and {@link #readParcelable(ClassLoader)} or
121 * {@link #writeParcelableArray} and
122 * {@link #readParcelableArray(ClassLoader)} to write or read. These
123 * methods write both the class type and its data to the Parcel, allowing
124 * that class to be reconstructed from the appropriate class loader when
127 * <p>There are also some methods that provide a more efficient way to work
128 * with Parcelables: {@link #writeTypedObject}, {@link #writeTypedArray},
129 * {@link #writeTypedList}, {@link #readTypedObject},
130 * {@link #createTypedArray} and {@link #createTypedArrayList}. These methods
131 * do not write the class information of the original object: instead, the
132 * caller of the read function must know what type to expect and pass in the
133 * appropriate {@link Parcelable.Creator Parcelable.Creator} instead to
134 * properly construct the new object and read its data. (To more efficient
135 * write and read a single Parcelable object that is not null, you can directly
136 * call {@link Parcelable#writeToParcel Parcelable.writeToParcel} and
137 * {@link Parcelable.Creator#createFromParcel Parcelable.Creator.createFromParcel}
142 * <p>A special type-safe container, called {@link Bundle}, is available
143 * for key/value maps of heterogeneous values. This has many optimizations
144 * for improved performance when reading and writing data, and its type-safe
145 * API avoids difficult to debug type errors when finally marshalling the
146 * data contents into a Parcel. The methods to use are
147 * {@link #writeBundle(Bundle)}, {@link #readBundle()}, and
148 * {@link #readBundle(ClassLoader)}.
150 * <h3>Active Objects</h3>
152 * <p>An unusual feature of Parcel is the ability to read and write active
153 * objects. For these objects the actual contents of the object is not
154 * written, rather a special token referencing the object is written. When
155 * reading the object back from the Parcel, you do not get a new instance of
156 * the object, but rather a handle that operates on the exact same object that
157 * was originally written. There are two forms of active objects available.</p>
159 * <p>{@link Binder} objects are a core facility of Android's general cross-process
160 * communication system. The {@link IBinder} interface describes an abstract
161 * protocol with a Binder object. Any such interface can be written in to
162 * a Parcel, and upon reading you will receive either the original object
163 * implementing that interface or a special proxy implementation
164 * that communicates calls back to the original object. The methods to use are
165 * {@link #writeStrongBinder(IBinder)},
166 * {@link #writeStrongInterface(IInterface)}, {@link #readStrongBinder()},
167 * {@link #writeBinderArray(IBinder[])}, {@link #readBinderArray(IBinder[])},
168 * {@link #createBinderArray()},
169 * {@link #writeBinderList(List)}, {@link #readBinderList(List)},
170 * {@link #createBinderArrayList()}.</p>
172 * <p>FileDescriptor objects, representing raw Linux file descriptor identifiers,
173 * can be written and {@link ParcelFileDescriptor} objects returned to operate
174 * on the original file descriptor. The returned file descriptor is a dup
175 * of the original file descriptor: the object and fd is different, but
176 * operating on the same underlying file stream, with the same position, etc.
177 * The methods to use are {@link #writeFileDescriptor(FileDescriptor)},
178 * {@link #readFileDescriptor()}.
180 * <h3>Untyped Containers</h3>
182 * <p>A final class of methods are for writing and reading standard Java
183 * containers of arbitrary types. These all revolve around the
184 * {@link #writeValue(Object)} and {@link #readValue(ClassLoader)} methods
185 * which define the types of objects allowed. The container methods are
186 * {@link #writeArray(Object[])}, {@link #readArray(ClassLoader)},
187 * {@link #writeList(List)}, {@link #readList(List, ClassLoader)},
188 * {@link #readArrayList(ClassLoader)},
189 * {@link #writeMap(Map)}, {@link #readMap(Map, ClassLoader)},
190 * {@link #writeSparseArray(SparseArray)},
191 * {@link #readSparseArray(ClassLoader)}.
193 public final class Parcel {
194 private static final boolean DEBUG_RECYCLE = false;
195 private static final boolean DEBUG_ARRAY_MAP = false;
196 private static final String TAG = "Parcel";
198 @SuppressWarnings({"UnusedDeclaration"})
199 private long mNativePtr; // used by native code
202 * Flag indicating if {@link #mNativePtr} was allocated by this object,
203 * indicating that we're responsible for its lifecycle.
205 private boolean mOwnsNativeParcelObject;
206 private long mNativeSize;
208 private ArrayMap<Class, Object> mClassCookies;
210 private RuntimeException mStack;
212 private static final int POOL_SIZE = 6;
213 private static final Parcel[] sOwnedPool = new Parcel[POOL_SIZE];
214 private static final Parcel[] sHolderPool = new Parcel[POOL_SIZE];
216 // Keep in sync with frameworks/native/include/private/binder/ParcelValTypes.h.
217 private static final int VAL_NULL = -1;
218 private static final int VAL_STRING = 0;
219 private static final int VAL_INTEGER = 1;
220 private static final int VAL_MAP = 2;
221 private static final int VAL_BUNDLE = 3;
222 private static final int VAL_PARCELABLE = 4;
223 private static final int VAL_SHORT = 5;
224 private static final int VAL_LONG = 6;
225 private static final int VAL_FLOAT = 7;
226 private static final int VAL_DOUBLE = 8;
227 private static final int VAL_BOOLEAN = 9;
228 private static final int VAL_CHARSEQUENCE = 10;
229 private static final int VAL_LIST = 11;
230 private static final int VAL_SPARSEARRAY = 12;
231 private static final int VAL_BYTEARRAY = 13;
232 private static final int VAL_STRINGARRAY = 14;
233 private static final int VAL_IBINDER = 15;
234 private static final int VAL_PARCELABLEARRAY = 16;
235 private static final int VAL_OBJECTARRAY = 17;
236 private static final int VAL_INTARRAY = 18;
237 private static final int VAL_LONGARRAY = 19;
238 private static final int VAL_BYTE = 20;
239 private static final int VAL_SERIALIZABLE = 21;
240 private static final int VAL_SPARSEBOOLEANARRAY = 22;
241 private static final int VAL_BOOLEANARRAY = 23;
242 private static final int VAL_CHARSEQUENCEARRAY = 24;
243 private static final int VAL_PERSISTABLEBUNDLE = 25;
244 private static final int VAL_SIZE = 26;
245 private static final int VAL_SIZEF = 27;
246 private static final int VAL_DOUBLEARRAY = 28;
248 // The initial int32 in a Binder call's reply Parcel header:
249 // Keep these in sync with libbinder's binder/Status.h.
250 private static final int EX_SECURITY = -1;
251 private static final int EX_BAD_PARCELABLE = -2;
252 private static final int EX_ILLEGAL_ARGUMENT = -3;
253 private static final int EX_NULL_POINTER = -4;
254 private static final int EX_ILLEGAL_STATE = -5;
255 private static final int EX_NETWORK_MAIN_THREAD = -6;
256 private static final int EX_UNSUPPORTED_OPERATION = -7;
257 private static final int EX_SERVICE_SPECIFIC = -8;
258 private static final int EX_PARCELABLE = -9;
259 private static final int EX_HAS_REPLY_HEADER = -128; // special; see below
260 // EX_TRANSACTION_FAILED is used exclusively in native code.
261 // see libbinder's binder/Status.h
262 private static final int EX_TRANSACTION_FAILED = -129;
265 private static native int nativeDataSize(long nativePtr);
267 private static native int nativeDataAvail(long nativePtr);
269 private static native int nativeDataPosition(long nativePtr);
271 private static native int nativeDataCapacity(long nativePtr);
273 private static native long nativeSetDataSize(long nativePtr, int size);
275 private static native void nativeSetDataPosition(long nativePtr, int pos);
277 private static native void nativeSetDataCapacity(long nativePtr, int size);
280 private static native boolean nativePushAllowFds(long nativePtr, boolean allowFds);
282 private static native void nativeRestoreAllowFds(long nativePtr, boolean lastValue);
284 private static native void nativeWriteByteArray(long nativePtr, byte[] b, int offset, int len);
285 private static native void nativeWriteBlob(long nativePtr, byte[] b, int offset, int len);
287 private static native void nativeWriteInt(long nativePtr, int val);
289 private static native void nativeWriteLong(long nativePtr, long val);
291 private static native void nativeWriteFloat(long nativePtr, float val);
293 private static native void nativeWriteDouble(long nativePtr, double val);
294 static native void nativeWriteString(long nativePtr, String val);
295 private static native void nativeWriteStrongBinder(long nativePtr, IBinder val);
296 private static native long nativeWriteFileDescriptor(long nativePtr, FileDescriptor val);
298 private static native byte[] nativeCreateByteArray(long nativePtr);
299 private static native boolean nativeReadByteArray(long nativePtr, byte[] dest, int destLen);
300 private static native byte[] nativeReadBlob(long nativePtr);
302 private static native int nativeReadInt(long nativePtr);
304 private static native long nativeReadLong(long nativePtr);
306 private static native float nativeReadFloat(long nativePtr);
308 private static native double nativeReadDouble(long nativePtr);
309 static native String nativeReadString(long nativePtr);
310 private static native IBinder nativeReadStrongBinder(long nativePtr);
311 private static native FileDescriptor nativeReadFileDescriptor(long nativePtr);
313 private static native long nativeCreate();
314 private static native long nativeFreeBuffer(long nativePtr);
315 private static native void nativeDestroy(long nativePtr);
317 private static native byte[] nativeMarshall(long nativePtr);
318 private static native long nativeUnmarshall(
319 long nativePtr, byte[] data, int offset, int length);
320 private static native int nativeCompareData(long thisNativePtr, long otherNativePtr);
321 private static native long nativeAppendFrom(
322 long thisNativePtr, long otherNativePtr, int offset, int length);
324 private static native boolean nativeHasFileDescriptors(long nativePtr);
325 private static native void nativeWriteInterfaceToken(long nativePtr, String interfaceName);
326 private static native void nativeEnforceInterface(long nativePtr, String interfaceName);
329 private static native long nativeGetBlobAshmemSize(long nativePtr);
331 public final static Parcelable.Creator<String> STRING_CREATOR
332 = new Parcelable.Creator<String>() {
333 public String createFromParcel(Parcel source) {
334 return source.readString();
336 public String[] newArray(int size) {
337 return new String[size];
344 public static class ReadWriteHelper {
345 public static final ReadWriteHelper DEFAULT = new ReadWriteHelper();
348 * Called when writing a string to a parcel. Subclasses wanting to write a string
349 * must use {@link #writeStringNoHelper(String)} to avoid
350 * infinity recursive calls.
352 public void writeString(Parcel p, String s) {
353 nativeWriteString(p.mNativePtr, s);
357 * Called when reading a string to a parcel. Subclasses wanting to read a string
358 * must use {@link #readStringNoHelper()} to avoid
359 * infinity recursive calls.
361 public String readString(Parcel p) {
362 return nativeReadString(p.mNativePtr);
366 private ReadWriteHelper mReadWriteHelper = ReadWriteHelper.DEFAULT;
369 * Retrieve a new Parcel object from the pool.
371 public static Parcel obtain() {
372 final Parcel[] pool = sOwnedPool;
373 synchronized (pool) {
375 for (int i=0; i<POOL_SIZE; i++) {
380 p.mStack = new RuntimeException();
382 p.mReadWriteHelper = ReadWriteHelper.DEFAULT;
387 return new Parcel(0);
391 * Put a Parcel object back into the pool. You must not touch
392 * the object after this call.
394 public final void recycle() {
395 if (DEBUG_RECYCLE) mStack = null;
399 if (mOwnsNativeParcelObject) {
406 synchronized (pool) {
407 for (int i=0; i<POOL_SIZE; i++) {
408 if (pool[i] == null) {
417 * Set a {@link ReadWriteHelper}, which can be used to avoid having duplicate strings, for
422 public void setReadWriteHelper(ReadWriteHelper helper) {
423 mReadWriteHelper = helper != null ? helper : ReadWriteHelper.DEFAULT;
427 * @return whether this parcel has a {@link ReadWriteHelper}.
431 public boolean hasReadWriteHelper() {
432 return (mReadWriteHelper != null) && (mReadWriteHelper != ReadWriteHelper.DEFAULT);
436 public static native long getGlobalAllocSize();
439 public static native long getGlobalAllocCount();
442 * Returns the total amount of data contained in the parcel.
444 public final int dataSize() {
445 return nativeDataSize(mNativePtr);
449 * Returns the amount of data remaining to be read from the
450 * parcel. That is, {@link #dataSize}-{@link #dataPosition}.
452 public final int dataAvail() {
453 return nativeDataAvail(mNativePtr);
457 * Returns the current position in the parcel data. Never
458 * more than {@link #dataSize}.
460 public final int dataPosition() {
461 return nativeDataPosition(mNativePtr);
465 * Returns the total amount of space in the parcel. This is always
466 * >= {@link #dataSize}. The difference between it and dataSize() is the
467 * amount of room left until the parcel needs to re-allocate its
470 public final int dataCapacity() {
471 return nativeDataCapacity(mNativePtr);
475 * Change the amount of data in the parcel. Can be either smaller or
476 * larger than the current size. If larger than the current capacity,
477 * more memory will be allocated.
479 * @param size The new number of bytes in the Parcel.
481 public final void setDataSize(int size) {
482 updateNativeSize(nativeSetDataSize(mNativePtr, size));
486 * Move the current read/write position in the parcel.
487 * @param pos New offset in the parcel; must be between 0 and
490 public final void setDataPosition(int pos) {
491 nativeSetDataPosition(mNativePtr, pos);
495 * Change the capacity (current available space) of the parcel.
497 * @param size The new capacity of the parcel, in bytes. Can not be
498 * less than {@link #dataSize} -- that is, you can not drop existing data
501 public final void setDataCapacity(int size) {
502 nativeSetDataCapacity(mNativePtr, size);
506 public final boolean pushAllowFds(boolean allowFds) {
507 return nativePushAllowFds(mNativePtr, allowFds);
511 public final void restoreAllowFds(boolean lastValue) {
512 nativeRestoreAllowFds(mNativePtr, lastValue);
516 * Returns the raw bytes of the parcel.
518 * <p class="note">The data you retrieve here <strong>must not</strong>
519 * be placed in any kind of persistent storage (on local disk, across
520 * a network, etc). For that, you should use standard serialization
521 * or another kind of general serialization mechanism. The Parcel
522 * marshalled representation is highly optimized for local IPC, and as
523 * such does not attempt to maintain compatibility with data created
524 * in different versions of the platform.
526 public final byte[] marshall() {
527 return nativeMarshall(mNativePtr);
531 * Set the bytes in data to be the raw bytes of this Parcel.
533 public final void unmarshall(byte[] data, int offset, int length) {
534 updateNativeSize(nativeUnmarshall(mNativePtr, data, offset, length));
537 public final void appendFrom(Parcel parcel, int offset, int length) {
538 updateNativeSize(nativeAppendFrom(mNativePtr, parcel.mNativePtr, offset, length));
542 public final int compareData(Parcel other) {
543 return nativeCompareData(mNativePtr, other.mNativePtr);
547 public final void setClassCookie(Class clz, Object cookie) {
548 if (mClassCookies == null) {
549 mClassCookies = new ArrayMap<>();
551 mClassCookies.put(clz, cookie);
555 public final Object getClassCookie(Class clz) {
556 return mClassCookies != null ? mClassCookies.get(clz) : null;
560 public final void adoptClassCookies(Parcel from) {
561 mClassCookies = from.mClassCookies;
565 * Report whether the parcel contains any marshalled file descriptors.
567 public final boolean hasFileDescriptors() {
568 return nativeHasFileDescriptors(mNativePtr);
572 * Store or read an IBinder interface token in the parcel at the current
573 * {@link #dataPosition}. This is used to validate that the marshalled
574 * transaction is intended for the target interface.
576 public final void writeInterfaceToken(String interfaceName) {
577 nativeWriteInterfaceToken(mNativePtr, interfaceName);
580 public final void enforceInterface(String interfaceName) {
581 nativeEnforceInterface(mNativePtr, interfaceName);
585 * Write a byte array into the parcel at the current {@link #dataPosition},
586 * growing {@link #dataCapacity} if needed.
587 * @param b Bytes to place into the parcel.
589 public final void writeByteArray(byte[] b) {
590 writeByteArray(b, 0, (b != null) ? b.length : 0);
594 * Write a byte array into the parcel at the current {@link #dataPosition},
595 * growing {@link #dataCapacity} if needed.
596 * @param b Bytes to place into the parcel.
597 * @param offset Index of first byte to be written.
598 * @param len Number of bytes to write.
600 public final void writeByteArray(byte[] b, int offset, int len) {
605 Arrays.checkOffsetAndCount(b.length, offset, len);
606 nativeWriteByteArray(mNativePtr, b, offset, len);
610 * Write a blob of data into the parcel at the current {@link #dataPosition},
611 * growing {@link #dataCapacity} if needed.
612 * @param b Bytes to place into the parcel.
616 public final void writeBlob(byte[] b) {
617 writeBlob(b, 0, (b != null) ? b.length : 0);
621 * Write a blob of data into the parcel at the current {@link #dataPosition},
622 * growing {@link #dataCapacity} if needed.
623 * @param b Bytes to place into the parcel.
624 * @param offset Index of first byte to be written.
625 * @param len Number of bytes to write.
629 public final void writeBlob(byte[] b, int offset, int len) {
634 Arrays.checkOffsetAndCount(b.length, offset, len);
635 nativeWriteBlob(mNativePtr, b, offset, len);
639 * Write an integer value into the parcel at the current dataPosition(),
640 * growing dataCapacity() if needed.
642 public final void writeInt(int val) {
643 nativeWriteInt(mNativePtr, val);
647 * Write a long integer value into the parcel at the current dataPosition(),
648 * growing dataCapacity() if needed.
650 public final void writeLong(long val) {
651 nativeWriteLong(mNativePtr, val);
655 * Write a floating point value into the parcel at the current
656 * dataPosition(), growing dataCapacity() if needed.
658 public final void writeFloat(float val) {
659 nativeWriteFloat(mNativePtr, val);
663 * Write a double precision floating point value into the parcel at the
664 * current dataPosition(), growing dataCapacity() if needed.
666 public final void writeDouble(double val) {
667 nativeWriteDouble(mNativePtr, val);
671 * Write a string value into the parcel at the current dataPosition(),
672 * growing dataCapacity() if needed.
674 public final void writeString(String val) {
675 mReadWriteHelper.writeString(this, val);
679 * Write a string without going though a {@link ReadWriteHelper}. Subclasses of
680 * {@link ReadWriteHelper} must use this method instead of {@link #writeString} to avoid
681 * infinity recursive calls.
685 public void writeStringNoHelper(String val) {
686 nativeWriteString(mNativePtr, val);
690 public final void writeBoolean(boolean val) {
691 writeInt(val ? 1 : 0);
695 * Write a CharSequence value into the parcel at the current dataPosition(),
696 * growing dataCapacity() if needed.
699 public final void writeCharSequence(CharSequence val) {
700 TextUtils.writeToParcel(val, this, 0);
704 * Write an object into the parcel at the current dataPosition(),
705 * growing dataCapacity() if needed.
707 public final void writeStrongBinder(IBinder val) {
708 nativeWriteStrongBinder(mNativePtr, val);
712 * Write an object into the parcel at the current dataPosition(),
713 * growing dataCapacity() if needed.
715 public final void writeStrongInterface(IInterface val) {
716 writeStrongBinder(val == null ? null : val.asBinder());
720 * Write a FileDescriptor into the parcel at the current dataPosition(),
721 * growing dataCapacity() if needed.
723 * <p class="caution">The file descriptor will not be closed, which may
724 * result in file descriptor leaks when objects are returned from Binder
725 * calls. Use {@link ParcelFileDescriptor#writeToParcel} instead, which
726 * accepts contextual flags and will close the original file descriptor
727 * if {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set.</p>
729 public final void writeFileDescriptor(FileDescriptor val) {
730 updateNativeSize(nativeWriteFileDescriptor(mNativePtr, val));
733 private void updateNativeSize(long newNativeSize) {
734 if (mOwnsNativeParcelObject) {
735 if (newNativeSize > Integer.MAX_VALUE) {
736 newNativeSize = Integer.MAX_VALUE;
738 if (newNativeSize != mNativeSize) {
739 int delta = (int) (newNativeSize - mNativeSize);
741 VMRuntime.getRuntime().registerNativeAllocation(delta);
743 VMRuntime.getRuntime().registerNativeFree(-delta);
745 mNativeSize = newNativeSize;
752 * This will be the new name for writeFileDescriptor, for consistency.
754 public final void writeRawFileDescriptor(FileDescriptor val) {
755 nativeWriteFileDescriptor(mNativePtr, val);
760 * Write an array of FileDescriptor objects into the Parcel.
762 * @param value The array of objects to be written.
764 public final void writeRawFileDescriptorArray(FileDescriptor[] value) {
766 int N = value.length;
768 for (int i=0; i<N; i++) {
769 writeRawFileDescriptor(value[i]);
777 * Write a byte value into the parcel at the current dataPosition(),
778 * growing dataCapacity() if needed.
780 public final void writeByte(byte val) {
785 * Please use {@link #writeBundle} instead. Flattens a Map into the parcel
786 * at the current dataPosition(),
787 * growing dataCapacity() if needed. The Map keys must be String objects.
788 * The Map values are written using {@link #writeValue} and must follow
789 * the specification there.
791 * <p>It is strongly recommended to use {@link #writeBundle} instead of
792 * this method, since the Bundle class provides a type-safe API that
793 * allows you to avoid mysterious type errors at the point of marshalling.
795 public final void writeMap(Map val) {
796 writeMapInternal((Map<String, Object>) val);
800 * Flatten a Map into the parcel at the current dataPosition(),
801 * growing dataCapacity() if needed. The Map keys must be String objects.
803 /* package */ void writeMapInternal(Map<String,Object> val) {
808 Set<Map.Entry<String,Object>> entries = val.entrySet();
809 writeInt(entries.size());
810 for (Map.Entry<String,Object> e : entries) {
811 writeValue(e.getKey());
812 writeValue(e.getValue());
817 * Flatten an ArrayMap into the parcel at the current dataPosition(),
818 * growing dataCapacity() if needed. The Map keys must be String objects.
820 /* package */ void writeArrayMapInternal(ArrayMap<String, Object> val) {
825 // Keep the format of this Parcel in sync with writeToParcelInner() in
826 // frameworks/native/libs/binder/PersistableBundle.cpp.
827 final int N = val.size();
829 if (DEBUG_ARRAY_MAP) {
830 RuntimeException here = new RuntimeException("here");
831 here.fillInStackTrace();
832 Log.d(TAG, "Writing " + N + " ArrayMap entries", here);
835 for (int i=0; i<N; i++) {
836 if (DEBUG_ARRAY_MAP) startPos = dataPosition();
837 writeString(val.keyAt(i));
838 writeValue(val.valueAt(i));
839 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Write #" + i + " "
840 + (dataPosition()-startPos) + " bytes: key=0x"
841 + Integer.toHexString(val.keyAt(i) != null ? val.keyAt(i).hashCode() : 0)
842 + " " + val.keyAt(i));
847 * @hide For testing only.
849 public void writeArrayMap(ArrayMap<String, Object> val) {
850 writeArrayMapInternal(val);
854 * Write an array set to the parcel.
856 * @param val The array set to write.
860 public void writeArraySet(@Nullable ArraySet<? extends Object> val) {
861 final int size = (val != null) ? val.size() : -1;
863 for (int i = 0; i < size; i++) {
864 writeValue(val.valueAt(i));
869 * Flatten a Bundle into the parcel at the current dataPosition(),
870 * growing dataCapacity() if needed.
872 public final void writeBundle(Bundle val) {
878 val.writeToParcel(this, 0);
882 * Flatten a PersistableBundle into the parcel at the current dataPosition(),
883 * growing dataCapacity() if needed.
885 public final void writePersistableBundle(PersistableBundle val) {
891 val.writeToParcel(this, 0);
895 * Flatten a Size into the parcel at the current dataPosition(),
896 * growing dataCapacity() if needed.
898 public final void writeSize(Size val) {
899 writeInt(val.getWidth());
900 writeInt(val.getHeight());
904 * Flatten a SizeF into the parcel at the current dataPosition(),
905 * growing dataCapacity() if needed.
907 public final void writeSizeF(SizeF val) {
908 writeFloat(val.getWidth());
909 writeFloat(val.getHeight());
913 * Flatten a List into the parcel at the current dataPosition(), growing
914 * dataCapacity() if needed. The List values are written using
915 * {@link #writeValue} and must follow the specification there.
917 public final void writeList(List val) {
926 writeValue(val.get(i));
932 * Flatten an Object array into the parcel at the current dataPosition(),
933 * growing dataCapacity() if needed. The array values are written using
934 * {@link #writeValue} and must follow the specification there.
936 public final void writeArray(Object[] val) {
951 * Flatten a generic SparseArray into the parcel at the current
952 * dataPosition(), growing dataCapacity() if needed. The SparseArray
953 * values are written using {@link #writeValue} and must follow the
954 * specification there.
956 public final void writeSparseArray(SparseArray<Object> val) {
965 writeInt(val.keyAt(i));
966 writeValue(val.valueAt(i));
971 public final void writeSparseBooleanArray(SparseBooleanArray val) {
980 writeInt(val.keyAt(i));
981 writeByte((byte)(val.valueAt(i) ? 1 : 0));
989 public final void writeSparseIntArray(SparseIntArray val) {
998 writeInt(val.keyAt(i));
999 writeInt(val.valueAt(i));
1004 public final void writeBooleanArray(boolean[] val) {
1008 for (int i=0; i<N; i++) {
1009 writeInt(val[i] ? 1 : 0);
1016 public final boolean[] createBooleanArray() {
1018 // >>2 as a fast divide-by-4 works in the create*Array() functions
1019 // because dataAvail() will never return a negative number. 4 is
1020 // the size of a stored boolean in the stream.
1021 if (N >= 0 && N <= (dataAvail() >> 2)) {
1022 boolean[] val = new boolean[N];
1023 for (int i=0; i<N; i++) {
1024 val[i] = readInt() != 0;
1032 public final void readBooleanArray(boolean[] val) {
1034 if (N == val.length) {
1035 for (int i=0; i<N; i++) {
1036 val[i] = readInt() != 0;
1039 throw new RuntimeException("bad array lengths");
1043 public final void writeCharArray(char[] val) {
1047 for (int i=0; i<N; i++) {
1048 writeInt((int)val[i]);
1055 public final char[] createCharArray() {
1057 if (N >= 0 && N <= (dataAvail() >> 2)) {
1058 char[] val = new char[N];
1059 for (int i=0; i<N; i++) {
1060 val[i] = (char)readInt();
1068 public final void readCharArray(char[] val) {
1070 if (N == val.length) {
1071 for (int i=0; i<N; i++) {
1072 val[i] = (char)readInt();
1075 throw new RuntimeException("bad array lengths");
1079 public final void writeIntArray(int[] val) {
1083 for (int i=0; i<N; i++) {
1091 public final int[] createIntArray() {
1093 if (N >= 0 && N <= (dataAvail() >> 2)) {
1094 int[] val = new int[N];
1095 for (int i=0; i<N; i++) {
1104 public final void readIntArray(int[] val) {
1106 if (N == val.length) {
1107 for (int i=0; i<N; i++) {
1111 throw new RuntimeException("bad array lengths");
1115 public final void writeLongArray(long[] val) {
1119 for (int i=0; i<N; i++) {
1127 public final long[] createLongArray() {
1129 // >>3 because stored longs are 64 bits
1130 if (N >= 0 && N <= (dataAvail() >> 3)) {
1131 long[] val = new long[N];
1132 for (int i=0; i<N; i++) {
1133 val[i] = readLong();
1141 public final void readLongArray(long[] val) {
1143 if (N == val.length) {
1144 for (int i=0; i<N; i++) {
1145 val[i] = readLong();
1148 throw new RuntimeException("bad array lengths");
1152 public final void writeFloatArray(float[] val) {
1156 for (int i=0; i<N; i++) {
1164 public final float[] createFloatArray() {
1166 // >>2 because stored floats are 4 bytes
1167 if (N >= 0 && N <= (dataAvail() >> 2)) {
1168 float[] val = new float[N];
1169 for (int i=0; i<N; i++) {
1170 val[i] = readFloat();
1178 public final void readFloatArray(float[] val) {
1180 if (N == val.length) {
1181 for (int i=0; i<N; i++) {
1182 val[i] = readFloat();
1185 throw new RuntimeException("bad array lengths");
1189 public final void writeDoubleArray(double[] val) {
1193 for (int i=0; i<N; i++) {
1194 writeDouble(val[i]);
1201 public final double[] createDoubleArray() {
1203 // >>3 because stored doubles are 8 bytes
1204 if (N >= 0 && N <= (dataAvail() >> 3)) {
1205 double[] val = new double[N];
1206 for (int i=0; i<N; i++) {
1207 val[i] = readDouble();
1215 public final void readDoubleArray(double[] val) {
1217 if (N == val.length) {
1218 for (int i=0; i<N; i++) {
1219 val[i] = readDouble();
1222 throw new RuntimeException("bad array lengths");
1226 public final void writeStringArray(String[] val) {
1230 for (int i=0; i<N; i++) {
1231 writeString(val[i]);
1238 public final String[] createStringArray() {
1241 String[] val = new String[N];
1242 for (int i=0; i<N; i++) {
1243 val[i] = readString();
1251 public final void readStringArray(String[] val) {
1253 if (N == val.length) {
1254 for (int i=0; i<N; i++) {
1255 val[i] = readString();
1258 throw new RuntimeException("bad array lengths");
1262 public final void writeBinderArray(IBinder[] val) {
1266 for (int i=0; i<N; i++) {
1267 writeStrongBinder(val[i]);
1277 public final void writeCharSequenceArray(CharSequence[] val) {
1281 for (int i=0; i<N; i++) {
1282 writeCharSequence(val[i]);
1292 public final void writeCharSequenceList(ArrayList<CharSequence> val) {
1296 for (int i=0; i<N; i++) {
1297 writeCharSequence(val.get(i));
1304 public final IBinder[] createBinderArray() {
1307 IBinder[] val = new IBinder[N];
1308 for (int i=0; i<N; i++) {
1309 val[i] = readStrongBinder();
1317 public final void readBinderArray(IBinder[] val) {
1319 if (N == val.length) {
1320 for (int i=0; i<N; i++) {
1321 val[i] = readStrongBinder();
1324 throw new RuntimeException("bad array lengths");
1329 * Flatten a List containing a particular object type into the parcel, at
1330 * the current dataPosition() and growing dataCapacity() if needed. The
1331 * type of the objects in the list must be one that implements Parcelable.
1332 * Unlike the generic writeList() method, however, only the raw data of the
1333 * objects is written and not their type, so you must use the corresponding
1334 * readTypedList() to unmarshall them.
1336 * @param val The list of objects to be written.
1338 * @see #createTypedArrayList
1339 * @see #readTypedList
1342 public final <T extends Parcelable> void writeTypedList(List<T> val) {
1343 writeTypedList(val, 0);
1349 public <T extends Parcelable> void writeTypedList(List<T> val, int parcelableFlags) {
1358 writeTypedObject(val.get(i), parcelableFlags);
1364 * Flatten a List containing String objects into the parcel, at
1365 * the current dataPosition() and growing dataCapacity() if needed. They
1366 * can later be retrieved with {@link #createStringArrayList} or
1367 * {@link #readStringList}.
1369 * @param val The list of strings to be written.
1371 * @see #createStringArrayList
1372 * @see #readStringList
1374 public final void writeStringList(List<String> val) {
1383 writeString(val.get(i));
1389 * Flatten a List containing IBinder objects into the parcel, at
1390 * the current dataPosition() and growing dataCapacity() if needed. They
1391 * can later be retrieved with {@link #createBinderArrayList} or
1392 * {@link #readBinderList}.
1394 * @param val The list of strings to be written.
1396 * @see #createBinderArrayList
1397 * @see #readBinderList
1399 public final void writeBinderList(List<IBinder> val) {
1408 writeStrongBinder(val.get(i));
1414 * Flatten a {@code List} containing arbitrary {@code Parcelable} objects into this parcel
1415 * at the current position. They can later be retrieved using
1416 * {@link #readParcelableList(List, ClassLoader)} if required.
1418 * @see #readParcelableList(List, ClassLoader)
1421 public final <T extends Parcelable> void writeParcelableList(List<T> val, int flags) {
1431 writeParcelable(val.get(i), flags);
1437 * Flatten a homogeneous array containing a particular object type into
1439 * the current dataPosition() and growing dataCapacity() if needed. The
1440 * type of the objects in the array must be one that implements Parcelable.
1441 * Unlike the {@link #writeParcelableArray} method, however, only the
1442 * raw data of the objects is written and not their type, so you must use
1443 * {@link #readTypedArray} with the correct corresponding
1444 * {@link Parcelable.Creator} implementation to unmarshall them.
1446 * @param val The array of objects to be written.
1447 * @param parcelableFlags Contextual flags as per
1448 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1450 * @see #readTypedArray
1451 * @see #writeParcelableArray
1452 * @see Parcelable.Creator
1454 public final <T extends Parcelable> void writeTypedArray(T[] val,
1455 int parcelableFlags) {
1459 for (int i = 0; i < N; i++) {
1463 item.writeToParcel(this, parcelableFlags);
1474 * Write a uniform (all items are null or the same class) array list of
1477 * @param list The list to write.
1481 public final <T extends Parcelable> void writeTypedArrayList(@Nullable ArrayList<T> list,
1482 int parcelableFlags) {
1484 int N = list.size();
1486 boolean wroteCreator = false;
1487 for (int i = 0; i < N; i++) {
1488 T item = list.get(i);
1491 if (!wroteCreator) {
1492 writeParcelableCreator(item);
1493 wroteCreator = true;
1495 item.writeToParcel(this, parcelableFlags);
1506 * Reads a uniform (all items are null or the same class) array list of
1509 * @return The list or null.
1513 public final @Nullable <T> ArrayList<T> readTypedArrayList(@Nullable ClassLoader loader) {
1518 Parcelable.Creator<?> creator = null;
1519 ArrayList<T> result = new ArrayList<T>(N);
1520 for (int i = 0; i < N; i++) {
1521 if (readInt() != 0) {
1522 if (creator == null) {
1523 creator = readParcelableCreator(loader);
1524 if (creator == null) {
1529 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
1530 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
1531 (Parcelable.ClassLoaderCreator<?>) creator;
1532 parcelable = (T) classLoaderCreator.createFromParcel(this, loader);
1534 parcelable = (T) creator.createFromParcel(this);
1536 result.add(parcelable);
1545 * Write a uniform (all items are null or the same class) array set of
1548 * @param set The set to write.
1552 public final <T extends Parcelable> void writeTypedArraySet(@Nullable ArraySet<T> set,
1553 int parcelableFlags) {
1557 boolean wroteCreator = false;
1558 for (int i = 0; i < N; i++) {
1559 T item = set.valueAt(i);
1562 if (!wroteCreator) {
1563 writeParcelableCreator(item);
1564 wroteCreator = true;
1566 item.writeToParcel(this, parcelableFlags);
1577 * Reads a uniform (all items are null or the same class) array set of
1580 * @return The set or null.
1584 public final @Nullable <T> ArraySet<T> readTypedArraySet(@Nullable ClassLoader loader) {
1589 Parcelable.Creator<?> creator = null;
1590 ArraySet<T> result = new ArraySet<T>(N);
1591 for (int i = 0; i < N; i++) {
1592 T parcelable = null;
1593 if (readInt() != 0) {
1594 if (creator == null) {
1595 creator = readParcelableCreator(loader);
1596 if (creator == null) {
1600 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
1601 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
1602 (Parcelable.ClassLoaderCreator<?>) creator;
1603 parcelable = (T) classLoaderCreator.createFromParcel(this, loader);
1605 parcelable = (T) creator.createFromParcel(this);
1608 result.append(parcelable);
1614 * Flatten the Parcelable object into the parcel.
1616 * @param val The Parcelable object to be written.
1617 * @param parcelableFlags Contextual flags as per
1618 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1620 * @see #readTypedObject
1622 public final <T extends Parcelable> void writeTypedObject(T val, int parcelableFlags) {
1625 val.writeToParcel(this, parcelableFlags);
1632 * Flatten a generic object in to a parcel. The given Object value may
1633 * currently be one of the following types:
1650 * <li> Object[] (supporting objects of the same type defined here).
1651 * <li> {@link Bundle}
1652 * <li> Map (as supported by {@link #writeMap}).
1653 * <li> Any object that implements the {@link Parcelable} protocol.
1655 * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
1656 * <li> List (as supported by {@link #writeList}).
1657 * <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}).
1658 * <li> {@link IBinder}
1659 * <li> Any object that implements Serializable (but see
1660 * {@link #writeSerializable} for caveats). Note that all of the
1661 * previous types have relatively efficient implementations for
1662 * writing to a Parcel; having to rely on the generic serialization
1663 * approach is much less efficient and should be avoided whenever
1667 * <p class="caution">{@link Parcelable} objects are written with
1668 * {@link Parcelable#writeToParcel} using contextual flags of 0. When
1669 * serializing objects containing {@link ParcelFileDescriptor}s,
1670 * this may result in file descriptor leaks when they are returned from
1671 * Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE}
1672 * should be used).</p>
1674 public final void writeValue(Object v) {
1677 } else if (v instanceof String) {
1678 writeInt(VAL_STRING);
1679 writeString((String) v);
1680 } else if (v instanceof Integer) {
1681 writeInt(VAL_INTEGER);
1682 writeInt((Integer) v);
1683 } else if (v instanceof Map) {
1686 } else if (v instanceof Bundle) {
1687 // Must be before Parcelable
1688 writeInt(VAL_BUNDLE);
1689 writeBundle((Bundle) v);
1690 } else if (v instanceof PersistableBundle) {
1691 writeInt(VAL_PERSISTABLEBUNDLE);
1692 writePersistableBundle((PersistableBundle) v);
1693 } else if (v instanceof Parcelable) {
1694 // IMPOTANT: cases for classes that implement Parcelable must
1695 // come before the Parcelable case, so that their specific VAL_*
1696 // types will be written.
1697 writeInt(VAL_PARCELABLE);
1698 writeParcelable((Parcelable) v, 0);
1699 } else if (v instanceof Short) {
1700 writeInt(VAL_SHORT);
1701 writeInt(((Short) v).intValue());
1702 } else if (v instanceof Long) {
1704 writeLong((Long) v);
1705 } else if (v instanceof Float) {
1706 writeInt(VAL_FLOAT);
1707 writeFloat((Float) v);
1708 } else if (v instanceof Double) {
1709 writeInt(VAL_DOUBLE);
1710 writeDouble((Double) v);
1711 } else if (v instanceof Boolean) {
1712 writeInt(VAL_BOOLEAN);
1713 writeInt((Boolean) v ? 1 : 0);
1714 } else if (v instanceof CharSequence) {
1715 // Must be after String
1716 writeInt(VAL_CHARSEQUENCE);
1717 writeCharSequence((CharSequence) v);
1718 } else if (v instanceof List) {
1720 writeList((List) v);
1721 } else if (v instanceof SparseArray) {
1722 writeInt(VAL_SPARSEARRAY);
1723 writeSparseArray((SparseArray) v);
1724 } else if (v instanceof boolean[]) {
1725 writeInt(VAL_BOOLEANARRAY);
1726 writeBooleanArray((boolean[]) v);
1727 } else if (v instanceof byte[]) {
1728 writeInt(VAL_BYTEARRAY);
1729 writeByteArray((byte[]) v);
1730 } else if (v instanceof String[]) {
1731 writeInt(VAL_STRINGARRAY);
1732 writeStringArray((String[]) v);
1733 } else if (v instanceof CharSequence[]) {
1734 // Must be after String[] and before Object[]
1735 writeInt(VAL_CHARSEQUENCEARRAY);
1736 writeCharSequenceArray((CharSequence[]) v);
1737 } else if (v instanceof IBinder) {
1738 writeInt(VAL_IBINDER);
1739 writeStrongBinder((IBinder) v);
1740 } else if (v instanceof Parcelable[]) {
1741 writeInt(VAL_PARCELABLEARRAY);
1742 writeParcelableArray((Parcelable[]) v, 0);
1743 } else if (v instanceof int[]) {
1744 writeInt(VAL_INTARRAY);
1745 writeIntArray((int[]) v);
1746 } else if (v instanceof long[]) {
1747 writeInt(VAL_LONGARRAY);
1748 writeLongArray((long[]) v);
1749 } else if (v instanceof Byte) {
1752 } else if (v instanceof Size) {
1754 writeSize((Size) v);
1755 } else if (v instanceof SizeF) {
1756 writeInt(VAL_SIZEF);
1757 writeSizeF((SizeF) v);
1758 } else if (v instanceof double[]) {
1759 writeInt(VAL_DOUBLEARRAY);
1760 writeDoubleArray((double[]) v);
1762 Class<?> clazz = v.getClass();
1763 if (clazz.isArray() && clazz.getComponentType() == Object.class) {
1764 // Only pure Object[] are written here, Other arrays of non-primitive types are
1765 // handled by serialization as this does not record the component type.
1766 writeInt(VAL_OBJECTARRAY);
1767 writeArray((Object[]) v);
1768 } else if (v instanceof Serializable) {
1770 writeInt(VAL_SERIALIZABLE);
1771 writeSerializable((Serializable) v);
1773 throw new RuntimeException("Parcel: unable to marshal value " + v);
1779 * Flatten the name of the class of the Parcelable and its contents
1782 * @param p The Parcelable object to be written.
1783 * @param parcelableFlags Contextual flags as per
1784 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1786 public final void writeParcelable(Parcelable p, int parcelableFlags) {
1791 writeParcelableCreator(p);
1792 p.writeToParcel(this, parcelableFlags);
1796 public final void writeParcelableCreator(Parcelable p) {
1797 String name = p.getClass().getName();
1802 * Write a generic serializable object in to a Parcel. It is strongly
1803 * recommended that this method be avoided, since the serialization
1804 * overhead is extremely large, and this approach will be much slower than
1805 * using the other approaches to writing data in to a Parcel.
1807 public final void writeSerializable(Serializable s) {
1812 String name = s.getClass().getName();
1815 ByteArrayOutputStream baos = new ByteArrayOutputStream();
1817 ObjectOutputStream oos = new ObjectOutputStream(baos);
1821 writeByteArray(baos.toByteArray());
1822 } catch (IOException ioe) {
1823 throw new RuntimeException("Parcelable encountered " +
1824 "IOException writing serializable object (name = " + name +
1830 * Special function for writing an exception result at the header of
1831 * a parcel, to be used when returning an exception from a transaction.
1832 * Note that this currently only supports a few exception types; any other
1833 * exception will be re-thrown by this function as a RuntimeException
1834 * (to be caught by the system's last-resort exception handling when
1835 * dispatching a transaction).
1837 * <p>The supported exception types are:
1839 * <li>{@link BadParcelableException}
1840 * <li>{@link IllegalArgumentException}
1841 * <li>{@link IllegalStateException}
1842 * <li>{@link NullPointerException}
1843 * <li>{@link SecurityException}
1844 * <li>{@link UnsupportedOperationException}
1845 * <li>{@link NetworkOnMainThreadException}
1848 * @param e The Exception to be written.
1850 * @see #writeNoException
1851 * @see #readException
1853 public final void writeException(Exception e) {
1855 if (e instanceof Parcelable
1856 && (e.getClass().getClassLoader() == Parcelable.class.getClassLoader())) {
1857 // We only send Parcelable exceptions that are in the
1858 // BootClassLoader to ensure that the receiver can unpack them
1859 code = EX_PARCELABLE;
1860 } else if (e instanceof SecurityException) {
1862 } else if (e instanceof BadParcelableException) {
1863 code = EX_BAD_PARCELABLE;
1864 } else if (e instanceof IllegalArgumentException) {
1865 code = EX_ILLEGAL_ARGUMENT;
1866 } else if (e instanceof NullPointerException) {
1867 code = EX_NULL_POINTER;
1868 } else if (e instanceof IllegalStateException) {
1869 code = EX_ILLEGAL_STATE;
1870 } else if (e instanceof NetworkOnMainThreadException) {
1871 code = EX_NETWORK_MAIN_THREAD;
1872 } else if (e instanceof UnsupportedOperationException) {
1873 code = EX_UNSUPPORTED_OPERATION;
1874 } else if (e instanceof ServiceSpecificException) {
1875 code = EX_SERVICE_SPECIFIC;
1878 StrictMode.clearGatheredViolations();
1880 if (e instanceof RuntimeException) {
1881 throw (RuntimeException) e;
1883 throw new RuntimeException(e);
1885 writeString(e.getMessage());
1887 case EX_SERVICE_SPECIFIC:
1888 writeInt(((ServiceSpecificException) e).errorCode);
1891 // Write parceled exception prefixed by length
1892 final int sizePosition = dataPosition();
1894 writeParcelable((Parcelable) e, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1895 final int payloadPosition = dataPosition();
1896 setDataPosition(sizePosition);
1897 writeInt(payloadPosition - sizePosition);
1898 setDataPosition(payloadPosition);
1904 * Special function for writing information at the front of the Parcel
1905 * indicating that no exception occurred.
1907 * @see #writeException
1908 * @see #readException
1910 public final void writeNoException() {
1911 // Despite the name of this function ("write no exception"),
1912 // it should instead be thought of as "write the RPC response
1913 // header", but because this function name is written out by
1914 // the AIDL compiler, we're not going to rename it.
1916 // The response header, in the non-exception case (see also
1917 // writeException above, also called by the AIDL compiler), is
1918 // either a 0 (the default case), or EX_HAS_REPLY_HEADER if
1919 // StrictMode has gathered up violations that have occurred
1920 // during a Binder call, in which case we write out the number
1921 // of violations and their details, serialized, before the
1922 // actual RPC respons data. The receiving end of this is
1923 // readException(), below.
1924 if (StrictMode.hasGatheredViolations()) {
1925 writeInt(EX_HAS_REPLY_HEADER);
1926 final int sizePosition = dataPosition();
1927 writeInt(0); // total size of fat header, to be filled in later
1928 StrictMode.writeGatheredViolationsToParcel(this);
1929 final int payloadPosition = dataPosition();
1930 setDataPosition(sizePosition);
1931 writeInt(payloadPosition - sizePosition); // header size
1932 setDataPosition(payloadPosition);
1939 * Special function for reading an exception result from the header of
1940 * a parcel, to be used after receiving the result of a transaction. This
1941 * will throw the exception for you if it had been written to the Parcel,
1942 * otherwise return and let you read the normal result data from the Parcel.
1944 * @see #writeException
1945 * @see #writeNoException
1947 public final void readException() {
1948 int code = readExceptionCode();
1950 String msg = readString();
1951 readException(code, msg);
1956 * Parses the header of a Binder call's response Parcel and
1957 * returns the exception code. Deals with lite or fat headers.
1958 * In the common successful case, this header is generally zero.
1959 * In less common cases, it's a small negative number and will be
1960 * followed by an error string.
1962 * This exists purely for android.database.DatabaseUtils and
1963 * insulating it from having to handle fat headers as returned by
1964 * e.g. StrictMode-induced RPC responses.
1968 public final int readExceptionCode() {
1969 int code = readInt();
1970 if (code == EX_HAS_REPLY_HEADER) {
1971 int headerSize = readInt();
1972 if (headerSize == 0) {
1973 Log.e(TAG, "Unexpected zero-sized Parcel reply header.");
1975 // Currently the only thing in the header is StrictMode stacks,
1976 // but discussions around event/RPC tracing suggest we might
1977 // put that here too. If so, switch on sub-header tags here.
1978 // But for now, just parse out the StrictMode stuff.
1979 StrictMode.readAndHandleBinderCallViolations(this);
1981 // And fat response headers are currently only used when
1982 // there are no exceptions, so return no error:
1989 * Throw an exception with the given message. Not intended for use
1990 * outside the Parcel class.
1992 * @param code Used to determine which exception class to throw.
1993 * @param msg The exception message.
1995 public final void readException(int code, String msg) {
1998 if (readInt() > 0) {
1999 SneakyThrow.sneakyThrow(
2000 (Exception) readParcelable(Parcelable.class.getClassLoader()));
2002 throw new RuntimeException(msg + " [missing Parcelable]");
2005 throw new SecurityException(msg);
2006 case EX_BAD_PARCELABLE:
2007 throw new BadParcelableException(msg);
2008 case EX_ILLEGAL_ARGUMENT:
2009 throw new IllegalArgumentException(msg);
2010 case EX_NULL_POINTER:
2011 throw new NullPointerException(msg);
2012 case EX_ILLEGAL_STATE:
2013 throw new IllegalStateException(msg);
2014 case EX_NETWORK_MAIN_THREAD:
2015 throw new NetworkOnMainThreadException();
2016 case EX_UNSUPPORTED_OPERATION:
2017 throw new UnsupportedOperationException(msg);
2018 case EX_SERVICE_SPECIFIC:
2019 throw new ServiceSpecificException(readInt(), msg);
2021 throw new RuntimeException("Unknown exception code: " + code
2026 * Read an integer value from the parcel at the current dataPosition().
2028 public final int readInt() {
2029 return nativeReadInt(mNativePtr);
2033 * Read a long integer value from the parcel at the current dataPosition().
2035 public final long readLong() {
2036 return nativeReadLong(mNativePtr);
2040 * Read a floating point value from the parcel at the current
2043 public final float readFloat() {
2044 return nativeReadFloat(mNativePtr);
2048 * Read a double precision floating point value from the parcel at the
2049 * current dataPosition().
2051 public final double readDouble() {
2052 return nativeReadDouble(mNativePtr);
2056 * Read a string value from the parcel at the current dataPosition().
2058 public final String readString() {
2059 return mReadWriteHelper.readString(this);
2063 * Read a string without going though a {@link ReadWriteHelper}. Subclasses of
2064 * {@link ReadWriteHelper} must use this method instead of {@link #readString} to avoid
2065 * infinity recursive calls.
2069 public String readStringNoHelper() {
2070 return nativeReadString(mNativePtr);
2074 public final boolean readBoolean() {
2075 return readInt() != 0;
2079 * Read a CharSequence value from the parcel at the current dataPosition().
2082 public final CharSequence readCharSequence() {
2083 return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
2087 * Read an object from the parcel at the current dataPosition().
2089 public final IBinder readStrongBinder() {
2090 return nativeReadStrongBinder(mNativePtr);
2094 * Read a FileDescriptor from the parcel at the current dataPosition().
2096 public final ParcelFileDescriptor readFileDescriptor() {
2097 FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
2098 return fd != null ? new ParcelFileDescriptor(fd) : null;
2102 public final FileDescriptor readRawFileDescriptor() {
2103 return nativeReadFileDescriptor(mNativePtr);
2108 * Read and return a new array of FileDescriptors from the parcel.
2109 * @return the FileDescriptor array, or null if the array is null.
2111 public final FileDescriptor[] createRawFileDescriptorArray() {
2116 FileDescriptor[] f = new FileDescriptor[N];
2117 for (int i = 0; i < N; i++) {
2118 f[i] = readRawFileDescriptor();
2125 * Read an array of FileDescriptors from a parcel.
2126 * The passed array must be exactly the length of the array in the parcel.
2127 * @return the FileDescriptor array, or null if the array is null.
2129 public final void readRawFileDescriptorArray(FileDescriptor[] val) {
2131 if (N == val.length) {
2132 for (int i=0; i<N; i++) {
2133 val[i] = readRawFileDescriptor();
2136 throw new RuntimeException("bad array lengths");
2140 /** @deprecated use {@link android.system.Os#open(String, int, int)} */
2142 static native FileDescriptor openFileDescriptor(String file, int mode)
2143 throws FileNotFoundException;
2145 /** @deprecated use {@link android.system.Os#dup(FileDescriptor)} */
2147 static native FileDescriptor dupFileDescriptor(FileDescriptor orig) throws IOException;
2149 /** @deprecated use {@link android.system.Os#close(FileDescriptor)} */
2151 static native void closeFileDescriptor(FileDescriptor desc) throws IOException;
2153 static native void clearFileDescriptor(FileDescriptor desc);
2156 * Read a byte value from the parcel at the current dataPosition().
2158 public final byte readByte() {
2159 return (byte)(readInt() & 0xff);
2163 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2164 * been written with {@link #writeBundle}. Read into an existing Map object
2165 * from the parcel at the current dataPosition().
2167 public final void readMap(Map outVal, ClassLoader loader) {
2169 readMapInternal(outVal, N, loader);
2173 * Read into an existing List object from the parcel at the current
2174 * dataPosition(), using the given class loader to load any enclosed
2175 * Parcelables. If it is null, the default class loader is used.
2177 public final void readList(List outVal, ClassLoader loader) {
2179 readListInternal(outVal, N, loader);
2183 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2184 * been written with {@link #writeBundle}. Read and return a new HashMap
2185 * object from the parcel at the current dataPosition(), using the given
2186 * class loader to load any enclosed Parcelables. Returns null if
2187 * the previously written map object was null.
2189 public final HashMap readHashMap(ClassLoader loader)
2195 HashMap m = new HashMap(N);
2196 readMapInternal(m, N, loader);
2201 * Read and return a new Bundle object from the parcel at the current
2202 * dataPosition(). Returns null if the previously written Bundle object was
2205 public final Bundle readBundle() {
2206 return readBundle(null);
2210 * Read and return a new Bundle object from the parcel at the current
2211 * dataPosition(), using the given class loader to initialize the class
2212 * loader of the Bundle for later retrieval of Parcelable objects.
2213 * Returns null if the previously written Bundle object was null.
2215 public final Bundle readBundle(ClassLoader loader) {
2216 int length = readInt();
2218 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2222 final Bundle bundle = new Bundle(this, length);
2223 if (loader != null) {
2224 bundle.setClassLoader(loader);
2230 * Read and return a new Bundle object from the parcel at the current
2231 * dataPosition(). Returns null if the previously written Bundle object was
2234 public final PersistableBundle readPersistableBundle() {
2235 return readPersistableBundle(null);
2239 * Read and return a new Bundle object from the parcel at the current
2240 * dataPosition(), using the given class loader to initialize the class
2241 * loader of the Bundle for later retrieval of Parcelable objects.
2242 * Returns null if the previously written Bundle object was null.
2244 public final PersistableBundle readPersistableBundle(ClassLoader loader) {
2245 int length = readInt();
2247 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2251 final PersistableBundle bundle = new PersistableBundle(this, length);
2252 if (loader != null) {
2253 bundle.setClassLoader(loader);
2259 * Read a Size from the parcel at the current dataPosition().
2261 public final Size readSize() {
2262 final int width = readInt();
2263 final int height = readInt();
2264 return new Size(width, height);
2268 * Read a SizeF from the parcel at the current dataPosition().
2270 public final SizeF readSizeF() {
2271 final float width = readFloat();
2272 final float height = readFloat();
2273 return new SizeF(width, height);
2277 * Read and return a byte[] object from the parcel.
2279 public final byte[] createByteArray() {
2280 return nativeCreateByteArray(mNativePtr);
2284 * Read a byte[] object from the parcel and copy it into the
2287 public final void readByteArray(byte[] val) {
2288 boolean valid = nativeReadByteArray(mNativePtr, val, (val != null) ? val.length : 0);
2290 throw new RuntimeException("bad array lengths");
2295 * Read a blob of data from the parcel and return it as a byte array.
2299 public final byte[] readBlob() {
2300 return nativeReadBlob(mNativePtr);
2304 * Read and return a String[] object from the parcel.
2307 public final String[] readStringArray() {
2308 String[] array = null;
2310 int length = readInt();
2313 array = new String[length];
2315 for (int i = 0 ; i < length ; i++)
2317 array[i] = readString();
2325 * Read and return a CharSequence[] object from the parcel.
2328 public final CharSequence[] readCharSequenceArray() {
2329 CharSequence[] array = null;
2331 int length = readInt();
2334 array = new CharSequence[length];
2336 for (int i = 0 ; i < length ; i++)
2338 array[i] = readCharSequence();
2346 * Read and return an ArrayList<CharSequence> object from the parcel.
2349 public final ArrayList<CharSequence> readCharSequenceList() {
2350 ArrayList<CharSequence> array = null;
2352 int length = readInt();
2354 array = new ArrayList<CharSequence>(length);
2356 for (int i = 0 ; i < length ; i++) {
2357 array.add(readCharSequence());
2365 * Read and return a new ArrayList object from the parcel at the current
2366 * dataPosition(). Returns null if the previously written list object was
2367 * null. The given class loader will be used to load any enclosed
2370 public final ArrayList readArrayList(ClassLoader loader) {
2375 ArrayList l = new ArrayList(N);
2376 readListInternal(l, N, loader);
2381 * Read and return a new Object array from the parcel at the current
2382 * dataPosition(). Returns null if the previously written array was
2383 * null. The given class loader will be used to load any enclosed
2386 public final Object[] readArray(ClassLoader loader) {
2391 Object[] l = new Object[N];
2392 readArrayInternal(l, N, loader);
2397 * Read and return a new SparseArray object from the parcel at the current
2398 * dataPosition(). Returns null if the previously written list object was
2399 * null. The given class loader will be used to load any enclosed
2402 public final SparseArray readSparseArray(ClassLoader loader) {
2407 SparseArray sa = new SparseArray(N);
2408 readSparseArrayInternal(sa, N, loader);
2413 * Read and return a new SparseBooleanArray object from the parcel at the current
2414 * dataPosition(). Returns null if the previously written list object was
2417 public final SparseBooleanArray readSparseBooleanArray() {
2422 SparseBooleanArray sa = new SparseBooleanArray(N);
2423 readSparseBooleanArrayInternal(sa, N);
2428 * Read and return a new SparseIntArray object from the parcel at the current
2429 * dataPosition(). Returns null if the previously written array object was null.
2432 public final SparseIntArray readSparseIntArray() {
2437 SparseIntArray sa = new SparseIntArray(N);
2438 readSparseIntArrayInternal(sa, N);
2443 * Read and return a new ArrayList containing a particular object type from
2444 * the parcel that was written with {@link #writeTypedList} at the
2445 * current dataPosition(). Returns null if the
2446 * previously written list object was null. The list <em>must</em> have
2447 * previously been written via {@link #writeTypedList} with the same object
2450 * @return A newly created ArrayList containing objects with the same data
2451 * as those that were previously written.
2453 * @see #writeTypedList
2455 public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
2460 ArrayList<T> l = new ArrayList<T>(N);
2462 if (readInt() != 0) {
2463 l.add(c.createFromParcel(this));
2473 * Read into the given List items containing a particular object type
2474 * that were written with {@link #writeTypedList} at the
2475 * current dataPosition(). The list <em>must</em> have
2476 * previously been written via {@link #writeTypedList} with the same object
2479 * @return A newly created ArrayList containing objects with the same data
2480 * as those that were previously written.
2482 * @see #writeTypedList
2484 public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
2485 int M = list.size();
2488 for (; i < M && i < N; i++) {
2489 if (readInt() != 0) {
2490 list.set(i, c.createFromParcel(this));
2496 if (readInt() != 0) {
2497 list.add(c.createFromParcel(this));
2508 * Read and return a new ArrayList containing String objects from
2509 * the parcel that was written with {@link #writeStringList} at the
2510 * current dataPosition(). Returns null if the
2511 * previously written list object was null.
2513 * @return A newly created ArrayList containing strings with the same data
2514 * as those that were previously written.
2516 * @see #writeStringList
2518 public final ArrayList<String> createStringArrayList() {
2523 ArrayList<String> l = new ArrayList<String>(N);
2525 l.add(readString());
2532 * Read and return a new ArrayList containing IBinder objects from
2533 * the parcel that was written with {@link #writeBinderList} at the
2534 * current dataPosition(). Returns null if the
2535 * previously written list object was null.
2537 * @return A newly created ArrayList containing strings with the same data
2538 * as those that were previously written.
2540 * @see #writeBinderList
2542 public final ArrayList<IBinder> createBinderArrayList() {
2547 ArrayList<IBinder> l = new ArrayList<IBinder>(N);
2549 l.add(readStrongBinder());
2556 * Read into the given List items String objects that were written with
2557 * {@link #writeStringList} at the current dataPosition().
2559 * @return A newly created ArrayList containing strings with the same data
2560 * as those that were previously written.
2562 * @see #writeStringList
2564 public final void readStringList(List<String> list) {
2565 int M = list.size();
2568 for (; i < M && i < N; i++) {
2569 list.set(i, readString());
2572 list.add(readString());
2580 * Read into the given List items IBinder objects that were written with
2581 * {@link #writeBinderList} at the current dataPosition().
2583 * @see #writeBinderList
2585 public final void readBinderList(List<IBinder> list) {
2586 int M = list.size();
2589 for (; i < M && i < N; i++) {
2590 list.set(i, readStrongBinder());
2593 list.add(readStrongBinder());
2601 * Read the list of {@code Parcelable} objects at the current data position into the
2602 * given {@code list}. The contents of the {@code list} are replaced. If the serialized
2603 * list was {@code null}, {@code list} is cleared.
2605 * @see #writeParcelableList(List, int)
2608 public final <T extends Parcelable> List<T> readParcelableList(List<T> list, ClassLoader cl) {
2609 final int N = readInt();
2615 final int M = list.size();
2617 for (; i < M && i < N; i++) {
2618 list.set(i, (T) readParcelable(cl));
2621 list.add((T) readParcelable(cl));
2630 * Read and return a new array containing a particular object type from
2631 * the parcel at the current dataPosition(). Returns null if the
2632 * previously written array was null. The array <em>must</em> have
2633 * previously been written via {@link #writeTypedArray} with the same
2636 * @return A newly created array containing objects with the same data
2637 * as those that were previously written.
2639 * @see #writeTypedArray
2641 public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
2646 T[] l = c.newArray(N);
2647 for (int i=0; i<N; i++) {
2648 if (readInt() != 0) {
2649 l[i] = c.createFromParcel(this);
2655 public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
2657 if (N == val.length) {
2658 for (int i=0; i<N; i++) {
2659 if (readInt() != 0) {
2660 val[i] = c.createFromParcel(this);
2666 throw new RuntimeException("bad array lengths");
2675 public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
2676 return createTypedArray(c);
2680 * Read and return a typed Parcelable object from a parcel.
2681 * Returns null if the previous written object was null.
2682 * The object <em>must</em> have previous been written via
2683 * {@link #writeTypedObject} with the same object type.
2685 * @return A newly created object of the type that was previously
2688 * @see #writeTypedObject
2690 public final <T> T readTypedObject(Parcelable.Creator<T> c) {
2691 if (readInt() != 0) {
2692 return c.createFromParcel(this);
2699 * Write a heterogeneous array of Parcelable objects into the Parcel.
2700 * Each object in the array is written along with its class name, so
2701 * that the correct class can later be instantiated. As a result, this
2702 * has significantly more overhead than {@link #writeTypedArray}, but will
2703 * correctly handle an array containing more than one type of object.
2705 * @param value The array of objects to be written.
2706 * @param parcelableFlags Contextual flags as per
2707 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2709 * @see #writeTypedArray
2711 public final <T extends Parcelable> void writeParcelableArray(T[] value,
2712 int parcelableFlags) {
2713 if (value != null) {
2714 int N = value.length;
2716 for (int i=0; i<N; i++) {
2717 writeParcelable(value[i], parcelableFlags);
2725 * Read a typed object from a parcel. The given class loader will be
2726 * used to load any enclosed Parcelables. If it is null, the default class
2727 * loader will be used.
2729 public final Object readValue(ClassLoader loader) {
2730 int type = readInt();
2737 return readString();
2743 return readHashMap(loader);
2745 case VAL_PARCELABLE:
2746 return readParcelable(loader);
2749 return (short) readInt();
2758 return readDouble();
2761 return readInt() == 1;
2763 case VAL_CHARSEQUENCE:
2764 return readCharSequence();
2767 return readArrayList(loader);
2769 case VAL_BOOLEANARRAY:
2770 return createBooleanArray();
2773 return createByteArray();
2775 case VAL_STRINGARRAY:
2776 return readStringArray();
2778 case VAL_CHARSEQUENCEARRAY:
2779 return readCharSequenceArray();
2782 return readStrongBinder();
2784 case VAL_OBJECTARRAY:
2785 return readArray(loader);
2788 return createIntArray();
2791 return createLongArray();
2796 case VAL_SERIALIZABLE:
2797 return readSerializable(loader);
2799 case VAL_PARCELABLEARRAY:
2800 return readParcelableArray(loader);
2802 case VAL_SPARSEARRAY:
2803 return readSparseArray(loader);
2805 case VAL_SPARSEBOOLEANARRAY:
2806 return readSparseBooleanArray();
2809 return readBundle(loader); // loading will be deferred
2811 case VAL_PERSISTABLEBUNDLE:
2812 return readPersistableBundle(loader);
2820 case VAL_DOUBLEARRAY:
2821 return createDoubleArray();
2824 int off = dataPosition() - 4;
2825 throw new RuntimeException(
2826 "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
2831 * Read and return a new Parcelable from the parcel. The given class loader
2832 * will be used to load any enclosed Parcelables. If it is null, the default
2833 * class loader will be used.
2834 * @param loader A ClassLoader from which to instantiate the Parcelable
2835 * object, or null for the default class loader.
2836 * @return Returns the newly created Parcelable, or null if a null
2837 * object has been written.
2838 * @throws BadParcelableException Throws BadParcelableException if there
2839 * was an error trying to instantiate the Parcelable.
2841 @SuppressWarnings("unchecked")
2842 public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
2843 Parcelable.Creator<?> creator = readParcelableCreator(loader);
2844 if (creator == null) {
2847 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2848 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2849 (Parcelable.ClassLoaderCreator<?>) creator;
2850 return (T) classLoaderCreator.createFromParcel(this, loader);
2852 return (T) creator.createFromParcel(this);
2856 @SuppressWarnings("unchecked")
2857 public final <T extends Parcelable> T readCreator(Parcelable.Creator<?> creator,
2858 ClassLoader loader) {
2859 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2860 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2861 (Parcelable.ClassLoaderCreator<?>) creator;
2862 return (T) classLoaderCreator.createFromParcel(this, loader);
2864 return (T) creator.createFromParcel(this);
2868 public final Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) {
2869 String name = readString();
2873 Parcelable.Creator<?> creator;
2874 synchronized (mCreators) {
2875 HashMap<String,Parcelable.Creator<?>> map = mCreators.get(loader);
2877 map = new HashMap<>();
2878 mCreators.put(loader, map);
2880 creator = map.get(name);
2881 if (creator == null) {
2883 // If loader == null, explicitly emulate Class.forName(String) "caller
2884 // classloader" behavior.
2885 ClassLoader parcelableClassLoader =
2886 (loader == null ? getClass().getClassLoader() : loader);
2887 // Avoid initializing the Parcelable class until we know it implements
2888 // Parcelable and has the necessary CREATOR field. http://b/1171613.
2889 Class<?> parcelableClass = Class.forName(name, false /* initialize */,
2890 parcelableClassLoader);
2891 if (!Parcelable.class.isAssignableFrom(parcelableClass)) {
2892 throw new BadParcelableException("Parcelable protocol requires that the "
2893 + "class implements Parcelable");
2895 Field f = parcelableClass.getField("CREATOR");
2896 if ((f.getModifiers() & Modifier.STATIC) == 0) {
2897 throw new BadParcelableException("Parcelable protocol requires "
2898 + "the CREATOR object to be static on class " + name);
2900 Class<?> creatorType = f.getType();
2901 if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) {
2902 // Fail before calling Field.get(), not after, to avoid initializing
2903 // parcelableClass unnecessarily.
2904 throw new BadParcelableException("Parcelable protocol requires a "
2905 + "Parcelable.Creator object called "
2906 + "CREATOR on class " + name);
2908 creator = (Parcelable.Creator<?>) f.get(null);
2910 catch (IllegalAccessException e) {
2911 Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
2912 throw new BadParcelableException(
2913 "IllegalAccessException when unmarshalling: " + name);
2915 catch (ClassNotFoundException e) {
2916 Log.e(TAG, "Class not found when unmarshalling: " + name, e);
2917 throw new BadParcelableException(
2918 "ClassNotFoundException when unmarshalling: " + name);
2920 catch (NoSuchFieldException e) {
2921 throw new BadParcelableException("Parcelable protocol requires a "
2922 + "Parcelable.Creator object called "
2923 + "CREATOR on class " + name);
2925 if (creator == null) {
2926 throw new BadParcelableException("Parcelable protocol requires a "
2927 + "non-null Parcelable.Creator object called "
2928 + "CREATOR on class " + name);
2931 map.put(name, creator);
2939 * Read and return a new Parcelable array from the parcel.
2940 * The given class loader will be used to load any enclosed
2942 * @return the Parcelable array, or null if the array is null
2944 public final Parcelable[] readParcelableArray(ClassLoader loader) {
2949 Parcelable[] p = new Parcelable[N];
2950 for (int i = 0; i < N; i++) {
2951 p[i] = readParcelable(loader);
2957 public final <T extends Parcelable> T[] readParcelableArray(ClassLoader loader,
2963 T[] p = (T[]) Array.newInstance(clazz, N);
2964 for (int i = 0; i < N; i++) {
2965 p[i] = readParcelable(loader);
2971 * Read and return a new Serializable object from the parcel.
2972 * @return the Serializable object, or null if the Serializable name
2973 * wasn't found in the parcel.
2975 public final Serializable readSerializable() {
2976 return readSerializable(null);
2979 private final Serializable readSerializable(final ClassLoader loader) {
2980 String name = readString();
2982 // For some reason we were unable to read the name of the Serializable (either there
2983 // is nothing left in the Parcel to read, or the next value wasn't a String), so
2984 // return null, which indicates that the name wasn't found in the parcel.
2988 byte[] serializedData = createByteArray();
2989 ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
2991 ObjectInputStream ois = new ObjectInputStream(bais) {
2993 protected Class<?> resolveClass(ObjectStreamClass osClass)
2994 throws IOException, ClassNotFoundException {
2995 // try the custom classloader if provided
2996 if (loader != null) {
2997 Class<?> c = Class.forName(osClass.getName(), false, loader);
3002 return super.resolveClass(osClass);
3005 return (Serializable) ois.readObject();
3006 } catch (IOException ioe) {
3007 throw new RuntimeException("Parcelable encountered " +
3008 "IOException reading a Serializable object (name = " + name +
3010 } catch (ClassNotFoundException cnfe) {
3011 throw new RuntimeException("Parcelable encountered " +
3012 "ClassNotFoundException reading a Serializable object (name = "
3013 + name + ")", cnfe);
3017 // Cache of previously looked up CREATOR.createFromParcel() methods for
3018 // particular classes. Keys are the names of the classes, values are
3020 private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator<?>>>
3021 mCreators = new HashMap<>();
3023 /** @hide for internal use only. */
3024 static protected final Parcel obtain(int obj) {
3025 throw new UnsupportedOperationException();
3029 static protected final Parcel obtain(long obj) {
3030 final Parcel[] pool = sHolderPool;
3031 synchronized (pool) {
3033 for (int i=0; i<POOL_SIZE; i++) {
3037 if (DEBUG_RECYCLE) {
3038 p.mStack = new RuntimeException();
3045 return new Parcel(obj);
3048 private Parcel(long nativePtr) {
3049 if (DEBUG_RECYCLE) {
3050 mStack = new RuntimeException();
3052 //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
3056 private void init(long nativePtr) {
3057 if (nativePtr != 0) {
3058 mNativePtr = nativePtr;
3059 mOwnsNativeParcelObject = false;
3061 mNativePtr = nativeCreate();
3062 mOwnsNativeParcelObject = true;
3066 private void freeBuffer() {
3067 if (mOwnsNativeParcelObject) {
3068 updateNativeSize(nativeFreeBuffer(mNativePtr));
3070 mReadWriteHelper = ReadWriteHelper.DEFAULT;
3073 private void destroy() {
3074 if (mNativePtr != 0) {
3075 if (mOwnsNativeParcelObject) {
3076 nativeDestroy(mNativePtr);
3077 updateNativeSize(0);
3081 mReadWriteHelper = null;
3085 protected void finalize() throws Throwable {
3086 if (DEBUG_RECYCLE) {
3087 if (mStack != null) {
3088 Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
3094 /* package */ void readMapInternal(Map outVal, int N,
3095 ClassLoader loader) {
3097 Object key = readValue(loader);
3098 Object value = readValue(loader);
3099 outVal.put(key, value);
3104 /* package */ void readArrayMapInternal(ArrayMap outVal, int N,
3105 ClassLoader loader) {
3106 if (DEBUG_ARRAY_MAP) {
3107 RuntimeException here = new RuntimeException("here");
3108 here.fillInStackTrace();
3109 Log.d(TAG, "Reading " + N + " ArrayMap entries", here);
3113 if (DEBUG_ARRAY_MAP) startPos = dataPosition();
3114 String key = readString();
3115 Object value = readValue(loader);
3116 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Read #" + (N-1) + " "
3117 + (dataPosition()-startPos) + " bytes: key=0x"
3118 + Integer.toHexString((key != null ? key.hashCode() : 0)) + " " + key);
3119 outVal.append(key, value);
3125 /* package */ void readArrayMapSafelyInternal(ArrayMap outVal, int N,
3126 ClassLoader loader) {
3127 if (DEBUG_ARRAY_MAP) {
3128 RuntimeException here = new RuntimeException("here");
3129 here.fillInStackTrace();
3130 Log.d(TAG, "Reading safely " + N + " ArrayMap entries", here);
3133 String key = readString();
3134 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Read safe #" + (N-1) + ": key=0x"
3135 + (key != null ? key.hashCode() : 0) + " " + key);
3136 Object value = readValue(loader);
3137 outVal.put(key, value);
3143 * @hide For testing only.
3145 public void readArrayMap(ArrayMap outVal, ClassLoader loader) {
3146 final int N = readInt();
3150 readArrayMapInternal(outVal, N, loader);
3154 * Reads an array set.
3156 * @param loader The class loader to use.
3160 public @Nullable ArraySet<? extends Object> readArraySet(ClassLoader loader) {
3161 final int size = readInt();
3165 ArraySet<Object> result = new ArraySet<>(size);
3166 for (int i = 0; i < size; i++) {
3167 Object value = readValue(loader);
3168 result.append(value);
3173 private void readListInternal(List outVal, int N,
3174 ClassLoader loader) {
3176 Object value = readValue(loader);
3177 //Log.d(TAG, "Unmarshalling value=" + value);
3183 private void readArrayInternal(Object[] outVal, int N,
3184 ClassLoader loader) {
3185 for (int i = 0; i < N; i++) {
3186 Object value = readValue(loader);
3187 //Log.d(TAG, "Unmarshalling value=" + value);
3192 private void readSparseArrayInternal(SparseArray outVal, int N,
3193 ClassLoader loader) {
3195 int key = readInt();
3196 Object value = readValue(loader);
3197 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3198 outVal.append(key, value);
3204 private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
3206 int key = readInt();
3207 boolean value = this.readByte() == 1;
3208 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3209 outVal.append(key, value);
3214 private void readSparseIntArrayInternal(SparseIntArray outVal, int N) {
3216 int key = readInt();
3217 int value = readInt();
3218 outVal.append(key, value);
3226 public long getBlobAshmemSize() {
3227 return nativeGetBlobAshmemSize(mNativePtr);