blob: 8ad600c644f3dcc41fadb3022e157e2448a52aad [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.os;
18
19import android.text.TextUtils;
20import android.util.Log;
21import android.util.SparseArray;
22import android.util.SparseBooleanArray;
23
24import java.io.ByteArrayInputStream;
25import java.io.ByteArrayOutputStream;
26import java.io.FileDescriptor;
27import java.io.FileNotFoundException;
28import java.io.IOException;
29import java.io.ObjectInputStream;
30import java.io.ObjectOutputStream;
31import java.io.Serializable;
32import java.lang.reflect.Field;
33import java.util.ArrayList;
34import java.util.HashMap;
35import java.util.List;
36import java.util.Map;
37import java.util.Set;
38
39/**
40 * Container for a message (data and object references) that can
41 * be sent through an IBinder. A Parcel can contain both flattened data
42 * that will be unflattened on the other side of the IPC (using the various
43 * methods here for writing specific types, or the general
44 * {@link Parcelable} interface), and references to live {@link IBinder}
45 * objects that will result in the other side receiving a proxy IBinder
46 * connected with the original IBinder in the Parcel.
47 *
48 * <p class="note">Parcel is <strong>not</strong> a general-purpose
49 * serialization mechanism. This class (and the corresponding
50 * {@link Parcelable} API for placing arbitrary objects into a Parcel) is
51 * designed as a high-performance IPC transport. As such, it is not
52 * appropriate to place any Parcel data in to persistent storage: changes
53 * in the underlying implementation of any of the data in the Parcel can
54 * render older data unreadable.</p>
55 *
56 * <p>The bulk of the Parcel API revolves around reading and writing data
57 * of various types. There are six major classes of such functions available.</p>
58 *
59 * <h3>Primitives</h3>
60 *
61 * <p>The most basic data functions are for writing and reading primitive
62 * data types: {@link #writeByte}, {@link #readByte}, {@link #writeDouble},
63 * {@link #readDouble}, {@link #writeFloat}, {@link #readFloat}, {@link #writeInt},
64 * {@link #readInt}, {@link #writeLong}, {@link #readLong},
65 * {@link #writeString}, {@link #readString}. Most other
66 * data operations are built on top of these. The given data is written and
67 * read using the endianess of the host CPU.</p>
68 *
69 * <h3>Primitive Arrays</h3>
70 *
71 * <p>There are a variety of methods for reading and writing raw arrays
72 * of primitive objects, which generally result in writing a 4-byte length
73 * followed by the primitive data items. The methods for reading can either
74 * read the data into an existing array, or create and return a new array.
75 * These available types are:</p>
76 *
77 * <ul>
78 * <li> {@link #writeBooleanArray(boolean[])},
79 * {@link #readBooleanArray(boolean[])}, {@link #createBooleanArray()}
80 * <li> {@link #writeByteArray(byte[])},
81 * {@link #writeByteArray(byte[], int, int)}, {@link #readByteArray(byte[])},
82 * {@link #createByteArray()}
83 * <li> {@link #writeCharArray(char[])}, {@link #readCharArray(char[])},
84 * {@link #createCharArray()}
85 * <li> {@link #writeDoubleArray(double[])}, {@link #readDoubleArray(double[])},
86 * {@link #createDoubleArray()}
87 * <li> {@link #writeFloatArray(float[])}, {@link #readFloatArray(float[])},
88 * {@link #createFloatArray()}
89 * <li> {@link #writeIntArray(int[])}, {@link #readIntArray(int[])},
90 * {@link #createIntArray()}
91 * <li> {@link #writeLongArray(long[])}, {@link #readLongArray(long[])},
92 * {@link #createLongArray()}
93 * <li> {@link #writeStringArray(String[])}, {@link #readStringArray(String[])},
94 * {@link #createStringArray()}.
95 * <li> {@link #writeSparseBooleanArray(SparseBooleanArray)},
96 * {@link #readSparseBooleanArray()}.
97 * </ul>
98 *
99 * <h3>Parcelables</h3>
100 *
101 * <p>The {@link Parcelable} protocol provides an extremely efficient (but
102 * low-level) protocol for objects to write and read themselves from Parcels.
103 * You can use the direct methods {@link #writeParcelable(Parcelable, int)}
104 * and {@link #readParcelable(ClassLoader)} or
105 * {@link #writeParcelableArray} and
106 * {@link #readParcelableArray(ClassLoader)} to write or read. These
107 * methods write both the class type and its data to the Parcel, allowing
108 * that class to be reconstructed from the appropriate class loader when
109 * later reading.</p>
110 *
111 * <p>There are also some methods that provide a more efficient way to work
112 * with Parcelables: {@link #writeTypedArray},
113 * {@link #writeTypedList(List)},
114 * {@link #readTypedArray} and {@link #readTypedList}. These methods
115 * do not write the class information of the original object: instead, the
116 * caller of the read function must know what type to expect and pass in the
117 * appropriate {@link Parcelable.Creator Parcelable.Creator} instead to
118 * properly construct the new object and read its data. (To more efficient
119 * write and read a single Parceable object, you can directly call
120 * {@link Parcelable#writeToParcel Parcelable.writeToParcel} and
121 * {@link Parcelable.Creator#createFromParcel Parcelable.Creator.createFromParcel}
122 * yourself.)</p>
123 *
124 * <h3>Bundles</h3>
125 *
126 * <p>A special type-safe container, called {@link Bundle}, is available
127 * for key/value maps of heterogeneous values. This has many optimizations
128 * for improved performance when reading and writing data, and its type-safe
129 * API avoids difficult to debug type errors when finally marshalling the
130 * data contents into a Parcel. The methods to use are
131 * {@link #writeBundle(Bundle)}, {@link #readBundle()}, and
132 * {@link #readBundle(ClassLoader)}.
133 *
134 * <h3>Active Objects</h3>
135 *
136 * <p>An unusual feature of Parcel is the ability to read and write active
137 * objects. For these objects the actual contents of the object is not
138 * written, rather a special token referencing the object is written. When
139 * reading the object back from the Parcel, you do not get a new instance of
140 * the object, but rather a handle that operates on the exact same object that
141 * was originally written. There are two forms of active objects available.</p>
142 *
143 * <p>{@link Binder} objects are a core facility of Android's general cross-process
144 * communication system. The {@link IBinder} interface describes an abstract
145 * protocol with a Binder object. Any such interface can be written in to
146 * a Parcel, and upon reading you will receive either the original object
147 * implementing that interface or a special proxy implementation
148 * that communicates calls back to the original object. The methods to use are
149 * {@link #writeStrongBinder(IBinder)},
150 * {@link #writeStrongInterface(IInterface)}, {@link #readStrongBinder()},
151 * {@link #writeBinderArray(IBinder[])}, {@link #readBinderArray(IBinder[])},
152 * {@link #createBinderArray()},
153 * {@link #writeBinderList(List)}, {@link #readBinderList(List)},
154 * {@link #createBinderArrayList()}.</p>
155 *
156 * <p>FileDescriptor objects, representing raw Linux file descriptor identifiers,
157 * can be written and {@link ParcelFileDescriptor} objects returned to operate
158 * on the original file descriptor. The returned file descriptor is a dup
159 * of the original file descriptor: the object and fd is different, but
160 * operating on the same underlying file stream, with the same position, etc.
161 * The methods to use are {@link #writeFileDescriptor(FileDescriptor)},
162 * {@link #readFileDescriptor()}.
163 *
164 * <h3>Untyped Containers</h3>
165 *
166 * <p>A final class of methods are for writing and reading standard Java
167 * containers of arbitrary types. These all revolve around the
168 * {@link #writeValue(Object)} and {@link #readValue(ClassLoader)} methods
169 * which define the types of objects allowed. The container methods are
170 * {@link #writeArray(Object[])}, {@link #readArray(ClassLoader)},
171 * {@link #writeList(List)}, {@link #readList(List, ClassLoader)},
172 * {@link #readArrayList(ClassLoader)},
173 * {@link #writeMap(Map)}, {@link #readMap(Map, ClassLoader)},
174 * {@link #writeSparseArray(SparseArray)},
175 * {@link #readSparseArray(ClassLoader)}.
176 */
177public final class Parcel {
178 private static final boolean DEBUG_RECYCLE = false;
179
180 @SuppressWarnings({"UnusedDeclaration"})
181 private int mObject; // used by native code
182 @SuppressWarnings({"UnusedDeclaration"})
183 private int mOwnObject; // used by native code
184 private RuntimeException mStack;
185
186 private static final int POOL_SIZE = 6;
187 private static final Parcel[] sOwnedPool = new Parcel[POOL_SIZE];
188 private static final Parcel[] sHolderPool = new Parcel[POOL_SIZE];
189
190 private static final int VAL_NULL = -1;
191 private static final int VAL_STRING = 0;
192 private static final int VAL_INTEGER = 1;
193 private static final int VAL_MAP = 2;
194 private static final int VAL_BUNDLE = 3;
195 private static final int VAL_PARCELABLE = 4;
196 private static final int VAL_SHORT = 5;
197 private static final int VAL_LONG = 6;
198 private static final int VAL_FLOAT = 7;
199 private static final int VAL_DOUBLE = 8;
200 private static final int VAL_BOOLEAN = 9;
201 private static final int VAL_CHARSEQUENCE = 10;
202 private static final int VAL_LIST = 11;
203 private static final int VAL_SPARSEARRAY = 12;
204 private static final int VAL_BYTEARRAY = 13;
205 private static final int VAL_STRINGARRAY = 14;
206 private static final int VAL_IBINDER = 15;
207 private static final int VAL_PARCELABLEARRAY = 16;
208 private static final int VAL_OBJECTARRAY = 17;
209 private static final int VAL_INTARRAY = 18;
210 private static final int VAL_LONGARRAY = 19;
211 private static final int VAL_BYTE = 20;
212 private static final int VAL_SERIALIZABLE = 21;
213 private static final int VAL_SPARSEBOOLEANARRAY = 22;
214 private static final int VAL_BOOLEANARRAY = 23;
Bjorn Bringert08bbffb2010-02-25 11:16:22 +0000215 private static final int VAL_CHARSEQUENCEARRAY = 24;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
217 private static final int EX_SECURITY = -1;
218 private static final int EX_BAD_PARCELABLE = -2;
219 private static final int EX_ILLEGAL_ARGUMENT = -3;
220 private static final int EX_NULL_POINTER = -4;
221 private static final int EX_ILLEGAL_STATE = -5;
222
223 public final static Parcelable.Creator<String> STRING_CREATOR
224 = new Parcelable.Creator<String>() {
225 public String createFromParcel(Parcel source) {
226 return source.readString();
227 }
228 public String[] newArray(int size) {
229 return new String[size];
230 }
231 };
232
233 /**
234 * Retrieve a new Parcel object from the pool.
235 */
236 public static Parcel obtain() {
237 final Parcel[] pool = sOwnedPool;
238 synchronized (pool) {
239 Parcel p;
240 for (int i=0; i<POOL_SIZE; i++) {
241 p = pool[i];
242 if (p != null) {
243 pool[i] = null;
244 if (DEBUG_RECYCLE) {
245 p.mStack = new RuntimeException();
246 }
247 return p;
248 }
249 }
250 }
251 return new Parcel(0);
252 }
253
254 /**
255 * Put a Parcel object back into the pool. You must not touch
256 * the object after this call.
257 */
258 public final void recycle() {
259 if (DEBUG_RECYCLE) mStack = null;
260 freeBuffer();
261 final Parcel[] pool = mOwnObject != 0 ? sOwnedPool : sHolderPool;
262 synchronized (pool) {
263 for (int i=0; i<POOL_SIZE; i++) {
264 if (pool[i] == null) {
265 pool[i] = this;
266 return;
267 }
268 }
269 }
270 }
271
272 /**
273 * Returns the total amount of data contained in the parcel.
274 */
275 public final native int dataSize();
276
277 /**
278 * Returns the amount of data remaining to be read from the
279 * parcel. That is, {@link #dataSize}-{@link #dataPosition}.
280 */
281 public final native int dataAvail();
282
283 /**
284 * Returns the current position in the parcel data. Never
285 * more than {@link #dataSize}.
286 */
287 public final native int dataPosition();
288
289 /**
290 * Returns the total amount of space in the parcel. This is always
291 * >= {@link #dataSize}. The difference between it and dataSize() is the
292 * amount of room left until the parcel needs to re-allocate its
293 * data buffer.
294 */
295 public final native int dataCapacity();
296
297 /**
298 * Change the amount of data in the parcel. Can be either smaller or
299 * larger than the current size. If larger than the current capacity,
300 * more memory will be allocated.
301 *
302 * @param size The new number of bytes in the Parcel.
303 */
304 public final native void setDataSize(int size);
305
306 /**
307 * Move the current read/write position in the parcel.
308 * @param pos New offset in the parcel; must be between 0 and
309 * {@link #dataSize}.
310 */
311 public final native void setDataPosition(int pos);
312
313 /**
314 * Change the capacity (current available space) of the parcel.
315 *
316 * @param size The new capacity of the parcel, in bytes. Can not be
317 * less than {@link #dataSize} -- that is, you can not drop existing data
318 * with this method.
319 */
320 public final native void setDataCapacity(int size);
321
322 /**
323 * Returns the raw bytes of the parcel.
324 *
325 * <p class="note">The data you retrieve here <strong>must not</strong>
326 * be placed in any kind of persistent storage (on local disk, across
327 * a network, etc). For that, you should use standard serialization
328 * or another kind of general serialization mechanism. The Parcel
329 * marshalled representation is highly optimized for local IPC, and as
330 * such does not attempt to maintain compatibility with data created
331 * in different versions of the platform.
332 */
333 public final native byte[] marshall();
334
335 /**
336 * Set the bytes in data to be the raw bytes of this Parcel.
337 */
338 public final native void unmarshall(byte[] data, int offest, int length);
339
340 public final native void appendFrom(Parcel parcel, int offset, int length);
341
342 /**
343 * Report whether the parcel contains any marshalled file descriptors.
344 */
345 public final native boolean hasFileDescriptors();
346
347 /**
348 * Store or read an IBinder interface token in the parcel at the current
349 * {@link #dataPosition}. This is used to validate that the marshalled
350 * transaction is intended for the target interface.
351 */
352 public final native void writeInterfaceToken(String interfaceName);
353 public final native void enforceInterface(String interfaceName);
354
355 /**
356 * Write a byte array into the parcel at the current {#link #dataPosition},
357 * growing {@link #dataCapacity} if needed.
358 * @param b Bytes to place into the parcel.
359 */
360 public final void writeByteArray(byte[] b) {
361 writeByteArray(b, 0, (b != null) ? b.length : 0);
362 }
363
364 /**
365 * Write an byte array into the parcel at the current {#link #dataPosition},
366 * growing {@link #dataCapacity} if needed.
367 * @param b Bytes to place into the parcel.
368 * @param offset Index of first byte to be written.
369 * @param len Number of bytes to write.
370 */
371 public final void writeByteArray(byte[] b, int offset, int len) {
372 if (b == null) {
373 writeInt(-1);
374 return;
375 }
376 if (b.length < offset + len || len < 0 || offset < 0) {
377 throw new ArrayIndexOutOfBoundsException();
378 }
379 writeNative(b, offset, len);
380 }
381
382 private native void writeNative(byte[] b, int offset, int len);
383
384 /**
385 * Write an integer value into the parcel at the current dataPosition(),
386 * growing dataCapacity() if needed.
387 */
388 public final native void writeInt(int val);
389
390 /**
391 * Write a long integer value into the parcel at the current dataPosition(),
392 * growing dataCapacity() if needed.
393 */
394 public final native void writeLong(long val);
395
396 /**
397 * Write a floating point value into the parcel at the current
398 * dataPosition(), growing dataCapacity() if needed.
399 */
400 public final native void writeFloat(float val);
401
402 /**
403 * Write a double precision floating point value into the parcel at the
404 * current dataPosition(), growing dataCapacity() if needed.
405 */
406 public final native void writeDouble(double val);
407
408 /**
409 * Write a string value into the parcel at the current dataPosition(),
410 * growing dataCapacity() if needed.
411 */
412 public final native void writeString(String val);
413
414 /**
Bjorn Bringert08bbffb2010-02-25 11:16:22 +0000415 * Write a CharSequence value into the parcel at the current dataPosition(),
416 * growing dataCapacity() if needed.
417 * @hide
418 */
419 public final void writeCharSequence(CharSequence val) {
420 TextUtils.writeToParcel(val, this, 0);
421 }
422
423 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800424 * Write an object into the parcel at the current dataPosition(),
425 * growing dataCapacity() if needed.
426 */
427 public final native void writeStrongBinder(IBinder val);
428
429 /**
430 * Write an object into the parcel at the current dataPosition(),
431 * growing dataCapacity() if needed.
432 */
433 public final void writeStrongInterface(IInterface val) {
434 writeStrongBinder(val == null ? null : val.asBinder());
435 }
436
437 /**
438 * Write a FileDescriptor into the parcel at the current dataPosition(),
439 * growing dataCapacity() if needed.
440 */
441 public final native void writeFileDescriptor(FileDescriptor val);
442
443 /**
444 * Write an byte value into the parcel at the current dataPosition(),
445 * growing dataCapacity() if needed.
446 */
447 public final void writeByte(byte val) {
448 writeInt(val);
449 }
450
451 /**
452 * Please use {@link #writeBundle} instead. Flattens a Map into the parcel
453 * at the current dataPosition(),
454 * growing dataCapacity() if needed. The Map keys must be String objects.
455 * The Map values are written using {@link #writeValue} and must follow
456 * the specification there.
457 *
458 * <p>It is strongly recommended to use {@link #writeBundle} instead of
459 * this method, since the Bundle class provides a type-safe API that
460 * allows you to avoid mysterious type errors at the point of marshalling.
461 */
462 public final void writeMap(Map val) {
463 writeMapInternal((Map<String,Object>) val);
464 }
465
466 /**
467 * Flatten a Map into the parcel at the current dataPosition(),
468 * growing dataCapacity() if needed. The Map keys must be String objects.
469 */
Dianne Hackborn6aff9052009-05-22 13:20:23 -0700470 /* package */ void writeMapInternal(Map<String,Object> val) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 if (val == null) {
472 writeInt(-1);
473 return;
474 }
475 Set<Map.Entry<String,Object>> entries = val.entrySet();
476 writeInt(entries.size());
477 for (Map.Entry<String,Object> e : entries) {
478 writeValue(e.getKey());
479 writeValue(e.getValue());
480 }
481 }
482
483 /**
484 * Flatten a Bundle into the parcel at the current dataPosition(),
485 * growing dataCapacity() if needed.
486 */
487 public final void writeBundle(Bundle val) {
488 if (val == null) {
489 writeInt(-1);
490 return;
491 }
492
Dianne Hackborn6aff9052009-05-22 13:20:23 -0700493 val.writeToParcel(this, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 }
495
496 /**
497 * Flatten a List into the parcel at the current dataPosition(), growing
498 * dataCapacity() if needed. The List values are written using
499 * {@link #writeValue} and must follow the specification there.
500 */
501 public final void writeList(List val) {
502 if (val == null) {
503 writeInt(-1);
504 return;
505 }
506 int N = val.size();
507 int i=0;
508 writeInt(N);
509 while (i < N) {
510 writeValue(val.get(i));
511 i++;
512 }
513 }
514
515 /**
516 * Flatten an Object array into the parcel at the current dataPosition(),
517 * growing dataCapacity() if needed. The array values are written using
518 * {@link #writeValue} and must follow the specification there.
519 */
520 public final void writeArray(Object[] val) {
521 if (val == null) {
522 writeInt(-1);
523 return;
524 }
525 int N = val.length;
526 int i=0;
527 writeInt(N);
528 while (i < N) {
529 writeValue(val[i]);
530 i++;
531 }
532 }
533
534 /**
535 * Flatten a generic SparseArray into the parcel at the current
536 * dataPosition(), growing dataCapacity() if needed. The SparseArray
537 * values are written using {@link #writeValue} and must follow the
538 * specification there.
539 */
540 public final void writeSparseArray(SparseArray<Object> val) {
541 if (val == null) {
542 writeInt(-1);
543 return;
544 }
545 int N = val.size();
546 writeInt(N);
547 int i=0;
548 while (i < N) {
549 writeInt(val.keyAt(i));
550 writeValue(val.valueAt(i));
551 i++;
552 }
553 }
554
555 public final void writeSparseBooleanArray(SparseBooleanArray val) {
556 if (val == null) {
557 writeInt(-1);
558 return;
559 }
560 int N = val.size();
561 writeInt(N);
562 int i=0;
563 while (i < N) {
564 writeInt(val.keyAt(i));
565 writeByte((byte)(val.valueAt(i) ? 1 : 0));
566 i++;
567 }
568 }
569
570 public final void writeBooleanArray(boolean[] val) {
571 if (val != null) {
572 int N = val.length;
573 writeInt(N);
574 for (int i=0; i<N; i++) {
575 writeInt(val[i] ? 1 : 0);
576 }
577 } else {
578 writeInt(-1);
579 }
580 }
581
582 public final boolean[] createBooleanArray() {
583 int N = readInt();
584 // >>2 as a fast divide-by-4 works in the create*Array() functions
585 // because dataAvail() will never return a negative number. 4 is
586 // the size of a stored boolean in the stream.
587 if (N >= 0 && N <= (dataAvail() >> 2)) {
588 boolean[] val = new boolean[N];
589 for (int i=0; i<N; i++) {
590 val[i] = readInt() != 0;
591 }
592 return val;
593 } else {
594 return null;
595 }
596 }
597
598 public final void readBooleanArray(boolean[] val) {
599 int N = readInt();
600 if (N == val.length) {
601 for (int i=0; i<N; i++) {
602 val[i] = readInt() != 0;
603 }
604 } else {
605 throw new RuntimeException("bad array lengths");
606 }
607 }
608
609 public final void writeCharArray(char[] val) {
610 if (val != null) {
611 int N = val.length;
612 writeInt(N);
613 for (int i=0; i<N; i++) {
614 writeInt((int)val[i]);
615 }
616 } else {
617 writeInt(-1);
618 }
619 }
620
621 public final char[] createCharArray() {
622 int N = readInt();
623 if (N >= 0 && N <= (dataAvail() >> 2)) {
624 char[] val = new char[N];
625 for (int i=0; i<N; i++) {
626 val[i] = (char)readInt();
627 }
628 return val;
629 } else {
630 return null;
631 }
632 }
633
634 public final void readCharArray(char[] val) {
635 int N = readInt();
636 if (N == val.length) {
637 for (int i=0; i<N; i++) {
638 val[i] = (char)readInt();
639 }
640 } else {
641 throw new RuntimeException("bad array lengths");
642 }
643 }
644
645 public final void writeIntArray(int[] val) {
646 if (val != null) {
647 int N = val.length;
648 writeInt(N);
649 for (int i=0; i<N; i++) {
650 writeInt(val[i]);
651 }
652 } else {
653 writeInt(-1);
654 }
655 }
656
657 public final int[] createIntArray() {
658 int N = readInt();
659 if (N >= 0 && N <= (dataAvail() >> 2)) {
660 int[] val = new int[N];
661 for (int i=0; i<N; i++) {
662 val[i] = readInt();
663 }
664 return val;
665 } else {
666 return null;
667 }
668 }
669
670 public final void readIntArray(int[] val) {
671 int N = readInt();
672 if (N == val.length) {
673 for (int i=0; i<N; i++) {
674 val[i] = readInt();
675 }
676 } else {
677 throw new RuntimeException("bad array lengths");
678 }
679 }
680
681 public final void writeLongArray(long[] val) {
682 if (val != null) {
683 int N = val.length;
684 writeInt(N);
685 for (int i=0; i<N; i++) {
686 writeLong(val[i]);
687 }
688 } else {
689 writeInt(-1);
690 }
691 }
692
693 public final long[] createLongArray() {
694 int N = readInt();
695 // >>3 because stored longs are 64 bits
696 if (N >= 0 && N <= (dataAvail() >> 3)) {
697 long[] val = new long[N];
698 for (int i=0; i<N; i++) {
699 val[i] = readLong();
700 }
701 return val;
702 } else {
703 return null;
704 }
705 }
706
707 public final void readLongArray(long[] val) {
708 int N = readInt();
709 if (N == val.length) {
710 for (int i=0; i<N; i++) {
711 val[i] = readLong();
712 }
713 } else {
714 throw new RuntimeException("bad array lengths");
715 }
716 }
717
718 public final void writeFloatArray(float[] val) {
719 if (val != null) {
720 int N = val.length;
721 writeInt(N);
722 for (int i=0; i<N; i++) {
723 writeFloat(val[i]);
724 }
725 } else {
726 writeInt(-1);
727 }
728 }
729
730 public final float[] createFloatArray() {
731 int N = readInt();
732 // >>2 because stored floats are 4 bytes
733 if (N >= 0 && N <= (dataAvail() >> 2)) {
734 float[] val = new float[N];
735 for (int i=0; i<N; i++) {
736 val[i] = readFloat();
737 }
738 return val;
739 } else {
740 return null;
741 }
742 }
743
744 public final void readFloatArray(float[] val) {
745 int N = readInt();
746 if (N == val.length) {
747 for (int i=0; i<N; i++) {
748 val[i] = readFloat();
749 }
750 } else {
751 throw new RuntimeException("bad array lengths");
752 }
753 }
754
755 public final void writeDoubleArray(double[] val) {
756 if (val != null) {
757 int N = val.length;
758 writeInt(N);
759 for (int i=0; i<N; i++) {
760 writeDouble(val[i]);
761 }
762 } else {
763 writeInt(-1);
764 }
765 }
766
767 public final double[] createDoubleArray() {
768 int N = readInt();
769 // >>3 because stored doubles are 8 bytes
770 if (N >= 0 && N <= (dataAvail() >> 3)) {
771 double[] val = new double[N];
772 for (int i=0; i<N; i++) {
773 val[i] = readDouble();
774 }
775 return val;
776 } else {
777 return null;
778 }
779 }
780
781 public final void readDoubleArray(double[] val) {
782 int N = readInt();
783 if (N == val.length) {
784 for (int i=0; i<N; i++) {
785 val[i] = readDouble();
786 }
787 } else {
788 throw new RuntimeException("bad array lengths");
789 }
790 }
791
792 public final void writeStringArray(String[] val) {
793 if (val != null) {
794 int N = val.length;
795 writeInt(N);
796 for (int i=0; i<N; i++) {
797 writeString(val[i]);
798 }
799 } else {
800 writeInt(-1);
801 }
802 }
803
804 public final String[] createStringArray() {
805 int N = readInt();
806 if (N >= 0) {
807 String[] val = new String[N];
808 for (int i=0; i<N; i++) {
809 val[i] = readString();
810 }
811 return val;
812 } else {
813 return null;
814 }
815 }
816
817 public final void readStringArray(String[] val) {
818 int N = readInt();
819 if (N == val.length) {
820 for (int i=0; i<N; i++) {
821 val[i] = readString();
822 }
823 } else {
824 throw new RuntimeException("bad array lengths");
825 }
826 }
827
828 public final void writeBinderArray(IBinder[] val) {
829 if (val != null) {
830 int N = val.length;
831 writeInt(N);
832 for (int i=0; i<N; i++) {
833 writeStrongBinder(val[i]);
834 }
835 } else {
836 writeInt(-1);
837 }
838 }
839
Bjorn Bringert08bbffb2010-02-25 11:16:22 +0000840 /**
841 * @hide
842 */
843 public final void writeCharSequenceArray(CharSequence[] val) {
844 if (val != null) {
845 int N = val.length;
846 writeInt(N);
847 for (int i=0; i<N; i++) {
848 writeCharSequence(val[i]);
849 }
850 } else {
851 writeInt(-1);
852 }
853 }
854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 public final IBinder[] createBinderArray() {
856 int N = readInt();
857 if (N >= 0) {
858 IBinder[] val = new IBinder[N];
859 for (int i=0; i<N; i++) {
860 val[i] = readStrongBinder();
861 }
862 return val;
863 } else {
864 return null;
865 }
866 }
867
868 public final void readBinderArray(IBinder[] val) {
869 int N = readInt();
870 if (N == val.length) {
871 for (int i=0; i<N; i++) {
872 val[i] = readStrongBinder();
873 }
874 } else {
875 throw new RuntimeException("bad array lengths");
876 }
877 }
878
879 /**
880 * Flatten a List containing a particular object type into the parcel, at
881 * the current dataPosition() and growing dataCapacity() if needed. The
882 * type of the objects in the list must be one that implements Parcelable.
883 * Unlike the generic writeList() method, however, only the raw data of the
884 * objects is written and not their type, so you must use the corresponding
885 * readTypedList() to unmarshall them.
886 *
887 * @param val The list of objects to be written.
888 *
889 * @see #createTypedArrayList
890 * @see #readTypedList
891 * @see Parcelable
892 */
893 public final <T extends Parcelable> void writeTypedList(List<T> val) {
894 if (val == null) {
895 writeInt(-1);
896 return;
897 }
898 int N = val.size();
899 int i=0;
900 writeInt(N);
901 while (i < N) {
902 T item = val.get(i);
903 if (item != null) {
904 writeInt(1);
905 item.writeToParcel(this, 0);
906 } else {
907 writeInt(0);
908 }
909 i++;
910 }
911 }
912
913 /**
914 * Flatten a List containing String objects into the parcel, at
915 * the current dataPosition() and growing dataCapacity() if needed. They
916 * can later be retrieved with {@link #createStringArrayList} or
917 * {@link #readStringList}.
918 *
919 * @param val The list of strings to be written.
920 *
921 * @see #createStringArrayList
922 * @see #readStringList
923 */
924 public final void writeStringList(List<String> val) {
925 if (val == null) {
926 writeInt(-1);
927 return;
928 }
929 int N = val.size();
930 int i=0;
931 writeInt(N);
932 while (i < N) {
933 writeString(val.get(i));
934 i++;
935 }
936 }
937
938 /**
939 * Flatten a List containing IBinder objects into the parcel, at
940 * the current dataPosition() and growing dataCapacity() if needed. They
941 * can later be retrieved with {@link #createBinderArrayList} or
942 * {@link #readBinderList}.
943 *
944 * @param val The list of strings to be written.
945 *
946 * @see #createBinderArrayList
947 * @see #readBinderList
948 */
949 public final void writeBinderList(List<IBinder> val) {
950 if (val == null) {
951 writeInt(-1);
952 return;
953 }
954 int N = val.size();
955 int i=0;
956 writeInt(N);
957 while (i < N) {
958 writeStrongBinder(val.get(i));
959 i++;
960 }
961 }
962
963 /**
964 * Flatten a heterogeneous array containing a particular object type into
965 * the parcel, at
966 * the current dataPosition() and growing dataCapacity() if needed. The
967 * type of the objects in the array must be one that implements Parcelable.
968 * Unlike the {@link #writeParcelableArray} method, however, only the
969 * raw data of the objects is written and not their type, so you must use
970 * {@link #readTypedArray} with the correct corresponding
971 * {@link Parcelable.Creator} implementation to unmarshall them.
972 *
973 * @param val The array of objects to be written.
974 * @param parcelableFlags Contextual flags as per
975 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
976 *
977 * @see #readTypedArray
978 * @see #writeParcelableArray
979 * @see Parcelable.Creator
980 */
981 public final <T extends Parcelable> void writeTypedArray(T[] val,
982 int parcelableFlags) {
983 if (val != null) {
984 int N = val.length;
985 writeInt(N);
986 for (int i=0; i<N; i++) {
987 T item = val[i];
988 if (item != null) {
989 writeInt(1);
990 item.writeToParcel(this, parcelableFlags);
991 } else {
992 writeInt(0);
993 }
994 }
995 } else {
996 writeInt(-1);
997 }
998 }
999
1000 /**
1001 * Flatten a generic object in to a parcel. The given Object value may
1002 * currently be one of the following types:
1003 *
1004 * <ul>
1005 * <li> null
1006 * <li> String
1007 * <li> Byte
1008 * <li> Short
1009 * <li> Integer
1010 * <li> Long
1011 * <li> Float
1012 * <li> Double
1013 * <li> Boolean
1014 * <li> String[]
1015 * <li> boolean[]
1016 * <li> byte[]
1017 * <li> int[]
1018 * <li> long[]
1019 * <li> Object[] (supporting objects of the same type defined here).
1020 * <li> {@link Bundle}
1021 * <li> Map (as supported by {@link #writeMap}).
1022 * <li> Any object that implements the {@link Parcelable} protocol.
1023 * <li> Parcelable[]
1024 * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}).
1025 * <li> List (as supported by {@link #writeList}).
1026 * <li> {@link SparseArray} (as supported by {@link #writeSparseArray}).
1027 * <li> {@link IBinder}
1028 * <li> Any object that implements Serializable (but see
1029 * {@link #writeSerializable} for caveats). Note that all of the
1030 * previous types have relatively efficient implementations for
1031 * writing to a Parcel; having to rely on the generic serialization
1032 * approach is much less efficient and should be avoided whenever
1033 * possible.
1034 * </ul>
1035 */
1036 public final void writeValue(Object v) {
1037 if (v == null) {
1038 writeInt(VAL_NULL);
1039 } else if (v instanceof String) {
1040 writeInt(VAL_STRING);
1041 writeString((String) v);
1042 } else if (v instanceof Integer) {
1043 writeInt(VAL_INTEGER);
1044 writeInt((Integer) v);
1045 } else if (v instanceof Map) {
1046 writeInt(VAL_MAP);
1047 writeMap((Map) v);
1048 } else if (v instanceof Bundle) {
1049 // Must be before Parcelable
1050 writeInt(VAL_BUNDLE);
1051 writeBundle((Bundle) v);
1052 } else if (v instanceof Parcelable) {
1053 writeInt(VAL_PARCELABLE);
1054 writeParcelable((Parcelable) v, 0);
1055 } else if (v instanceof Short) {
1056 writeInt(VAL_SHORT);
1057 writeInt(((Short) v).intValue());
1058 } else if (v instanceof Long) {
1059 writeInt(VAL_LONG);
1060 writeLong((Long) v);
1061 } else if (v instanceof Float) {
1062 writeInt(VAL_FLOAT);
1063 writeFloat((Float) v);
1064 } else if (v instanceof Double) {
1065 writeInt(VAL_DOUBLE);
1066 writeDouble((Double) v);
1067 } else if (v instanceof Boolean) {
1068 writeInt(VAL_BOOLEAN);
1069 writeInt((Boolean) v ? 1 : 0);
1070 } else if (v instanceof CharSequence) {
1071 // Must be after String
1072 writeInt(VAL_CHARSEQUENCE);
Bjorn Bringert08bbffb2010-02-25 11:16:22 +00001073 writeCharSequence((CharSequence) v);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 } else if (v instanceof List) {
1075 writeInt(VAL_LIST);
1076 writeList((List) v);
1077 } else if (v instanceof SparseArray) {
1078 writeInt(VAL_SPARSEARRAY);
1079 writeSparseArray((SparseArray) v);
1080 } else if (v instanceof boolean[]) {
1081 writeInt(VAL_BOOLEANARRAY);
1082 writeBooleanArray((boolean[]) v);
1083 } else if (v instanceof byte[]) {
1084 writeInt(VAL_BYTEARRAY);
1085 writeByteArray((byte[]) v);
1086 } else if (v instanceof String[]) {
1087 writeInt(VAL_STRINGARRAY);
1088 writeStringArray((String[]) v);
Bjorn Bringert08bbffb2010-02-25 11:16:22 +00001089 } else if (v instanceof CharSequence[]) {
1090 // Must be after String[] and before Object[]
1091 writeInt(VAL_CHARSEQUENCEARRAY);
1092 writeCharSequenceArray((CharSequence[]) v);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 } else if (v instanceof IBinder) {
1094 writeInt(VAL_IBINDER);
1095 writeStrongBinder((IBinder) v);
1096 } else if (v instanceof Parcelable[]) {
1097 writeInt(VAL_PARCELABLEARRAY);
1098 writeParcelableArray((Parcelable[]) v, 0);
1099 } else if (v instanceof Object[]) {
1100 writeInt(VAL_OBJECTARRAY);
1101 writeArray((Object[]) v);
1102 } else if (v instanceof int[]) {
1103 writeInt(VAL_INTARRAY);
1104 writeIntArray((int[]) v);
1105 } else if (v instanceof long[]) {
1106 writeInt(VAL_LONGARRAY);
1107 writeLongArray((long[]) v);
1108 } else if (v instanceof Byte) {
1109 writeInt(VAL_BYTE);
1110 writeInt((Byte) v);
1111 } else if (v instanceof Serializable) {
1112 // Must be last
1113 writeInt(VAL_SERIALIZABLE);
1114 writeSerializable((Serializable) v);
1115 } else {
1116 throw new RuntimeException("Parcel: unable to marshal value " + v);
1117 }
1118 }
1119
1120 /**
1121 * Flatten the name of the class of the Parcelable and its contents
1122 * into the parcel.
1123 *
1124 * @param p The Parcelable object to be written.
1125 * @param parcelableFlags Contextual flags as per
1126 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1127 */
1128 public final void writeParcelable(Parcelable p, int parcelableFlags) {
1129 if (p == null) {
1130 writeString(null);
1131 return;
1132 }
1133 String name = p.getClass().getName();
1134 writeString(name);
1135 p.writeToParcel(this, parcelableFlags);
1136 }
1137
1138 /**
1139 * Write a generic serializable object in to a Parcel. It is strongly
1140 * recommended that this method be avoided, since the serialization
1141 * overhead is extremely large, and this approach will be much slower than
1142 * using the other approaches to writing data in to a Parcel.
1143 */
1144 public final void writeSerializable(Serializable s) {
1145 if (s == null) {
1146 writeString(null);
1147 return;
1148 }
1149 String name = s.getClass().getName();
1150 writeString(name);
1151
1152 ByteArrayOutputStream baos = new ByteArrayOutputStream();
1153 try {
1154 ObjectOutputStream oos = new ObjectOutputStream(baos);
1155 oos.writeObject(s);
1156 oos.close();
1157
1158 writeByteArray(baos.toByteArray());
1159 } catch (IOException ioe) {
1160 throw new RuntimeException("Parcelable encountered " +
1161 "IOException writing serializable object (name = " + name +
1162 ")", ioe);
1163 }
1164 }
1165
1166 /**
1167 * Special function for writing an exception result at the header of
1168 * a parcel, to be used when returning an exception from a transaction.
1169 * Note that this currently only supports a few exception types; any other
1170 * exception will be re-thrown by this function as a RuntimeException
1171 * (to be caught by the system's last-resort exception handling when
1172 * dispatching a transaction).
1173 *
1174 * <p>The supported exception types are:
1175 * <ul>
1176 * <li>{@link BadParcelableException}
1177 * <li>{@link IllegalArgumentException}
1178 * <li>{@link IllegalStateException}
1179 * <li>{@link NullPointerException}
1180 * <li>{@link SecurityException}
1181 * </ul>
1182 *
1183 * @param e The Exception to be written.
1184 *
1185 * @see #writeNoException
1186 * @see #readException
1187 */
1188 public final void writeException(Exception e) {
1189 int code = 0;
1190 if (e instanceof SecurityException) {
1191 code = EX_SECURITY;
1192 } else if (e instanceof BadParcelableException) {
1193 code = EX_BAD_PARCELABLE;
1194 } else if (e instanceof IllegalArgumentException) {
1195 code = EX_ILLEGAL_ARGUMENT;
1196 } else if (e instanceof NullPointerException) {
1197 code = EX_NULL_POINTER;
1198 } else if (e instanceof IllegalStateException) {
1199 code = EX_ILLEGAL_STATE;
1200 }
1201 writeInt(code);
1202 if (code == 0) {
1203 if (e instanceof RuntimeException) {
1204 throw (RuntimeException) e;
1205 }
1206 throw new RuntimeException(e);
1207 }
1208 writeString(e.getMessage());
1209 }
1210
1211 /**
1212 * Special function for writing information at the front of the Parcel
1213 * indicating that no exception occurred.
1214 *
1215 * @see #writeException
1216 * @see #readException
1217 */
1218 public final void writeNoException() {
1219 writeInt(0);
1220 }
1221
1222 /**
1223 * Special function for reading an exception result from the header of
1224 * a parcel, to be used after receiving the result of a transaction. This
1225 * will throw the exception for you if it had been written to the Parcel,
1226 * otherwise return and let you read the normal result data from the Parcel.
1227 *
1228 * @see #writeException
1229 * @see #writeNoException
1230 */
1231 public final void readException() {
1232 int code = readInt();
1233 if (code == 0) return;
1234 String msg = readString();
1235 readException(code, msg);
1236 }
1237
1238 /**
1239 * Use this function for customized exception handling.
1240 * customized method call this method for all unknown case
1241 * @param code exception code
1242 * @param msg exception message
1243 */
1244 public final void readException(int code, String msg) {
1245 switch (code) {
1246 case EX_SECURITY:
1247 throw new SecurityException(msg);
1248 case EX_BAD_PARCELABLE:
1249 throw new BadParcelableException(msg);
1250 case EX_ILLEGAL_ARGUMENT:
1251 throw new IllegalArgumentException(msg);
1252 case EX_NULL_POINTER:
1253 throw new NullPointerException(msg);
1254 case EX_ILLEGAL_STATE:
1255 throw new IllegalStateException(msg);
1256 }
1257 throw new RuntimeException("Unknown exception code: " + code
1258 + " msg " + msg);
1259 }
1260
1261 /**
1262 * Read an integer value from the parcel at the current dataPosition().
1263 */
1264 public final native int readInt();
1265
1266 /**
1267 * Read a long integer value from the parcel at the current dataPosition().
1268 */
1269 public final native long readLong();
1270
1271 /**
1272 * Read a floating point value from the parcel at the current
1273 * dataPosition().
1274 */
1275 public final native float readFloat();
1276
1277 /**
1278 * Read a double precision floating point value from the parcel at the
1279 * current dataPosition().
1280 */
1281 public final native double readDouble();
1282
1283 /**
1284 * Read a string value from the parcel at the current dataPosition().
1285 */
1286 public final native String readString();
1287
1288 /**
Bjorn Bringert08bbffb2010-02-25 11:16:22 +00001289 * Read a CharSequence value from the parcel at the current dataPosition().
1290 * @hide
1291 */
1292 public final CharSequence readCharSequence() {
1293 return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this);
1294 }
1295
1296 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001297 * Read an object from the parcel at the current dataPosition().
1298 */
1299 public final native IBinder readStrongBinder();
1300
1301 /**
1302 * Read a FileDescriptor from the parcel at the current dataPosition().
1303 */
1304 public final ParcelFileDescriptor readFileDescriptor() {
1305 FileDescriptor fd = internalReadFileDescriptor();
1306 return fd != null ? new ParcelFileDescriptor(fd) : null;
1307 }
1308
1309 private native FileDescriptor internalReadFileDescriptor();
1310 /*package*/ static native FileDescriptor openFileDescriptor(String file,
1311 int mode) throws FileNotFoundException;
1312 /*package*/ static native void closeFileDescriptor(FileDescriptor desc)
1313 throws IOException;
1314
1315 /**
1316 * Read a byte value from the parcel at the current dataPosition().
1317 */
1318 public final byte readByte() {
1319 return (byte)(readInt() & 0xff);
1320 }
1321
1322 /**
1323 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
1324 * been written with {@link #writeBundle}. Read into an existing Map object
1325 * from the parcel at the current dataPosition().
1326 */
1327 public final void readMap(Map outVal, ClassLoader loader) {
1328 int N = readInt();
1329 readMapInternal(outVal, N, loader);
1330 }
1331
1332 /**
1333 * Read into an existing List object from the parcel at the current
1334 * dataPosition(), using the given class loader to load any enclosed
1335 * Parcelables. If it is null, the default class loader is used.
1336 */
1337 public final void readList(List outVal, ClassLoader loader) {
1338 int N = readInt();
1339 readListInternal(outVal, N, loader);
1340 }
1341
1342 /**
1343 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have
1344 * been written with {@link #writeBundle}. Read and return a new HashMap
1345 * object from the parcel at the current dataPosition(), using the given
1346 * class loader to load any enclosed Parcelables. Returns null if
1347 * the previously written map object was null.
1348 */
1349 public final HashMap readHashMap(ClassLoader loader)
1350 {
1351 int N = readInt();
1352 if (N < 0) {
1353 return null;
1354 }
1355 HashMap m = new HashMap(N);
1356 readMapInternal(m, N, loader);
1357 return m;
1358 }
1359
1360 /**
1361 * Read and return a new Bundle object from the parcel at the current
1362 * dataPosition(). Returns null if the previously written Bundle object was
1363 * null.
1364 */
1365 public final Bundle readBundle() {
1366 return readBundle(null);
1367 }
1368
1369 /**
1370 * Read and return a new Bundle object from the parcel at the current
1371 * dataPosition(), using the given class loader to initialize the class
1372 * loader of the Bundle for later retrieval of Parcelable objects.
1373 * Returns null if the previously written Bundle object was null.
1374 */
1375 public final Bundle readBundle(ClassLoader loader) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 int length = readInt();
1377 if (length < 0) {
1378 return null;
1379 }
Dianne Hackborn6aff9052009-05-22 13:20:23 -07001380
1381 final Bundle bundle = new Bundle(this, length);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 if (loader != null) {
1383 bundle.setClassLoader(loader);
1384 }
1385 return bundle;
1386 }
1387
1388 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 * Read and return a byte[] object from the parcel.
1390 */
1391 public final native byte[] createByteArray();
1392
1393 /**
1394 * Read a byte[] object from the parcel and copy it into the
1395 * given byte array.
1396 */
1397 public final void readByteArray(byte[] val) {
1398 // TODO: make this a native method to avoid the extra copy.
1399 byte[] ba = createByteArray();
1400 if (ba.length == val.length) {
1401 System.arraycopy(ba, 0, val, 0, ba.length);
1402 } else {
1403 throw new RuntimeException("bad array lengths");
1404 }
1405 }
1406
1407 /**
1408 * Read and return a String[] object from the parcel.
1409 * {@hide}
1410 */
1411 public final String[] readStringArray() {
1412 String[] array = null;
1413
1414 int length = readInt();
1415 if (length >= 0)
1416 {
1417 array = new String[length];
1418
1419 for (int i = 0 ; i < length ; i++)
1420 {
1421 array[i] = readString();
1422 }
1423 }
1424
1425 return array;
1426 }
1427
1428 /**
Bjorn Bringert08bbffb2010-02-25 11:16:22 +00001429 * Read and return a CharSequence[] object from the parcel.
1430 * {@hide}
1431 */
1432 public final CharSequence[] readCharSequenceArray() {
1433 CharSequence[] array = null;
1434
1435 int length = readInt();
1436 if (length >= 0)
1437 {
1438 array = new CharSequence[length];
1439
1440 for (int i = 0 ; i < length ; i++)
1441 {
1442 array[i] = readCharSequence();
1443 }
1444 }
1445
1446 return array;
1447 }
1448
1449 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 * Read and return a new ArrayList object from the parcel at the current
1451 * dataPosition(). Returns null if the previously written list object was
1452 * null. The given class loader will be used to load any enclosed
1453 * Parcelables.
1454 */
1455 public final ArrayList readArrayList(ClassLoader loader) {
1456 int N = readInt();
1457 if (N < 0) {
1458 return null;
1459 }
1460 ArrayList l = new ArrayList(N);
1461 readListInternal(l, N, loader);
1462 return l;
1463 }
1464
1465 /**
1466 * Read and return a new Object array from the parcel at the current
1467 * dataPosition(). Returns null if the previously written array was
1468 * null. The given class loader will be used to load any enclosed
1469 * Parcelables.
1470 */
1471 public final Object[] readArray(ClassLoader loader) {
1472 int N = readInt();
1473 if (N < 0) {
1474 return null;
1475 }
1476 Object[] l = new Object[N];
1477 readArrayInternal(l, N, loader);
1478 return l;
1479 }
1480
1481 /**
1482 * Read and return a new SparseArray object from the parcel at the current
1483 * dataPosition(). Returns null if the previously written list object was
1484 * null. The given class loader will be used to load any enclosed
1485 * Parcelables.
1486 */
1487 public final SparseArray readSparseArray(ClassLoader loader) {
1488 int N = readInt();
1489 if (N < 0) {
1490 return null;
1491 }
1492 SparseArray sa = new SparseArray(N);
1493 readSparseArrayInternal(sa, N, loader);
1494 return sa;
1495 }
1496
1497 /**
1498 * Read and return a new SparseBooleanArray object from the parcel at the current
1499 * dataPosition(). Returns null if the previously written list object was
1500 * null.
1501 */
1502 public final SparseBooleanArray readSparseBooleanArray() {
1503 int N = readInt();
1504 if (N < 0) {
1505 return null;
1506 }
1507 SparseBooleanArray sa = new SparseBooleanArray(N);
1508 readSparseBooleanArrayInternal(sa, N);
1509 return sa;
1510 }
1511
1512 /**
1513 * Read and return a new ArrayList containing a particular object type from
1514 * the parcel that was written with {@link #writeTypedList} at the
1515 * current dataPosition(). Returns null if the
1516 * previously written list object was null. The list <em>must</em> have
1517 * previously been written via {@link #writeTypedList} with the same object
1518 * type.
1519 *
1520 * @return A newly created ArrayList containing objects with the same data
1521 * as those that were previously written.
1522 *
1523 * @see #writeTypedList
1524 */
1525 public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) {
1526 int N = readInt();
1527 if (N < 0) {
1528 return null;
1529 }
1530 ArrayList<T> l = new ArrayList<T>(N);
1531 while (N > 0) {
1532 if (readInt() != 0) {
1533 l.add(c.createFromParcel(this));
1534 } else {
1535 l.add(null);
1536 }
1537 N--;
1538 }
1539 return l;
1540 }
1541
1542 /**
1543 * Read into the given List items containing a particular object type
1544 * that were written with {@link #writeTypedList} at the
1545 * current dataPosition(). The list <em>must</em> have
1546 * previously been written via {@link #writeTypedList} with the same object
1547 * type.
1548 *
1549 * @return A newly created ArrayList containing objects with the same data
1550 * as those that were previously written.
1551 *
1552 * @see #writeTypedList
1553 */
1554 public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) {
1555 int M = list.size();
1556 int N = readInt();
1557 int i = 0;
1558 for (; i < M && i < N; i++) {
1559 if (readInt() != 0) {
1560 list.set(i, c.createFromParcel(this));
1561 } else {
1562 list.set(i, null);
1563 }
1564 }
1565 for (; i<N; i++) {
1566 if (readInt() != 0) {
1567 list.add(c.createFromParcel(this));
1568 } else {
1569 list.add(null);
1570 }
1571 }
1572 for (; i<M; i++) {
1573 list.remove(N);
1574 }
1575 }
1576
1577 /**
1578 * Read and return a new ArrayList containing String objects from
1579 * the parcel that was written with {@link #writeStringList} at the
1580 * current dataPosition(). Returns null if the
1581 * previously written list object was null.
1582 *
1583 * @return A newly created ArrayList containing strings with the same data
1584 * as those that were previously written.
1585 *
1586 * @see #writeStringList
1587 */
1588 public final ArrayList<String> createStringArrayList() {
1589 int N = readInt();
1590 if (N < 0) {
1591 return null;
1592 }
1593 ArrayList<String> l = new ArrayList<String>(N);
1594 while (N > 0) {
1595 l.add(readString());
1596 N--;
1597 }
1598 return l;
1599 }
1600
1601 /**
1602 * Read and return a new ArrayList containing IBinder objects from
1603 * the parcel that was written with {@link #writeBinderList} at the
1604 * current dataPosition(). Returns null if the
1605 * previously written list object was null.
1606 *
1607 * @return A newly created ArrayList containing strings with the same data
1608 * as those that were previously written.
1609 *
1610 * @see #writeBinderList
1611 */
1612 public final ArrayList<IBinder> createBinderArrayList() {
1613 int N = readInt();
1614 if (N < 0) {
1615 return null;
1616 }
1617 ArrayList<IBinder> l = new ArrayList<IBinder>(N);
1618 while (N > 0) {
1619 l.add(readStrongBinder());
1620 N--;
1621 }
1622 return l;
1623 }
1624
1625 /**
1626 * Read into the given List items String objects that were written with
1627 * {@link #writeStringList} at the current dataPosition().
1628 *
1629 * @return A newly created ArrayList containing strings with the same data
1630 * as those that were previously written.
1631 *
1632 * @see #writeStringList
1633 */
1634 public final void readStringList(List<String> list) {
1635 int M = list.size();
1636 int N = readInt();
1637 int i = 0;
1638 for (; i < M && i < N; i++) {
1639 list.set(i, readString());
1640 }
1641 for (; i<N; i++) {
1642 list.add(readString());
1643 }
1644 for (; i<M; i++) {
1645 list.remove(N);
1646 }
1647 }
1648
1649 /**
1650 * Read into the given List items IBinder objects that were written with
1651 * {@link #writeBinderList} at the current dataPosition().
1652 *
1653 * @return A newly created ArrayList containing strings with the same data
1654 * as those that were previously written.
1655 *
1656 * @see #writeBinderList
1657 */
1658 public final void readBinderList(List<IBinder> list) {
1659 int M = list.size();
1660 int N = readInt();
1661 int i = 0;
1662 for (; i < M && i < N; i++) {
1663 list.set(i, readStrongBinder());
1664 }
1665 for (; i<N; i++) {
1666 list.add(readStrongBinder());
1667 }
1668 for (; i<M; i++) {
1669 list.remove(N);
1670 }
1671 }
1672
1673 /**
1674 * Read and return a new array containing a particular object type from
1675 * the parcel at the current dataPosition(). Returns null if the
1676 * previously written array was null. The array <em>must</em> have
1677 * previously been written via {@link #writeTypedArray} with the same
1678 * object type.
1679 *
1680 * @return A newly created array containing objects with the same data
1681 * as those that were previously written.
1682 *
1683 * @see #writeTypedArray
1684 */
1685 public final <T> T[] createTypedArray(Parcelable.Creator<T> c) {
1686 int N = readInt();
1687 if (N < 0) {
1688 return null;
1689 }
1690 T[] l = c.newArray(N);
1691 for (int i=0; i<N; i++) {
1692 if (readInt() != 0) {
1693 l[i] = c.createFromParcel(this);
1694 }
1695 }
1696 return l;
1697 }
1698
1699 public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) {
1700 int N = readInt();
1701 if (N == val.length) {
1702 for (int i=0; i<N; i++) {
1703 if (readInt() != 0) {
1704 val[i] = c.createFromParcel(this);
1705 } else {
1706 val[i] = null;
1707 }
1708 }
1709 } else {
1710 throw new RuntimeException("bad array lengths");
1711 }
1712 }
1713
1714 /**
1715 * @deprecated
1716 * @hide
1717 */
1718 @Deprecated
1719 public final <T> T[] readTypedArray(Parcelable.Creator<T> c) {
1720 return createTypedArray(c);
1721 }
1722
1723 /**
1724 * Write a heterogeneous array of Parcelable objects into the Parcel.
1725 * Each object in the array is written along with its class name, so
1726 * that the correct class can later be instantiated. As a result, this
1727 * has significantly more overhead than {@link #writeTypedArray}, but will
1728 * correctly handle an array containing more than one type of object.
1729 *
1730 * @param value The array of objects to be written.
1731 * @param parcelableFlags Contextual flags as per
1732 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}.
1733 *
1734 * @see #writeTypedArray
1735 */
1736 public final <T extends Parcelable> void writeParcelableArray(T[] value,
1737 int parcelableFlags) {
1738 if (value != null) {
1739 int N = value.length;
1740 writeInt(N);
1741 for (int i=0; i<N; i++) {
1742 writeParcelable(value[i], parcelableFlags);
1743 }
1744 } else {
1745 writeInt(-1);
1746 }
1747 }
1748
1749 /**
1750 * Read a typed object from a parcel. The given class loader will be
1751 * used to load any enclosed Parcelables. If it is null, the default class
1752 * loader will be used.
1753 */
1754 public final Object readValue(ClassLoader loader) {
1755 int type = readInt();
1756
1757 switch (type) {
1758 case VAL_NULL:
1759 return null;
1760
1761 case VAL_STRING:
1762 return readString();
1763
1764 case VAL_INTEGER:
1765 return readInt();
1766
1767 case VAL_MAP:
1768 return readHashMap(loader);
1769
1770 case VAL_PARCELABLE:
1771 return readParcelable(loader);
1772
1773 case VAL_SHORT:
1774 return (short) readInt();
1775
1776 case VAL_LONG:
1777 return readLong();
1778
1779 case VAL_FLOAT:
1780 return readFloat();
1781
1782 case VAL_DOUBLE:
1783 return readDouble();
1784
1785 case VAL_BOOLEAN:
1786 return readInt() == 1;
1787
1788 case VAL_CHARSEQUENCE:
Bjorn Bringert08bbffb2010-02-25 11:16:22 +00001789 return readCharSequence();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790
1791 case VAL_LIST:
1792 return readArrayList(loader);
1793
1794 case VAL_BOOLEANARRAY:
1795 return createBooleanArray();
1796
1797 case VAL_BYTEARRAY:
1798 return createByteArray();
1799
1800 case VAL_STRINGARRAY:
1801 return readStringArray();
1802
Bjorn Bringert08bbffb2010-02-25 11:16:22 +00001803 case VAL_CHARSEQUENCEARRAY:
1804 return readCharSequenceArray();
1805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 case VAL_IBINDER:
1807 return readStrongBinder();
1808
1809 case VAL_OBJECTARRAY:
1810 return readArray(loader);
1811
1812 case VAL_INTARRAY:
1813 return createIntArray();
1814
1815 case VAL_LONGARRAY:
1816 return createLongArray();
1817
1818 case VAL_BYTE:
1819 return readByte();
1820
1821 case VAL_SERIALIZABLE:
1822 return readSerializable();
1823
1824 case VAL_PARCELABLEARRAY:
1825 return readParcelableArray(loader);
1826
1827 case VAL_SPARSEARRAY:
1828 return readSparseArray(loader);
1829
1830 case VAL_SPARSEBOOLEANARRAY:
1831 return readSparseBooleanArray();
1832
1833 case VAL_BUNDLE:
1834 return readBundle(loader); // loading will be deferred
1835
1836 default:
1837 int off = dataPosition() - 4;
1838 throw new RuntimeException(
1839 "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off);
1840 }
1841 }
1842
1843 /**
1844 * Read and return a new Parcelable from the parcel. The given class loader
1845 * will be used to load any enclosed Parcelables. If it is null, the default
1846 * class loader will be used.
1847 * @param loader A ClassLoader from which to instantiate the Parcelable
1848 * object, or null for the default class loader.
1849 * @return Returns the newly created Parcelable, or null if a null
1850 * object has been written.
1851 * @throws BadParcelableException Throws BadParcelableException if there
1852 * was an error trying to instantiate the Parcelable.
1853 */
1854 public final <T extends Parcelable> T readParcelable(ClassLoader loader) {
1855 String name = readString();
1856 if (name == null) {
1857 return null;
1858 }
1859 Parcelable.Creator<T> creator;
1860 synchronized (mCreators) {
1861 HashMap<String,Parcelable.Creator> map = mCreators.get(loader);
1862 if (map == null) {
1863 map = new HashMap<String,Parcelable.Creator>();
1864 mCreators.put(loader, map);
1865 }
1866 creator = map.get(name);
1867 if (creator == null) {
1868 try {
1869 Class c = loader == null ?
1870 Class.forName(name) : Class.forName(name, true, loader);
1871 Field f = c.getField("CREATOR");
1872 creator = (Parcelable.Creator)f.get(null);
1873 }
1874 catch (IllegalAccessException e) {
1875 Log.e("Parcel", "Class not found when unmarshalling: "
1876 + name + ", e: " + e);
1877 throw new BadParcelableException(
1878 "IllegalAccessException when unmarshalling: " + name);
1879 }
1880 catch (ClassNotFoundException e) {
1881 Log.e("Parcel", "Class not found when unmarshalling: "
1882 + name + ", e: " + e);
1883 throw new BadParcelableException(
1884 "ClassNotFoundException when unmarshalling: " + name);
1885 }
1886 catch (ClassCastException e) {
1887 throw new BadParcelableException("Parcelable protocol requires a "
1888 + "Parcelable.Creator object called "
1889 + " CREATOR on class " + name);
1890 }
1891 catch (NoSuchFieldException e) {
1892 throw new BadParcelableException("Parcelable protocol requires a "
1893 + "Parcelable.Creator object called "
1894 + " CREATOR on class " + name);
1895 }
1896 if (creator == null) {
1897 throw new BadParcelableException("Parcelable protocol requires a "
1898 + "Parcelable.Creator object called "
1899 + " CREATOR on class " + name);
1900 }
1901
1902 map.put(name, creator);
1903 }
1904 }
1905
1906 return creator.createFromParcel(this);
1907 }
1908
1909 /**
1910 * Read and return a new Parcelable array from the parcel.
1911 * The given class loader will be used to load any enclosed
1912 * Parcelables.
1913 * @return the Parcelable array, or null if the array is null
1914 */
1915 public final Parcelable[] readParcelableArray(ClassLoader loader) {
1916 int N = readInt();
1917 if (N < 0) {
1918 return null;
1919 }
1920 Parcelable[] p = new Parcelable[N];
1921 for (int i = 0; i < N; i++) {
1922 p[i] = (Parcelable) readParcelable(loader);
1923 }
1924 return p;
1925 }
1926
1927 /**
1928 * Read and return a new Serializable object from the parcel.
1929 * @return the Serializable object, or null if the Serializable name
1930 * wasn't found in the parcel.
1931 */
1932 public final Serializable readSerializable() {
1933 String name = readString();
1934 if (name == null) {
1935 // For some reason we were unable to read the name of the Serializable (either there
1936 // is nothing left in the Parcel to read, or the next value wasn't a String), so
1937 // return null, which indicates that the name wasn't found in the parcel.
1938 return null;
1939 }
1940
1941 byte[] serializedData = createByteArray();
1942 ByteArrayInputStream bais = new ByteArrayInputStream(serializedData);
1943 try {
1944 ObjectInputStream ois = new ObjectInputStream(bais);
1945 return (Serializable) ois.readObject();
1946 } catch (IOException ioe) {
1947 throw new RuntimeException("Parcelable encountered " +
1948 "IOException reading a Serializable object (name = " + name +
1949 ")", ioe);
1950 } catch (ClassNotFoundException cnfe) {
1951 throw new RuntimeException("Parcelable encountered" +
1952 "ClassNotFoundException reading a Serializable object (name = "
1953 + name + ")", cnfe);
1954 }
1955 }
1956
1957 // Cache of previously looked up CREATOR.createFromParcel() methods for
1958 // particular classes. Keys are the names of the classes, values are
1959 // Method objects.
1960 private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator>>
1961 mCreators = new HashMap<ClassLoader,HashMap<String,Parcelable.Creator>>();
1962
1963 static protected final Parcel obtain(int obj) {
1964 final Parcel[] pool = sHolderPool;
1965 synchronized (pool) {
1966 Parcel p;
1967 for (int i=0; i<POOL_SIZE; i++) {
1968 p = pool[i];
1969 if (p != null) {
1970 pool[i] = null;
1971 if (DEBUG_RECYCLE) {
1972 p.mStack = new RuntimeException();
1973 }
1974 p.init(obj);
1975 return p;
1976 }
1977 }
1978 }
1979 return new Parcel(obj);
1980 }
1981
1982 private Parcel(int obj) {
1983 if (DEBUG_RECYCLE) {
1984 mStack = new RuntimeException();
1985 }
1986 //Log.i("Parcel", "Initializing obj=0x" + Integer.toHexString(obj), mStack);
1987 init(obj);
1988 }
1989
1990 @Override
1991 protected void finalize() throws Throwable {
1992 if (DEBUG_RECYCLE) {
1993 if (mStack != null) {
1994 Log.w("Parcel", "Client did not call Parcel.recycle()", mStack);
1995 }
1996 }
1997 destroy();
1998 }
1999
2000 private native void freeBuffer();
2001 private native void init(int obj);
2002 private native void destroy();
2003
Dianne Hackborn6aff9052009-05-22 13:20:23 -07002004 /* package */ void readMapInternal(Map outVal, int N,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002005 ClassLoader loader) {
2006 while (N > 0) {
2007 Object key = readValue(loader);
2008 Object value = readValue(loader);
2009 outVal.put(key, value);
2010 N--;
2011 }
2012 }
2013
2014 private void readListInternal(List outVal, int N,
2015 ClassLoader loader) {
2016 while (N > 0) {
2017 Object value = readValue(loader);
2018 //Log.d("Parcel", "Unmarshalling value=" + value);
2019 outVal.add(value);
2020 N--;
2021 }
2022 }
2023
2024 private void readArrayInternal(Object[] outVal, int N,
2025 ClassLoader loader) {
2026 for (int i = 0; i < N; i++) {
2027 Object value = readValue(loader);
2028 //Log.d("Parcel", "Unmarshalling value=" + value);
2029 outVal[i] = value;
2030 }
2031 }
2032
2033 private void readSparseArrayInternal(SparseArray outVal, int N,
2034 ClassLoader loader) {
2035 while (N > 0) {
2036 int key = readInt();
2037 Object value = readValue(loader);
2038 //Log.i("Parcel", "Unmarshalling key=" + key + " value=" + value);
2039 outVal.append(key, value);
2040 N--;
2041 }
2042 }
2043
2044
2045 private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) {
2046 while (N > 0) {
2047 int key = readInt();
2048 boolean value = this.readByte() == 1;
2049 //Log.i("Parcel", "Unmarshalling key=" + key + " value=" + value);
2050 outVal.append(key, value);
2051 N--;
2052 }
2053 }
2054}