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 int size = entries.size();
812 for (Map.Entry<String,Object> e : entries) {
813 writeValue(e.getKey());
814 writeValue(e.getValue());
819 throw new BadParcelableException("Map size does not match number of entries!");
825 * Flatten an ArrayMap into the parcel at the current dataPosition(),
826 * growing dataCapacity() if needed. The Map keys must be String objects.
828 /* package */ void writeArrayMapInternal(ArrayMap<String, Object> val) {
833 // Keep the format of this Parcel in sync with writeToParcelInner() in
834 // frameworks/native/libs/binder/PersistableBundle.cpp.
835 final int N = val.size();
837 if (DEBUG_ARRAY_MAP) {
838 RuntimeException here = new RuntimeException("here");
839 here.fillInStackTrace();
840 Log.d(TAG, "Writing " + N + " ArrayMap entries", here);
843 for (int i=0; i<N; i++) {
844 if (DEBUG_ARRAY_MAP) startPos = dataPosition();
845 writeString(val.keyAt(i));
846 writeValue(val.valueAt(i));
847 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Write #" + i + " "
848 + (dataPosition()-startPos) + " bytes: key=0x"
849 + Integer.toHexString(val.keyAt(i) != null ? val.keyAt(i).hashCode() : 0)
850 + " " + val.keyAt(i));
855 * @hide For testing only.
857 public void writeArrayMap(ArrayMap<String, Object> val) {
858 writeArrayMapInternal(val);
862 * Write an array set to the parcel.
864 * @param val The array set to write.
868 public void writeArraySet(@Nullable ArraySet<? extends Object> val) {
869 final int size = (val != null) ? val.size() : -1;
871 for (int i = 0; i < size; i++) {
872 writeValue(val.valueAt(i));
877 * Flatten a Bundle into the parcel at the current dataPosition(),
878 * growing dataCapacity() if needed.
880 public final void writeBundle(Bundle val) {
886 val.writeToParcel(this, 0);
890 * Flatten a PersistableBundle into the parcel at the current dataPosition(),
891 * growing dataCapacity() if needed.
893 public final void writePersistableBundle(PersistableBundle val) {
899 val.writeToParcel(this, 0);
903 * Flatten a Size into the parcel at the current dataPosition(),
904 * growing dataCapacity() if needed.
906 public final void writeSize(Size val) {
907 writeInt(val.getWidth());
908 writeInt(val.getHeight());
912 * Flatten a SizeF into the parcel at the current dataPosition(),
913 * growing dataCapacity() if needed.
915 public final void writeSizeF(SizeF val) {
916 writeFloat(val.getWidth());
917 writeFloat(val.getHeight());
921 * Flatten a List into the parcel at the current dataPosition(), growing
922 * dataCapacity() if needed. The List values are written using
923 * {@link #writeValue} and must follow the specification there.
925 public final void writeList(List val) {
934 writeValue(val.get(i));
940 * Flatten an Object array into the parcel at the current dataPosition(),
941 * growing dataCapacity() if needed. The array values are written using
942 * {@link #writeValue} and must follow the specification there.
944 public final void writeArray(Object[] val) {
959 * Flatten a generic SparseArray into the parcel at the current
960 * dataPosition(), growing dataCapacity() if needed. The SparseArray
961 * values are written using {@link #writeValue} and must follow the
962 * specification there.
964 public final void writeSparseArray(SparseArray<Object> val) {
973 writeInt(val.keyAt(i));
974 writeValue(val.valueAt(i));
979 public final void writeSparseBooleanArray(SparseBooleanArray val) {
988 writeInt(val.keyAt(i));
989 writeByte((byte)(val.valueAt(i) ? 1 : 0));
997 public final void writeSparseIntArray(SparseIntArray val) {
1006 writeInt(val.keyAt(i));
1007 writeInt(val.valueAt(i));
1012 public final void writeBooleanArray(boolean[] val) {
1016 for (int i=0; i<N; i++) {
1017 writeInt(val[i] ? 1 : 0);
1024 public final boolean[] createBooleanArray() {
1026 // >>2 as a fast divide-by-4 works in the create*Array() functions
1027 // because dataAvail() will never return a negative number. 4 is
1028 // the size of a stored boolean in the stream.
1029 if (N >= 0 && N <= (dataAvail() >> 2)) {
1030 boolean[] val = new boolean[N];
1031 for (int i=0; i<N; i++) {
1032 val[i] = readInt() != 0;
1040 public final void readBooleanArray(boolean[] val) {
1042 if (N == val.length) {
1043 for (int i=0; i<N; i++) {
1044 val[i] = readInt() != 0;
1047 throw new RuntimeException("bad array lengths");
1051 public final void writeCharArray(char[] val) {
1055 for (int i=0; i<N; i++) {
1056 writeInt((int)val[i]);
1063 public final char[] createCharArray() {
1065 if (N >= 0 && N <= (dataAvail() >> 2)) {
1066 char[] val = new char[N];
1067 for (int i=0; i<N; i++) {
1068 val[i] = (char)readInt();
1076 public final void readCharArray(char[] val) {
1078 if (N == val.length) {
1079 for (int i=0; i<N; i++) {
1080 val[i] = (char)readInt();
1083 throw new RuntimeException("bad array lengths");
1087 public final void writeIntArray(int[] val) {
1091 for (int i=0; i<N; i++) {
1099 public final int[] createIntArray() {
1101 if (N >= 0 && N <= (dataAvail() >> 2)) {
1102 int[] val = new int[N];
1103 for (int i=0; i<N; i++) {
1112 public final void readIntArray(int[] val) {
1114 if (N == val.length) {
1115 for (int i=0; i<N; i++) {
1119 throw new RuntimeException("bad array lengths");
1123 public final void writeLongArray(long[] val) {
1127 for (int i=0; i<N; i++) {
1135 public final long[] createLongArray() {
1137 // >>3 because stored longs are 64 bits
1138 if (N >= 0 && N <= (dataAvail() >> 3)) {
1139 long[] val = new long[N];
1140 for (int i=0; i<N; i++) {
1141 val[i] = readLong();
1149 public final void readLongArray(long[] val) {
1151 if (N == val.length) {
1152 for (int i=0; i<N; i++) {
1153 val[i] = readLong();
1156 throw new RuntimeException("bad array lengths");
1160 public final void writeFloatArray(float[] val) {
1164 for (int i=0; i<N; i++) {
1172 public final float[] createFloatArray() {
1174 // >>2 because stored floats are 4 bytes
1175 if (N >= 0 && N <= (dataAvail() >> 2)) {
1176 float[] val = new float[N];
1177 for (int i=0; i<N; i++) {
1178 val[i] = readFloat();
1186 public final void readFloatArray(float[] val) {
1188 if (N == val.length) {
1189 for (int i=0; i<N; i++) {
1190 val[i] = readFloat();
1193 throw new RuntimeException("bad array lengths");
1197 public final void writeDoubleArray(double[] val) {
1201 for (int i=0; i<N; i++) {
1202 writeDouble(val[i]);
1209 public final double[] createDoubleArray() {
1211 // >>3 because stored doubles are 8 bytes
1212 if (N >= 0 && N <= (dataAvail() >> 3)) {
1213 double[] val = new double[N];
1214 for (int i=0; i<N; i++) {
1215 val[i] = readDouble();
1223 public final void readDoubleArray(double[] val) {
1225 if (N == val.length) {
1226 for (int i=0; i<N; i++) {
1227 val[i] = readDouble();
1230 throw new RuntimeException("bad array lengths");
1234 public final void writeStringArray(String[] val) {
1238 for (int i=0; i<N; i++) {
1239 writeString(val[i]);
1246 public final String[] createStringArray() {
1249 String[] val = new String[N];
1250 for (int i=0; i<N; i++) {
1251 val[i] = readString();
1259 public final void readStringArray(String[] val) {
1261 if (N == val.length) {
1262 for (int i=0; i<N; i++) {
1263 val[i] = readString();
1266 throw new RuntimeException("bad array lengths");
1270 public final void writeBinderArray(IBinder[] val) {
1274 for (int i=0; i<N; i++) {
1275 writeStrongBinder(val[i]);
1285 public final void writeCharSequenceArray(CharSequence[] val) {
1289 for (int i=0; i<N; i++) {
1290 writeCharSequence(val[i]);
1300 public final void writeCharSequenceList(ArrayList<CharSequence> val) {
1304 for (int i=0; i<N; i++) {
1305 writeCharSequence(val.get(i));
1312 public final IBinder[] createBinderArray() {
1315 IBinder[] val = new IBinder[N];
1316 for (int i=0; i<N; i++) {
1317 val[i] = readStrongBinder();
1325 public final void readBinderArray(IBinder[] val) {
1327 if (N == val.length) {
1328 for (int i=0; i<N; i++) {
1329 val[i] = readStrongBinder();
1332 throw new RuntimeException("bad array lengths");
1337 * Flatten a List containing a particular object type into the parcel, at
1338 * the current dataPosition() and growing dataCapacity() if needed. The
1339 * type of the objects in the list must be one that implements Parcelable.
1340 * Unlike the generic writeList() method, however, only the raw data of the
1341 * objects is written and not their type, so you must use the corresponding
1342 * readTypedList() to unmarshall them.
1344 * @param val The list of objects to be written.
1346 * @see #createTypedArrayList
1347 * @see #readTypedList
1350 public final <T extends Parcelable> void writeTypedList(List<T> val) {
1351 writeTypedList(val, 0);
1357 public <T extends Parcelable> void writeTypedList(List<T> val, int parcelableFlags) {
1366 writeTypedObject(val.get(i), parcelableFlags);
1372 * Flatten a List containing String objects into the parcel, at
1373 * the current dataPosition() and growing dataCapacity() if needed. They
1374 * can later be retrieved with {@link #createStringArrayList} or
1375 * {@link #readStringList}.
1377 * @param val The list of strings to be written.
1379 * @see #createStringArrayList
1380 * @see #readStringList
1382 public final void writeStringList(List<String> val) {
1391 writeString(val.get(i));
1397 * Flatten a List containing IBinder objects into the parcel, at
1398 * the current dataPosition() and growing dataCapacity() if needed. They
1399 * can later be retrieved with {@link #createBinderArrayList} or
1400 * {@link #readBinderList}.
1402 * @param val The list of strings to be written.
1404 * @see #createBinderArrayList
1405 * @see #readBinderList
1407 public final void writeBinderList(List<IBinder> val) {
1416 writeStrongBinder(val.get(i));
1422 * Flatten a {@code List} containing arbitrary {@code Parcelable} objects into this parcel
1423 * at the current position. They can later be retrieved using
1424 * {@link #readParcelableList(List, ClassLoader)} if required.
1426 * @see #readParcelableList(List, ClassLoader)
1429 public final <T extends Parcelable> void writeParcelableList(List<T> val, int flags) {
1439 writeParcelable(val.get(i), flags);
1445 * Flatten a homogeneous array containing a particular object type into
1447 * the current dataPosition() and growing dataCapacity() if needed. The
1448 * type of the objects in the array must be one that implements Parcelable.
1449 * Unlike the {@link #writeParcelableArray} method, however, only the
1450 * raw data of the objects is written and not their type, so you must use
1451 * {@link #readTypedArray} with the correct corresponding
1452 * {@link Parcelable.Creator} implementation to unmarshall them.
1454 * @param val The array of objects to be written.
1455 * @param parcelableFlags Contextual flags as per
1456 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1458 * @see #readTypedArray
1459 * @see #writeParcelableArray
1460 * @see Parcelable.Creator
1462 public final <T extends Parcelable> void writeTypedArray(T[] val,
1463 int parcelableFlags) {
1467 for (int i = 0; i < N; i++) {
1471 item.writeToParcel(this, parcelableFlags);
1482 * Write a uniform (all items are null or the same class) array list of
1485 * @param list The list to write.
1489 public final <T extends Parcelable> void writeTypedArrayList(@Nullable ArrayList<T> list,
1490 int parcelableFlags) {
1492 int N = list.size();
1494 boolean wroteCreator = false;
1495 for (int i = 0; i < N; i++) {
1496 T item = list.get(i);
1499 if (!wroteCreator) {
1500 writeParcelableCreator(item);
1501 wroteCreator = true;
1503 item.writeToParcel(this, parcelableFlags);
1514 * Reads a uniform (all items are null or the same class) array list of
1517 * @return The list or null.
1521 public final @Nullable <T> ArrayList<T> readTypedArrayList(@Nullable ClassLoader loader) {
1526 Parcelable.Creator<?> creator = null;
1527 ArrayList<T> result = new ArrayList<T>(N);
1528 for (int i = 0; i < N; i++) {
1529 if (readInt() != 0) {
1530 if (creator == null) {
1531 creator = readParcelableCreator(loader);
1532 if (creator == null) {
1537 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
1538 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
1539 (Parcelable.ClassLoaderCreator<?>) creator;
1540 parcelable = (T) classLoaderCreator.createFromParcel(this, loader);
1542 parcelable = (T) creator.createFromParcel(this);
1544 result.add(parcelable);
1553 * Write a uniform (all items are null or the same class) array set of
1556 * @param set The set to write.
1560 public final <T extends Parcelable> void writeTypedArraySet(@Nullable ArraySet<T> set,
1561 int parcelableFlags) {
1565 boolean wroteCreator = false;
1566 for (int i = 0; i < N; i++) {
1567 T item = set.valueAt(i);
1570 if (!wroteCreator) {
1571 writeParcelableCreator(item);
1572 wroteCreator = true;
1574 item.writeToParcel(this, parcelableFlags);
1585 * Reads a uniform (all items are null or the same class) array set of
1588 * @return The set or null.
1592 public final @Nullable <T> ArraySet<T> readTypedArraySet(@Nullable ClassLoader loader) {
1597 Parcelable.Creator<?> creator = null;
1598 ArraySet<T> result = new ArraySet<T>(N);
1599 for (int i = 0; i < N; i++) {
1600 T parcelable = null;
1601 if (readInt() != 0) {
1602 if (creator == null) {
1603 creator = readParcelableCreator(loader);
1604 if (creator == null) {
1608 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
1609 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
1610 (Parcelable.ClassLoaderCreator<?>) creator;
1611 parcelable = (T) classLoaderCreator.createFromParcel(this, loader);
1613 parcelable = (T) creator.createFromParcel(this);
1616 result.append(parcelable);
1622 * Flatten the Parcelable object into the parcel.
1624 * @param val The Parcelable object to be written.
1625 * @param parcelableFlags Contextual flags as per
1626 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1628 * @see #readTypedObject
1630 public final <T extends Parcelable> void writeTypedObject(T val, int parcelableFlags) {
1633 val.writeToParcel(this, parcelableFlags);
1640 * Flatten a generic object in to a parcel. The given Object value may
1641 * currently be one of the following types:
1658 * <li> Object[] (supporting objects of the same type defined here).
1659 * <li> {@link Bundle}
1660 * <li> Map (as supported by {@link #writeMap}).
1661 * <li> Any object that implements the {@link Parcelable} protocol.
1663 * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
1664 * <li> List (as supported by {@link #writeList}).
1665 * <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}).
1666 * <li> {@link IBinder}
1667 * <li> Any object that implements Serializable (but see
1668 * {@link #writeSerializable} for caveats). Note that all of the
1669 * previous types have relatively efficient implementations for
1670 * writing to a Parcel; having to rely on the generic serialization
1671 * approach is much less efficient and should be avoided whenever
1675 * <p class="caution">{@link Parcelable} objects are written with
1676 * {@link Parcelable#writeToParcel} using contextual flags of 0. When
1677 * serializing objects containing {@link ParcelFileDescriptor}s,
1678 * this may result in file descriptor leaks when they are returned from
1679 * Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE}
1680 * should be used).</p>
1682 public final void writeValue(Object v) {
1685 } else if (v instanceof String) {
1686 writeInt(VAL_STRING);
1687 writeString((String) v);
1688 } else if (v instanceof Integer) {
1689 writeInt(VAL_INTEGER);
1690 writeInt((Integer) v);
1691 } else if (v instanceof Map) {
1694 } else if (v instanceof Bundle) {
1695 // Must be before Parcelable
1696 writeInt(VAL_BUNDLE);
1697 writeBundle((Bundle) v);
1698 } else if (v instanceof PersistableBundle) {
1699 writeInt(VAL_PERSISTABLEBUNDLE);
1700 writePersistableBundle((PersistableBundle) v);
1701 } else if (v instanceof Parcelable) {
1702 // IMPOTANT: cases for classes that implement Parcelable must
1703 // come before the Parcelable case, so that their specific VAL_*
1704 // types will be written.
1705 writeInt(VAL_PARCELABLE);
1706 writeParcelable((Parcelable) v, 0);
1707 } else if (v instanceof Short) {
1708 writeInt(VAL_SHORT);
1709 writeInt(((Short) v).intValue());
1710 } else if (v instanceof Long) {
1712 writeLong((Long) v);
1713 } else if (v instanceof Float) {
1714 writeInt(VAL_FLOAT);
1715 writeFloat((Float) v);
1716 } else if (v instanceof Double) {
1717 writeInt(VAL_DOUBLE);
1718 writeDouble((Double) v);
1719 } else if (v instanceof Boolean) {
1720 writeInt(VAL_BOOLEAN);
1721 writeInt((Boolean) v ? 1 : 0);
1722 } else if (v instanceof CharSequence) {
1723 // Must be after String
1724 writeInt(VAL_CHARSEQUENCE);
1725 writeCharSequence((CharSequence) v);
1726 } else if (v instanceof List) {
1728 writeList((List) v);
1729 } else if (v instanceof SparseArray) {
1730 writeInt(VAL_SPARSEARRAY);
1731 writeSparseArray((SparseArray) v);
1732 } else if (v instanceof boolean[]) {
1733 writeInt(VAL_BOOLEANARRAY);
1734 writeBooleanArray((boolean[]) v);
1735 } else if (v instanceof byte[]) {
1736 writeInt(VAL_BYTEARRAY);
1737 writeByteArray((byte[]) v);
1738 } else if (v instanceof String[]) {
1739 writeInt(VAL_STRINGARRAY);
1740 writeStringArray((String[]) v);
1741 } else if (v instanceof CharSequence[]) {
1742 // Must be after String[] and before Object[]
1743 writeInt(VAL_CHARSEQUENCEARRAY);
1744 writeCharSequenceArray((CharSequence[]) v);
1745 } else if (v instanceof IBinder) {
1746 writeInt(VAL_IBINDER);
1747 writeStrongBinder((IBinder) v);
1748 } else if (v instanceof Parcelable[]) {
1749 writeInt(VAL_PARCELABLEARRAY);
1750 writeParcelableArray((Parcelable[]) v, 0);
1751 } else if (v instanceof int[]) {
1752 writeInt(VAL_INTARRAY);
1753 writeIntArray((int[]) v);
1754 } else if (v instanceof long[]) {
1755 writeInt(VAL_LONGARRAY);
1756 writeLongArray((long[]) v);
1757 } else if (v instanceof Byte) {
1760 } else if (v instanceof Size) {
1762 writeSize((Size) v);
1763 } else if (v instanceof SizeF) {
1764 writeInt(VAL_SIZEF);
1765 writeSizeF((SizeF) v);
1766 } else if (v instanceof double[]) {
1767 writeInt(VAL_DOUBLEARRAY);
1768 writeDoubleArray((double[]) v);
1770 Class<?> clazz = v.getClass();
1771 if (clazz.isArray() && clazz.getComponentType() == Object.class) {
1772 // Only pure Object[] are written here, Other arrays of non-primitive types are
1773 // handled by serialization as this does not record the component type.
1774 writeInt(VAL_OBJECTARRAY);
1775 writeArray((Object[]) v);
1776 } else if (v instanceof Serializable) {
1778 writeInt(VAL_SERIALIZABLE);
1779 writeSerializable((Serializable) v);
1781 throw new RuntimeException("Parcel: unable to marshal value " + v);
1787 * Flatten the name of the class of the Parcelable and its contents
1790 * @param p The Parcelable object to be written.
1791 * @param parcelableFlags Contextual flags as per
1792 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1794 public final void writeParcelable(Parcelable p, int parcelableFlags) {
1799 writeParcelableCreator(p);
1800 p.writeToParcel(this, parcelableFlags);
1804 public final void writeParcelableCreator(Parcelable p) {
1805 String name = p.getClass().getName();
1810 * Write a generic serializable object in to a Parcel. It is strongly
1811 * recommended that this method be avoided, since the serialization
1812 * overhead is extremely large, and this approach will be much slower than
1813 * using the other approaches to writing data in to a Parcel.
1815 public final void writeSerializable(Serializable s) {
1820 String name = s.getClass().getName();
1823 ByteArrayOutputStream baos = new ByteArrayOutputStream();
1825 ObjectOutputStream oos = new ObjectOutputStream(baos);
1829 writeByteArray(baos.toByteArray());
1830 } catch (IOException ioe) {
1831 throw new RuntimeException("Parcelable encountered " +
1832 "IOException writing serializable object (name = " + name +
1838 * Special function for writing an exception result at the header of
1839 * a parcel, to be used when returning an exception from a transaction.
1840 * Note that this currently only supports a few exception types; any other
1841 * exception will be re-thrown by this function as a RuntimeException
1842 * (to be caught by the system's last-resort exception handling when
1843 * dispatching a transaction).
1845 * <p>The supported exception types are:
1847 * <li>{@link BadParcelableException}
1848 * <li>{@link IllegalArgumentException}
1849 * <li>{@link IllegalStateException}
1850 * <li>{@link NullPointerException}
1851 * <li>{@link SecurityException}
1852 * <li>{@link UnsupportedOperationException}
1853 * <li>{@link NetworkOnMainThreadException}
1856 * @param e The Exception to be written.
1858 * @see #writeNoException
1859 * @see #readException
1861 public final void writeException(Exception e) {
1863 if (e instanceof Parcelable
1864 && (e.getClass().getClassLoader() == Parcelable.class.getClassLoader())) {
1865 // We only send Parcelable exceptions that are in the
1866 // BootClassLoader to ensure that the receiver can unpack them
1867 code = EX_PARCELABLE;
1868 } else if (e instanceof SecurityException) {
1870 } else if (e instanceof BadParcelableException) {
1871 code = EX_BAD_PARCELABLE;
1872 } else if (e instanceof IllegalArgumentException) {
1873 code = EX_ILLEGAL_ARGUMENT;
1874 } else if (e instanceof NullPointerException) {
1875 code = EX_NULL_POINTER;
1876 } else if (e instanceof IllegalStateException) {
1877 code = EX_ILLEGAL_STATE;
1878 } else if (e instanceof NetworkOnMainThreadException) {
1879 code = EX_NETWORK_MAIN_THREAD;
1880 } else if (e instanceof UnsupportedOperationException) {
1881 code = EX_UNSUPPORTED_OPERATION;
1882 } else if (e instanceof ServiceSpecificException) {
1883 code = EX_SERVICE_SPECIFIC;
1886 StrictMode.clearGatheredViolations();
1888 if (e instanceof RuntimeException) {
1889 throw (RuntimeException) e;
1891 throw new RuntimeException(e);
1893 writeString(e.getMessage());
1895 case EX_SERVICE_SPECIFIC:
1896 writeInt(((ServiceSpecificException) e).errorCode);
1899 // Write parceled exception prefixed by length
1900 final int sizePosition = dataPosition();
1902 writeParcelable((Parcelable) e, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
1903 final int payloadPosition = dataPosition();
1904 setDataPosition(sizePosition);
1905 writeInt(payloadPosition - sizePosition);
1906 setDataPosition(payloadPosition);
1912 * Special function for writing information at the front of the Parcel
1913 * indicating that no exception occurred.
1915 * @see #writeException
1916 * @see #readException
1918 public final void writeNoException() {
1919 // Despite the name of this function ("write no exception"),
1920 // it should instead be thought of as "write the RPC response
1921 // header", but because this function name is written out by
1922 // the AIDL compiler, we're not going to rename it.
1924 // The response header, in the non-exception case (see also
1925 // writeException above, also called by the AIDL compiler), is
1926 // either a 0 (the default case), or EX_HAS_REPLY_HEADER if
1927 // StrictMode has gathered up violations that have occurred
1928 // during a Binder call, in which case we write out the number
1929 // of violations and their details, serialized, before the
1930 // actual RPC respons data. The receiving end of this is
1931 // readException(), below.
1932 if (StrictMode.hasGatheredViolations()) {
1933 writeInt(EX_HAS_REPLY_HEADER);
1934 final int sizePosition = dataPosition();
1935 writeInt(0); // total size of fat header, to be filled in later
1936 StrictMode.writeGatheredViolationsToParcel(this);
1937 final int payloadPosition = dataPosition();
1938 setDataPosition(sizePosition);
1939 writeInt(payloadPosition - sizePosition); // header size
1940 setDataPosition(payloadPosition);
1947 * Special function for reading an exception result from the header of
1948 * a parcel, to be used after receiving the result of a transaction. This
1949 * will throw the exception for you if it had been written to the Parcel,
1950 * otherwise return and let you read the normal result data from the Parcel.
1952 * @see #writeException
1953 * @see #writeNoException
1955 public final void readException() {
1956 int code = readExceptionCode();
1958 String msg = readString();
1959 readException(code, msg);
1964 * Parses the header of a Binder call's response Parcel and
1965 * returns the exception code. Deals with lite or fat headers.
1966 * In the common successful case, this header is generally zero.
1967 * In less common cases, it's a small negative number and will be
1968 * followed by an error string.
1970 * This exists purely for android.database.DatabaseUtils and
1971 * insulating it from having to handle fat headers as returned by
1972 * e.g. StrictMode-induced RPC responses.
1976 public final int readExceptionCode() {
1977 int code = readInt();
1978 if (code == EX_HAS_REPLY_HEADER) {
1979 int headerSize = readInt();
1980 if (headerSize == 0) {
1981 Log.e(TAG, "Unexpected zero-sized Parcel reply header.");
1983 // Currently the only thing in the header is StrictMode stacks,
1984 // but discussions around event/RPC tracing suggest we might
1985 // put that here too. If so, switch on sub-header tags here.
1986 // But for now, just parse out the StrictMode stuff.
1987 StrictMode.readAndHandleBinderCallViolations(this);
1989 // And fat response headers are currently only used when
1990 // there are no exceptions, so return no error:
1997 * Throw an exception with the given message. Not intended for use
1998 * outside the Parcel class.
2000 * @param code Used to determine which exception class to throw.
2001 * @param msg The exception message.
2003 public final void readException(int code, String msg) {
2006 if (readInt() > 0) {
2007 SneakyThrow.sneakyThrow(
2008 (Exception) readParcelable(Parcelable.class.getClassLoader()));
2010 throw new RuntimeException(msg + " [missing Parcelable]");
2013 throw new SecurityException(msg);
2014 case EX_BAD_PARCELABLE:
2015 throw new BadParcelableException(msg);
2016 case EX_ILLEGAL_ARGUMENT:
2017 throw new IllegalArgumentException(msg);
2018 case EX_NULL_POINTER:
2019 throw new NullPointerException(msg);
2020 case EX_ILLEGAL_STATE:
2021 throw new IllegalStateException(msg);
2022 case EX_NETWORK_MAIN_THREAD:
2023 throw new NetworkOnMainThreadException();
2024 case EX_UNSUPPORTED_OPERATION:
2025 throw new UnsupportedOperationException(msg);
2026 case EX_SERVICE_SPECIFIC:
2027 throw new ServiceSpecificException(readInt(), msg);
2029 throw new RuntimeException("Unknown exception code: " + code
2034 * Read an integer value from the parcel at the current dataPosition().
2036 public final int readInt() {
2037 return nativeReadInt(mNativePtr);
2041 * Read a long integer value from the parcel at the current dataPosition().
2043 public final long readLong() {
2044 return nativeReadLong(mNativePtr);
2048 * Read a floating point value from the parcel at the current
2051 public final float readFloat() {
2052 return nativeReadFloat(mNativePtr);
2056 * Read a double precision floating point value from the parcel at the
2057 * current dataPosition().
2059 public final double readDouble() {
2060 return nativeReadDouble(mNativePtr);
2064 * Read a string value from the parcel at the current dataPosition().
2066 public final String readString() {
2067 return mReadWriteHelper.readString(this);
2071 * Read a string without going though a {@link ReadWriteHelper}. Subclasses of
2072 * {@link ReadWriteHelper} must use this method instead of {@link #readString} to avoid
2073 * infinity recursive calls.
2077 public String readStringNoHelper() {
2078 return nativeReadString(mNativePtr);
2082 public final boolean readBoolean() {
2083 return readInt() != 0;
2087 * Read a CharSequence value from the parcel at the current dataPosition().
2090 public final CharSequence readCharSequence() {
2091 return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
2095 * Read an object from the parcel at the current dataPosition().
2097 public final IBinder readStrongBinder() {
2098 return nativeReadStrongBinder(mNativePtr);
2102 * Read a FileDescriptor from the parcel at the current dataPosition().
2104 public final ParcelFileDescriptor readFileDescriptor() {
2105 FileDescriptor fd = nativeReadFileDescriptor(mNativePtr);
2106 return fd != null ? new ParcelFileDescriptor(fd) : null;
2110 public final FileDescriptor readRawFileDescriptor() {
2111 return nativeReadFileDescriptor(mNativePtr);
2116 * Read and return a new array of FileDescriptors from the parcel.
2117 * @return the FileDescriptor array, or null if the array is null.
2119 public final FileDescriptor[] createRawFileDescriptorArray() {
2124 FileDescriptor[] f = new FileDescriptor[N];
2125 for (int i = 0; i < N; i++) {
2126 f[i] = readRawFileDescriptor();
2133 * Read an array of FileDescriptors from a parcel.
2134 * The passed array must be exactly the length of the array in the parcel.
2135 * @return the FileDescriptor array, or null if the array is null.
2137 public final void readRawFileDescriptorArray(FileDescriptor[] val) {
2139 if (N == val.length) {
2140 for (int i=0; i<N; i++) {
2141 val[i] = readRawFileDescriptor();
2144 throw new RuntimeException("bad array lengths");
2148 /** @deprecated use {@link android.system.Os#open(String, int, int)} */
2150 static native FileDescriptor openFileDescriptor(String file, int mode)
2151 throws FileNotFoundException;
2153 /** @deprecated use {@link android.system.Os#dup(FileDescriptor)} */
2155 static native FileDescriptor dupFileDescriptor(FileDescriptor orig) throws IOException;
2157 /** @deprecated use {@link android.system.Os#close(FileDescriptor)} */
2159 static native void closeFileDescriptor(FileDescriptor desc) throws IOException;
2161 static native void clearFileDescriptor(FileDescriptor desc);
2164 * Read a byte value from the parcel at the current dataPosition().
2166 public final byte readByte() {
2167 return (byte)(readInt() & 0xff);
2171 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2172 * been written with {@link #writeBundle}. Read into an existing Map object
2173 * from the parcel at the current dataPosition().
2175 public final void readMap(Map outVal, ClassLoader loader) {
2177 readMapInternal(outVal, N, loader);
2181 * Read into an existing List object from the parcel at the current
2182 * dataPosition(), using the given class loader to load any enclosed
2183 * Parcelables. If it is null, the default class loader is used.
2185 public final void readList(List outVal, ClassLoader loader) {
2187 readListInternal(outVal, N, loader);
2191 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
2192 * been written with {@link #writeBundle}. Read and return a new HashMap
2193 * object from the parcel at the current dataPosition(), using the given
2194 * class loader to load any enclosed Parcelables. Returns null if
2195 * the previously written map object was null.
2197 public final HashMap readHashMap(ClassLoader loader)
2203 HashMap m = new HashMap(N);
2204 readMapInternal(m, N, loader);
2209 * Read and return a new Bundle object from the parcel at the current
2210 * dataPosition(). Returns null if the previously written Bundle object was
2213 public final Bundle readBundle() {
2214 return readBundle(null);
2218 * Read and return a new Bundle object from the parcel at the current
2219 * dataPosition(), using the given class loader to initialize the class
2220 * loader of the Bundle for later retrieval of Parcelable objects.
2221 * Returns null if the previously written Bundle object was null.
2223 public final Bundle readBundle(ClassLoader loader) {
2224 int length = readInt();
2226 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2230 final Bundle bundle = new Bundle(this, length);
2231 if (loader != null) {
2232 bundle.setClassLoader(loader);
2238 * Read and return a new Bundle object from the parcel at the current
2239 * dataPosition(). Returns null if the previously written Bundle object was
2242 public final PersistableBundle readPersistableBundle() {
2243 return readPersistableBundle(null);
2247 * Read and return a new Bundle object from the parcel at the current
2248 * dataPosition(), using the given class loader to initialize the class
2249 * loader of the Bundle for later retrieval of Parcelable objects.
2250 * Returns null if the previously written Bundle object was null.
2252 public final PersistableBundle readPersistableBundle(ClassLoader loader) {
2253 int length = readInt();
2255 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length);
2259 final PersistableBundle bundle = new PersistableBundle(this, length);
2260 if (loader != null) {
2261 bundle.setClassLoader(loader);
2267 * Read a Size from the parcel at the current dataPosition().
2269 public final Size readSize() {
2270 final int width = readInt();
2271 final int height = readInt();
2272 return new Size(width, height);
2276 * Read a SizeF from the parcel at the current dataPosition().
2278 public final SizeF readSizeF() {
2279 final float width = readFloat();
2280 final float height = readFloat();
2281 return new SizeF(width, height);
2285 * Read and return a byte[] object from the parcel.
2287 public final byte[] createByteArray() {
2288 return nativeCreateByteArray(mNativePtr);
2292 * Read a byte[] object from the parcel and copy it into the
2295 public final void readByteArray(byte[] val) {
2296 boolean valid = nativeReadByteArray(mNativePtr, val, (val != null) ? val.length : 0);
2298 throw new RuntimeException("bad array lengths");
2303 * Read a blob of data from the parcel and return it as a byte array.
2307 public final byte[] readBlob() {
2308 return nativeReadBlob(mNativePtr);
2312 * Read and return a String[] object from the parcel.
2315 public final String[] readStringArray() {
2316 String[] array = null;
2318 int length = readInt();
2321 array = new String[length];
2323 for (int i = 0 ; i < length ; i++)
2325 array[i] = readString();
2333 * Read and return a CharSequence[] object from the parcel.
2336 public final CharSequence[] readCharSequenceArray() {
2337 CharSequence[] array = null;
2339 int length = readInt();
2342 array = new CharSequence[length];
2344 for (int i = 0 ; i < length ; i++)
2346 array[i] = readCharSequence();
2354 * Read and return an ArrayList<CharSequence> object from the parcel.
2357 public final ArrayList<CharSequence> readCharSequenceList() {
2358 ArrayList<CharSequence> array = null;
2360 int length = readInt();
2362 array = new ArrayList<CharSequence>(length);
2364 for (int i = 0 ; i < length ; i++) {
2365 array.add(readCharSequence());
2373 * Read and return a new ArrayList object from the parcel at the current
2374 * dataPosition(). Returns null if the previously written list object was
2375 * null. The given class loader will be used to load any enclosed
2378 public final ArrayList readArrayList(ClassLoader loader) {
2383 ArrayList l = new ArrayList(N);
2384 readListInternal(l, N, loader);
2389 * Read and return a new Object array from the parcel at the current
2390 * dataPosition(). Returns null if the previously written array was
2391 * null. The given class loader will be used to load any enclosed
2394 public final Object[] readArray(ClassLoader loader) {
2399 Object[] l = new Object[N];
2400 readArrayInternal(l, N, loader);
2405 * Read and return a new SparseArray object from the parcel at the current
2406 * dataPosition(). Returns null if the previously written list object was
2407 * null. The given class loader will be used to load any enclosed
2410 public final SparseArray readSparseArray(ClassLoader loader) {
2415 SparseArray sa = new SparseArray(N);
2416 readSparseArrayInternal(sa, N, loader);
2421 * Read and return a new SparseBooleanArray object from the parcel at the current
2422 * dataPosition(). Returns null if the previously written list object was
2425 public final SparseBooleanArray readSparseBooleanArray() {
2430 SparseBooleanArray sa = new SparseBooleanArray(N);
2431 readSparseBooleanArrayInternal(sa, N);
2436 * Read and return a new SparseIntArray object from the parcel at the current
2437 * dataPosition(). Returns null if the previously written array object was null.
2440 public final SparseIntArray readSparseIntArray() {
2445 SparseIntArray sa = new SparseIntArray(N);
2446 readSparseIntArrayInternal(sa, N);
2451 * Read and return a new ArrayList containing a particular object type from
2452 * the parcel that was written with {@link #writeTypedList} at the
2453 * current dataPosition(). Returns null if the
2454 * previously written list object was null. The list <em>must</em> have
2455 * previously been written via {@link #writeTypedList} with the same object
2458 * @return A newly created ArrayList containing objects with the same data
2459 * as those that were previously written.
2461 * @see #writeTypedList
2463 public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
2468 ArrayList<T> l = new ArrayList<T>(N);
2470 if (readInt() != 0) {
2471 l.add(c.createFromParcel(this));
2481 * Read into the given List items containing a particular object type
2482 * that were written with {@link #writeTypedList} at the
2483 * current dataPosition(). The list <em>must</em> have
2484 * previously been written via {@link #writeTypedList} with the same object
2487 * @return A newly created ArrayList containing objects with the same data
2488 * as those that were previously written.
2490 * @see #writeTypedList
2492 public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
2493 int M = list.size();
2496 for (; i < M && i < N; i++) {
2497 if (readInt() != 0) {
2498 list.set(i, c.createFromParcel(this));
2504 if (readInt() != 0) {
2505 list.add(c.createFromParcel(this));
2516 * Read and return a new ArrayList containing String objects from
2517 * the parcel that was written with {@link #writeStringList} at the
2518 * current dataPosition(). Returns null if the
2519 * previously written list object was null.
2521 * @return A newly created ArrayList containing strings with the same data
2522 * as those that were previously written.
2524 * @see #writeStringList
2526 public final ArrayList<String> createStringArrayList() {
2531 ArrayList<String> l = new ArrayList<String>(N);
2533 l.add(readString());
2540 * Read and return a new ArrayList containing IBinder objects from
2541 * the parcel that was written with {@link #writeBinderList} at the
2542 * current dataPosition(). Returns null if the
2543 * previously written list object was null.
2545 * @return A newly created ArrayList containing strings with the same data
2546 * as those that were previously written.
2548 * @see #writeBinderList
2550 public final ArrayList<IBinder> createBinderArrayList() {
2555 ArrayList<IBinder> l = new ArrayList<IBinder>(N);
2557 l.add(readStrongBinder());
2564 * Read into the given List items String objects that were written with
2565 * {@link #writeStringList} at the current dataPosition().
2567 * @return A newly created ArrayList containing strings with the same data
2568 * as those that were previously written.
2570 * @see #writeStringList
2572 public final void readStringList(List<String> list) {
2573 int M = list.size();
2576 for (; i < M && i < N; i++) {
2577 list.set(i, readString());
2580 list.add(readString());
2588 * Read into the given List items IBinder objects that were written with
2589 * {@link #writeBinderList} at the current dataPosition().
2591 * @see #writeBinderList
2593 public final void readBinderList(List<IBinder> list) {
2594 int M = list.size();
2597 for (; i < M && i < N; i++) {
2598 list.set(i, readStrongBinder());
2601 list.add(readStrongBinder());
2609 * Read the list of {@code Parcelable} objects at the current data position into the
2610 * given {@code list}. The contents of the {@code list} are replaced. If the serialized
2611 * list was {@code null}, {@code list} is cleared.
2613 * @see #writeParcelableList(List, int)
2616 public final <T extends Parcelable> List<T> readParcelableList(List<T> list, ClassLoader cl) {
2617 final int N = readInt();
2623 final int M = list.size();
2625 for (; i < M && i < N; i++) {
2626 list.set(i, (T) readParcelable(cl));
2629 list.add((T) readParcelable(cl));
2638 * Read and return a new array containing a particular object type from
2639 * the parcel at the current dataPosition(). Returns null if the
2640 * previously written array was null. The array <em>must</em> have
2641 * previously been written via {@link #writeTypedArray} with the same
2644 * @return A newly created array containing objects with the same data
2645 * as those that were previously written.
2647 * @see #writeTypedArray
2649 public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
2654 T[] l = c.newArray(N);
2655 for (int i=0; i<N; i++) {
2656 if (readInt() != 0) {
2657 l[i] = c.createFromParcel(this);
2663 public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
2665 if (N == val.length) {
2666 for (int i=0; i<N; i++) {
2667 if (readInt() != 0) {
2668 val[i] = c.createFromParcel(this);
2674 throw new RuntimeException("bad array lengths");
2683 public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
2684 return createTypedArray(c);
2688 * Read and return a typed Parcelable object from a parcel.
2689 * Returns null if the previous written object was null.
2690 * The object <em>must</em> have previous been written via
2691 * {@link #writeTypedObject} with the same object type.
2693 * @return A newly created object of the type that was previously
2696 * @see #writeTypedObject
2698 public final <T> T readTypedObject(Parcelable.Creator<T> c) {
2699 if (readInt() != 0) {
2700 return c.createFromParcel(this);
2707 * Write a heterogeneous array of Parcelable objects into the Parcel.
2708 * Each object in the array is written along with its class name, so
2709 * that the correct class can later be instantiated. As a result, this
2710 * has significantly more overhead than {@link #writeTypedArray}, but will
2711 * correctly handle an array containing more than one type of object.
2713 * @param value The array of objects to be written.
2714 * @param parcelableFlags Contextual flags as per
2715 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
2717 * @see #writeTypedArray
2719 public final <T extends Parcelable> void writeParcelableArray(T[] value,
2720 int parcelableFlags) {
2721 if (value != null) {
2722 int N = value.length;
2724 for (int i=0; i<N; i++) {
2725 writeParcelable(value[i], parcelableFlags);
2733 * Read a typed object from a parcel. The given class loader will be
2734 * used to load any enclosed Parcelables. If it is null, the default class
2735 * loader will be used.
2737 public final Object readValue(ClassLoader loader) {
2738 int type = readInt();
2745 return readString();
2751 return readHashMap(loader);
2753 case VAL_PARCELABLE:
2754 return readParcelable(loader);
2757 return (short) readInt();
2766 return readDouble();
2769 return readInt() == 1;
2771 case VAL_CHARSEQUENCE:
2772 return readCharSequence();
2775 return readArrayList(loader);
2777 case VAL_BOOLEANARRAY:
2778 return createBooleanArray();
2781 return createByteArray();
2783 case VAL_STRINGARRAY:
2784 return readStringArray();
2786 case VAL_CHARSEQUENCEARRAY:
2787 return readCharSequenceArray();
2790 return readStrongBinder();
2792 case VAL_OBJECTARRAY:
2793 return readArray(loader);
2796 return createIntArray();
2799 return createLongArray();
2804 case VAL_SERIALIZABLE:
2805 return readSerializable(loader);
2807 case VAL_PARCELABLEARRAY:
2808 return readParcelableArray(loader);
2810 case VAL_SPARSEARRAY:
2811 return readSparseArray(loader);
2813 case VAL_SPARSEBOOLEANARRAY:
2814 return readSparseBooleanArray();
2817 return readBundle(loader); // loading will be deferred
2819 case VAL_PERSISTABLEBUNDLE:
2820 return readPersistableBundle(loader);
2828 case VAL_DOUBLEARRAY:
2829 return createDoubleArray();
2832 int off = dataPosition() - 4;
2833 throw new RuntimeException(
2834 "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
2839 * Read and return a new Parcelable from the parcel. The given class loader
2840 * will be used to load any enclosed Parcelables. If it is null, the default
2841 * class loader will be used.
2842 * @param loader A ClassLoader from which to instantiate the Parcelable
2843 * object, or null for the default class loader.
2844 * @return Returns the newly created Parcelable, or null if a null
2845 * object has been written.
2846 * @throws BadParcelableException Throws BadParcelableException if there
2847 * was an error trying to instantiate the Parcelable.
2849 @SuppressWarnings("unchecked")
2850 public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
2851 Parcelable.Creator<?> creator = readParcelableCreator(loader);
2852 if (creator == null) {
2855 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2856 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2857 (Parcelable.ClassLoaderCreator<?>) creator;
2858 return (T) classLoaderCreator.createFromParcel(this, loader);
2860 return (T) creator.createFromParcel(this);
2864 @SuppressWarnings("unchecked")
2865 public final <T extends Parcelable> T readCreator(Parcelable.Creator<?> creator,
2866 ClassLoader loader) {
2867 if (creator instanceof Parcelable.ClassLoaderCreator<?>) {
2868 Parcelable.ClassLoaderCreator<?> classLoaderCreator =
2869 (Parcelable.ClassLoaderCreator<?>) creator;
2870 return (T) classLoaderCreator.createFromParcel(this, loader);
2872 return (T) creator.createFromParcel(this);
2876 public final Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) {
2877 String name = readString();
2881 Parcelable.Creator<?> creator;
2882 synchronized (mCreators) {
2883 HashMap<String,Parcelable.Creator<?>> map = mCreators.get(loader);
2885 map = new HashMap<>();
2886 mCreators.put(loader, map);
2888 creator = map.get(name);
2889 if (creator == null) {
2891 // If loader == null, explicitly emulate Class.forName(String) "caller
2892 // classloader" behavior.
2893 ClassLoader parcelableClassLoader =
2894 (loader == null ? getClass().getClassLoader() : loader);
2895 // Avoid initializing the Parcelable class until we know it implements
2896 // Parcelable and has the necessary CREATOR field. http://b/1171613.
2897 Class<?> parcelableClass = Class.forName(name, false /* initialize */,
2898 parcelableClassLoader);
2899 if (!Parcelable.class.isAssignableFrom(parcelableClass)) {
2900 throw new BadParcelableException("Parcelable protocol requires that the "
2901 + "class implements Parcelable");
2903 Field f = parcelableClass.getField("CREATOR");
2904 if ((f.getModifiers() & Modifier.STATIC) == 0) {
2905 throw new BadParcelableException("Parcelable protocol requires "
2906 + "the CREATOR object to be static on class " + name);
2908 Class<?> creatorType = f.getType();
2909 if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) {
2910 // Fail before calling Field.get(), not after, to avoid initializing
2911 // parcelableClass unnecessarily.
2912 throw new BadParcelableException("Parcelable protocol requires a "
2913 + "Parcelable.Creator object called "
2914 + "CREATOR on class " + name);
2916 creator = (Parcelable.Creator<?>) f.get(null);
2918 catch (IllegalAccessException e) {
2919 Log.e(TAG, "Illegal access when unmarshalling: " + name, e);
2920 throw new BadParcelableException(
2921 "IllegalAccessException when unmarshalling: " + name);
2923 catch (ClassNotFoundException e) {
2924 Log.e(TAG, "Class not found when unmarshalling: " + name, e);
2925 throw new BadParcelableException(
2926 "ClassNotFoundException when unmarshalling: " + name);
2928 catch (NoSuchFieldException e) {
2929 throw new BadParcelableException("Parcelable protocol requires a "
2930 + "Parcelable.Creator object called "
2931 + "CREATOR on class " + name);
2933 if (creator == null) {
2934 throw new BadParcelableException("Parcelable protocol requires a "
2935 + "non-null Parcelable.Creator object called "
2936 + "CREATOR on class " + name);
2939 map.put(name, creator);
2947 * Read and return a new Parcelable array from the parcel.
2948 * The given class loader will be used to load any enclosed
2950 * @return the Parcelable array, or null if the array is null
2952 public final Parcelable[] readParcelableArray(ClassLoader loader) {
2957 Parcelable[] p = new Parcelable[N];
2958 for (int i = 0; i < N; i++) {
2959 p[i] = readParcelable(loader);
2965 public final <T extends Parcelable> T[] readParcelableArray(ClassLoader loader,
2971 T[] p = (T[]) Array.newInstance(clazz, N);
2972 for (int i = 0; i < N; i++) {
2973 p[i] = readParcelable(loader);
2979 * Read and return a new Serializable object from the parcel.
2980 * @return the Serializable object, or null if the Serializable name
2981 * wasn't found in the parcel.
2983 public final Serializable readSerializable() {
2984 return readSerializable(null);
2987 private final Serializable readSerializable(final ClassLoader loader) {
2988 String name = readString();
2990 // For some reason we were unable to read the name of the Serializable (either there
2991 // is nothing left in the Parcel to read, or the next value wasn't a String), so
2992 // return null, which indicates that the name wasn't found in the parcel.
2996 byte[] serializedData = createByteArray();
2997 ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
2999 ObjectInputStream ois = new ObjectInputStream(bais) {
3001 protected Class<?> resolveClass(ObjectStreamClass osClass)
3002 throws IOException, ClassNotFoundException {
3003 // try the custom classloader if provided
3004 if (loader != null) {
3005 Class<?> c = Class.forName(osClass.getName(), false, loader);
3010 return super.resolveClass(osClass);
3013 return (Serializable) ois.readObject();
3014 } catch (IOException ioe) {
3015 throw new RuntimeException("Parcelable encountered " +
3016 "IOException reading a Serializable object (name = " + name +
3018 } catch (ClassNotFoundException cnfe) {
3019 throw new RuntimeException("Parcelable encountered " +
3020 "ClassNotFoundException reading a Serializable object (name = "
3021 + name + ")", cnfe);
3025 // Cache of previously looked up CREATOR.createFromParcel() methods for
3026 // particular classes. Keys are the names of the classes, values are
3028 private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator<?>>>
3029 mCreators = new HashMap<>();
3031 /** @hide for internal use only. */
3032 static protected final Parcel obtain(int obj) {
3033 throw new UnsupportedOperationException();
3037 static protected final Parcel obtain(long obj) {
3038 final Parcel[] pool = sHolderPool;
3039 synchronized (pool) {
3041 for (int i=0; i<POOL_SIZE; i++) {
3045 if (DEBUG_RECYCLE) {
3046 p.mStack = new RuntimeException();
3053 return new Parcel(obj);
3056 private Parcel(long nativePtr) {
3057 if (DEBUG_RECYCLE) {
3058 mStack = new RuntimeException();
3060 //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
3064 private void init(long nativePtr) {
3065 if (nativePtr != 0) {
3066 mNativePtr = nativePtr;
3067 mOwnsNativeParcelObject = false;
3069 mNativePtr = nativeCreate();
3070 mOwnsNativeParcelObject = true;
3074 private void freeBuffer() {
3075 if (mOwnsNativeParcelObject) {
3076 updateNativeSize(nativeFreeBuffer(mNativePtr));
3078 mReadWriteHelper = ReadWriteHelper.DEFAULT;
3081 private void destroy() {
3082 if (mNativePtr != 0) {
3083 if (mOwnsNativeParcelObject) {
3084 nativeDestroy(mNativePtr);
3085 updateNativeSize(0);
3089 mReadWriteHelper = null;
3093 protected void finalize() throws Throwable {
3094 if (DEBUG_RECYCLE) {
3095 if (mStack != null) {
3096 Log.w(TAG, "Client did not call Parcel.recycle()", mStack);
3102 /* package */ void readMapInternal(Map outVal, int N,
3103 ClassLoader loader) {
3105 Object key = readValue(loader);
3106 Object value = readValue(loader);
3107 outVal.put(key, value);
3112 /* package */ void readArrayMapInternal(ArrayMap outVal, int N,
3113 ClassLoader loader) {
3114 if (DEBUG_ARRAY_MAP) {
3115 RuntimeException here = new RuntimeException("here");
3116 here.fillInStackTrace();
3117 Log.d(TAG, "Reading " + N + " ArrayMap entries", here);
3121 if (DEBUG_ARRAY_MAP) startPos = dataPosition();
3122 String key = readString();
3123 Object value = readValue(loader);
3124 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Read #" + (N-1) + " "
3125 + (dataPosition()-startPos) + " bytes: key=0x"
3126 + Integer.toHexString((key != null ? key.hashCode() : 0)) + " " + key);
3127 outVal.append(key, value);
3133 /* package */ void readArrayMapSafelyInternal(ArrayMap outVal, int N,
3134 ClassLoader loader) {
3135 if (DEBUG_ARRAY_MAP) {
3136 RuntimeException here = new RuntimeException("here");
3137 here.fillInStackTrace();
3138 Log.d(TAG, "Reading safely " + N + " ArrayMap entries", here);
3141 String key = readString();
3142 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Read safe #" + (N-1) + ": key=0x"
3143 + (key != null ? key.hashCode() : 0) + " " + key);
3144 Object value = readValue(loader);
3145 outVal.put(key, value);
3151 * @hide For testing only.
3153 public void readArrayMap(ArrayMap outVal, ClassLoader loader) {
3154 final int N = readInt();
3158 readArrayMapInternal(outVal, N, loader);
3162 * Reads an array set.
3164 * @param loader The class loader to use.
3168 public @Nullable ArraySet<? extends Object> readArraySet(ClassLoader loader) {
3169 final int size = readInt();
3173 ArraySet<Object> result = new ArraySet<>(size);
3174 for (int i = 0; i < size; i++) {
3175 Object value = readValue(loader);
3176 result.append(value);
3181 private void readListInternal(List outVal, int N,
3182 ClassLoader loader) {
3184 Object value = readValue(loader);
3185 //Log.d(TAG, "Unmarshalling value=" + value);
3191 private void readArrayInternal(Object[] outVal, int N,
3192 ClassLoader loader) {
3193 for (int i = 0; i < N; i++) {
3194 Object value = readValue(loader);
3195 //Log.d(TAG, "Unmarshalling value=" + value);
3200 private void readSparseArrayInternal(SparseArray outVal, int N,
3201 ClassLoader loader) {
3203 int key = readInt();
3204 Object value = readValue(loader);
3205 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3206 outVal.append(key, value);
3212 private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
3214 int key = readInt();
3215 boolean value = this.readByte() == 1;
3216 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value);
3217 outVal.append(key, value);
3222 private void readSparseIntArrayInternal(SparseIntArray outVal, int N) {
3224 int key = readInt();
3225 int value = readInt();
3226 outVal.append(key, value);
3234 public long getBlobAshmemSize() {
3235 return nativeGetBlobAshmemSize(mNativePtr);