Parcel.java revision 2f974b252f819405a54798c9736f448f979a095f
1/* 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.ArrayMap; 21import android.util.Log; 22import android.util.Size; 23import android.util.SizeF; 24import android.util.SparseArray; 25import android.util.SparseBooleanArray; 26 27import java.io.ByteArrayInputStream; 28import java.io.ByteArrayOutputStream; 29import java.io.FileDescriptor; 30import java.io.FileNotFoundException; 31import java.io.IOException; 32import java.io.ObjectInputStream; 33import java.io.ObjectOutputStream; 34import java.io.ObjectStreamClass; 35import java.io.Serializable; 36import java.lang.reflect.Field; 37import java.lang.reflect.Modifier; 38import java.util.ArrayList; 39import java.util.Arrays; 40import java.util.HashMap; 41import java.util.List; 42import java.util.Map; 43import java.util.Set; 44 45/** 46 * Container for a message (data and object references) that can 47 * be sent through an IBinder. A Parcel can contain both flattened data 48 * that will be unflattened on the other side of the IPC (using the various 49 * methods here for writing specific types, or the general 50 * {@link Parcelable} interface), and references to live {@link IBinder} 51 * objects that will result in the other side receiving a proxy IBinder 52 * connected with the original IBinder in the Parcel. 53 * 54 * <p class="note">Parcel is <strong>not</strong> a general-purpose 55 * serialization mechanism. This class (and the corresponding 56 * {@link Parcelable} API for placing arbitrary objects into a Parcel) is 57 * designed as a high-performance IPC transport. As such, it is not 58 * appropriate to place any Parcel data in to persistent storage: changes 59 * in the underlying implementation of any of the data in the Parcel can 60 * render older data unreadable.</p> 61 * 62 * <p>The bulk of the Parcel API revolves around reading and writing data 63 * of various types. There are six major classes of such functions available.</p> 64 * 65 * <h3>Primitives</h3> 66 * 67 * <p>The most basic data functions are for writing and reading primitive 68 * data types: {@link #writeByte}, {@link #readByte}, {@link #writeDouble}, 69 * {@link #readDouble}, {@link #writeFloat}, {@link #readFloat}, {@link #writeInt}, 70 * {@link #readInt}, {@link #writeLong}, {@link #readLong}, 71 * {@link #writeString}, {@link #readString}. Most other 72 * data operations are built on top of these. The given data is written and 73 * read using the endianess of the host CPU.</p> 74 * 75 * <h3>Primitive Arrays</h3> 76 * 77 * <p>There are a variety of methods for reading and writing raw arrays 78 * of primitive objects, which generally result in writing a 4-byte length 79 * followed by the primitive data items. The methods for reading can either 80 * read the data into an existing array, or create and return a new array. 81 * These available types are:</p> 82 * 83 * <ul> 84 * <li> {@link #writeBooleanArray(boolean[])}, 85 * {@link #readBooleanArray(boolean[])}, {@link #createBooleanArray()} 86 * <li> {@link #writeByteArray(byte[])}, 87 * {@link #writeByteArray(byte[], int, int)}, {@link #readByteArray(byte[])}, 88 * {@link #createByteArray()} 89 * <li> {@link #writeCharArray(char[])}, {@link #readCharArray(char[])}, 90 * {@link #createCharArray()} 91 * <li> {@link #writeDoubleArray(double[])}, {@link #readDoubleArray(double[])}, 92 * {@link #createDoubleArray()} 93 * <li> {@link #writeFloatArray(float[])}, {@link #readFloatArray(float[])}, 94 * {@link #createFloatArray()} 95 * <li> {@link #writeIntArray(int[])}, {@link #readIntArray(int[])}, 96 * {@link #createIntArray()} 97 * <li> {@link #writeLongArray(long[])}, {@link #readLongArray(long[])}, 98 * {@link #createLongArray()} 99 * <li> {@link #writeStringArray(String[])}, {@link #readStringArray(String[])}, 100 * {@link #createStringArray()}. 101 * <li> {@link #writeSparseBooleanArray(SparseBooleanArray)}, 102 * {@link #readSparseBooleanArray()}. 103 * </ul> 104 * 105 * <h3>Parcelables</h3> 106 * 107 * <p>The {@link Parcelable} protocol provides an extremely efficient (but 108 * low-level) protocol for objects to write and read themselves from Parcels. 109 * You can use the direct methods {@link #writeParcelable(Parcelable, int)} 110 * and {@link #readParcelable(ClassLoader)} or 111 * {@link #writeParcelableArray} and 112 * {@link #readParcelableArray(ClassLoader)} to write or read. These 113 * methods write both the class type and its data to the Parcel, allowing 114 * that class to be reconstructed from the appropriate class loader when 115 * later reading.</p> 116 * 117 * <p>There are also some methods that provide a more efficient way to work 118 * with Parcelables: {@link #writeTypedObject}, {@link #writeTypedArray}, 119 * {@link #writeTypedList}, {@link #readTypedObject}, 120 * {@link #createTypedArray} and {@link #createTypedArrayList}. These methods 121 * do not write the class information of the original object: instead, the 122 * caller of the read function must know what type to expect and pass in the 123 * appropriate {@link Parcelable.Creator Parcelable.Creator} instead to 124 * properly construct the new object and read its data. (To more efficient 125 * write and read a single Parceable object that is not null, you can directly 126 * call {@link Parcelable#writeToParcel Parcelable.writeToParcel} and 127 * {@link Parcelable.Creator#createFromParcel Parcelable.Creator.createFromParcel} 128 * yourself.)</p> 129 * 130 * <h3>Bundles</h3> 131 * 132 * <p>A special type-safe container, called {@link Bundle}, is available 133 * for key/value maps of heterogeneous values. This has many optimizations 134 * for improved performance when reading and writing data, and its type-safe 135 * API avoids difficult to debug type errors when finally marshalling the 136 * data contents into a Parcel. The methods to use are 137 * {@link #writeBundle(Bundle)}, {@link #readBundle()}, and 138 * {@link #readBundle(ClassLoader)}. 139 * 140 * <h3>Active Objects</h3> 141 * 142 * <p>An unusual feature of Parcel is the ability to read and write active 143 * objects. For these objects the actual contents of the object is not 144 * written, rather a special token referencing the object is written. When 145 * reading the object back from the Parcel, you do not get a new instance of 146 * the object, but rather a handle that operates on the exact same object that 147 * was originally written. There are two forms of active objects available.</p> 148 * 149 * <p>{@link Binder} objects are a core facility of Android's general cross-process 150 * communication system. The {@link IBinder} interface describes an abstract 151 * protocol with a Binder object. Any such interface can be written in to 152 * a Parcel, and upon reading you will receive either the original object 153 * implementing that interface or a special proxy implementation 154 * that communicates calls back to the original object. The methods to use are 155 * {@link #writeStrongBinder(IBinder)}, 156 * {@link #writeStrongInterface(IInterface)}, {@link #readStrongBinder()}, 157 * {@link #writeBinderArray(IBinder[])}, {@link #readBinderArray(IBinder[])}, 158 * {@link #createBinderArray()}, 159 * {@link #writeBinderList(List)}, {@link #readBinderList(List)}, 160 * {@link #createBinderArrayList()}.</p> 161 * 162 * <p>FileDescriptor objects, representing raw Linux file descriptor identifiers, 163 * can be written and {@link ParcelFileDescriptor} objects returned to operate 164 * on the original file descriptor. The returned file descriptor is a dup 165 * of the original file descriptor: the object and fd is different, but 166 * operating on the same underlying file stream, with the same position, etc. 167 * The methods to use are {@link #writeFileDescriptor(FileDescriptor)}, 168 * {@link #readFileDescriptor()}. 169 * 170 * <h3>Untyped Containers</h3> 171 * 172 * <p>A final class of methods are for writing and reading standard Java 173 * containers of arbitrary types. These all revolve around the 174 * {@link #writeValue(Object)} and {@link #readValue(ClassLoader)} methods 175 * which define the types of objects allowed. The container methods are 176 * {@link #writeArray(Object[])}, {@link #readArray(ClassLoader)}, 177 * {@link #writeList(List)}, {@link #readList(List, ClassLoader)}, 178 * {@link #readArrayList(ClassLoader)}, 179 * {@link #writeMap(Map)}, {@link #readMap(Map, ClassLoader)}, 180 * {@link #writeSparseArray(SparseArray)}, 181 * {@link #readSparseArray(ClassLoader)}. 182 */ 183public final class Parcel { 184 private static final boolean DEBUG_RECYCLE = false; 185 private static final boolean DEBUG_ARRAY_MAP = false; 186 private static final String TAG = "Parcel"; 187 188 @SuppressWarnings({"UnusedDeclaration"}) 189 private long mNativePtr; // used by native code 190 191 /** 192 * Flag indicating if {@link #mNativePtr} was allocated by this object, 193 * indicating that we're responsible for its lifecycle. 194 */ 195 private boolean mOwnsNativeParcelObject; 196 197 private RuntimeException mStack; 198 199 private static final int POOL_SIZE = 6; 200 private static final Parcel[] sOwnedPool = new Parcel[POOL_SIZE]; 201 private static final Parcel[] sHolderPool = new Parcel[POOL_SIZE]; 202 203 private static final int VAL_NULL = -1; 204 private static final int VAL_STRING = 0; 205 private static final int VAL_INTEGER = 1; 206 private static final int VAL_MAP = 2; 207 private static final int VAL_BUNDLE = 3; 208 private static final int VAL_PARCELABLE = 4; 209 private static final int VAL_SHORT = 5; 210 private static final int VAL_LONG = 6; 211 private static final int VAL_FLOAT = 7; 212 private static final int VAL_DOUBLE = 8; 213 private static final int VAL_BOOLEAN = 9; 214 private static final int VAL_CHARSEQUENCE = 10; 215 private static final int VAL_LIST = 11; 216 private static final int VAL_SPARSEARRAY = 12; 217 private static final int VAL_BYTEARRAY = 13; 218 private static final int VAL_STRINGARRAY = 14; 219 private static final int VAL_IBINDER = 15; 220 private static final int VAL_PARCELABLEARRAY = 16; 221 private static final int VAL_OBJECTARRAY = 17; 222 private static final int VAL_INTARRAY = 18; 223 private static final int VAL_LONGARRAY = 19; 224 private static final int VAL_BYTE = 20; 225 private static final int VAL_SERIALIZABLE = 21; 226 private static final int VAL_SPARSEBOOLEANARRAY = 22; 227 private static final int VAL_BOOLEANARRAY = 23; 228 private static final int VAL_CHARSEQUENCEARRAY = 24; 229 private static final int VAL_PERSISTABLEBUNDLE = 25; 230 private static final int VAL_SIZE = 26; 231 private static final int VAL_SIZEF = 27; 232 233 // The initial int32 in a Binder call's reply Parcel header: 234 private static final int EX_SECURITY = -1; 235 private static final int EX_BAD_PARCELABLE = -2; 236 private static final int EX_ILLEGAL_ARGUMENT = -3; 237 private static final int EX_NULL_POINTER = -4; 238 private static final int EX_ILLEGAL_STATE = -5; 239 private static final int EX_NETWORK_MAIN_THREAD = -6; 240 private static final int EX_UNSUPPORTED_OPERATION = -7; 241 private static final int EX_HAS_REPLY_HEADER = -128; // special; see below 242 243 private static native int nativeDataSize(long nativePtr); 244 private static native int nativeDataAvail(long nativePtr); 245 private static native int nativeDataPosition(long nativePtr); 246 private static native int nativeDataCapacity(long nativePtr); 247 private static native void nativeSetDataSize(long nativePtr, int size); 248 private static native void nativeSetDataPosition(long nativePtr, int pos); 249 private static native void nativeSetDataCapacity(long nativePtr, int size); 250 251 private static native boolean nativePushAllowFds(long nativePtr, boolean allowFds); 252 private static native void nativeRestoreAllowFds(long nativePtr, boolean lastValue); 253 254 private static native void nativeWriteByteArray(long nativePtr, byte[] b, int offset, int len); 255 private static native void nativeWriteBlob(long nativePtr, byte[] b, int offset, int len); 256 private static native void nativeWriteInt(long nativePtr, int val); 257 private static native void nativeWriteLong(long nativePtr, long val); 258 private static native void nativeWriteFloat(long nativePtr, float val); 259 private static native void nativeWriteDouble(long nativePtr, double val); 260 private static native void nativeWriteString(long nativePtr, String val); 261 private static native void nativeWriteStrongBinder(long nativePtr, IBinder val); 262 private static native void nativeWriteFileDescriptor(long nativePtr, FileDescriptor val); 263 264 private static native byte[] nativeCreateByteArray(long nativePtr); 265 private static native byte[] nativeReadBlob(long nativePtr); 266 private static native int nativeReadInt(long nativePtr); 267 private static native long nativeReadLong(long nativePtr); 268 private static native float nativeReadFloat(long nativePtr); 269 private static native double nativeReadDouble(long nativePtr); 270 private static native String nativeReadString(long nativePtr); 271 private static native IBinder nativeReadStrongBinder(long nativePtr); 272 private static native FileDescriptor nativeReadFileDescriptor(long nativePtr); 273 274 private static native long nativeCreate(); 275 private static native void nativeFreeBuffer(long nativePtr); 276 private static native void nativeDestroy(long nativePtr); 277 278 private static native byte[] nativeMarshall(long nativePtr); 279 private static native void nativeUnmarshall( 280 long nativePtr, byte[] data, int offset, int length); 281 private static native void nativeAppendFrom( 282 long thisNativePtr, long otherNativePtr, int offset, int length); 283 private static native boolean nativeHasFileDescriptors(long nativePtr); 284 private static native void nativeWriteInterfaceToken(long nativePtr, String interfaceName); 285 private static native void nativeEnforceInterface(long nativePtr, String interfaceName); 286 287 private static native long nativeGetBlobAshmemSize(long nativePtr); 288 289 public final static Parcelable.Creator<String> STRING_CREATOR 290 = new Parcelable.Creator<String>() { 291 public String createFromParcel(Parcel source) { 292 return source.readString(); 293 } 294 public String[] newArray(int size) { 295 return new String[size]; 296 } 297 }; 298 299 /** 300 * Retrieve a new Parcel object from the pool. 301 */ 302 public static Parcel obtain() { 303 final Parcel[] pool = sOwnedPool; 304 synchronized (pool) { 305 Parcel p; 306 for (int i=0; i<POOL_SIZE; i++) { 307 p = pool[i]; 308 if (p != null) { 309 pool[i] = null; 310 if (DEBUG_RECYCLE) { 311 p.mStack = new RuntimeException(); 312 } 313 return p; 314 } 315 } 316 } 317 return new Parcel(0); 318 } 319 320 /** 321 * Put a Parcel object back into the pool. You must not touch 322 * the object after this call. 323 */ 324 public final void recycle() { 325 if (DEBUG_RECYCLE) mStack = null; 326 freeBuffer(); 327 328 final Parcel[] pool; 329 if (mOwnsNativeParcelObject) { 330 pool = sOwnedPool; 331 } else { 332 mNativePtr = 0; 333 pool = sHolderPool; 334 } 335 336 synchronized (pool) { 337 for (int i=0; i<POOL_SIZE; i++) { 338 if (pool[i] == null) { 339 pool[i] = this; 340 return; 341 } 342 } 343 } 344 } 345 346 /** @hide */ 347 public static native long getGlobalAllocSize(); 348 349 /** @hide */ 350 public static native long getGlobalAllocCount(); 351 352 /** 353 * Returns the total amount of data contained in the parcel. 354 */ 355 public final int dataSize() { 356 return nativeDataSize(mNativePtr); 357 } 358 359 /** 360 * Returns the amount of data remaining to be read from the 361 * parcel. That is, {@link #dataSize}-{@link #dataPosition}. 362 */ 363 public final int dataAvail() { 364 return nativeDataAvail(mNativePtr); 365 } 366 367 /** 368 * Returns the current position in the parcel data. Never 369 * more than {@link #dataSize}. 370 */ 371 public final int dataPosition() { 372 return nativeDataPosition(mNativePtr); 373 } 374 375 /** 376 * Returns the total amount of space in the parcel. This is always 377 * >= {@link #dataSize}. The difference between it and dataSize() is the 378 * amount of room left until the parcel needs to re-allocate its 379 * data buffer. 380 */ 381 public final int dataCapacity() { 382 return nativeDataCapacity(mNativePtr); 383 } 384 385 /** 386 * Change the amount of data in the parcel. Can be either smaller or 387 * larger than the current size. If larger than the current capacity, 388 * more memory will be allocated. 389 * 390 * @param size The new number of bytes in the Parcel. 391 */ 392 public final void setDataSize(int size) { 393 nativeSetDataSize(mNativePtr, size); 394 } 395 396 /** 397 * Move the current read/write position in the parcel. 398 * @param pos New offset in the parcel; must be between 0 and 399 * {@link #dataSize}. 400 */ 401 public final void setDataPosition(int pos) { 402 nativeSetDataPosition(mNativePtr, pos); 403 } 404 405 /** 406 * Change the capacity (current available space) of the parcel. 407 * 408 * @param size The new capacity of the parcel, in bytes. Can not be 409 * less than {@link #dataSize} -- that is, you can not drop existing data 410 * with this method. 411 */ 412 public final void setDataCapacity(int size) { 413 nativeSetDataCapacity(mNativePtr, size); 414 } 415 416 /** @hide */ 417 public final boolean pushAllowFds(boolean allowFds) { 418 return nativePushAllowFds(mNativePtr, allowFds); 419 } 420 421 /** @hide */ 422 public final void restoreAllowFds(boolean lastValue) { 423 nativeRestoreAllowFds(mNativePtr, lastValue); 424 } 425 426 /** 427 * Returns the raw bytes of the parcel. 428 * 429 * <p class="note">The data you retrieve here <strong>must not</strong> 430 * be placed in any kind of persistent storage (on local disk, across 431 * a network, etc). For that, you should use standard serialization 432 * or another kind of general serialization mechanism. The Parcel 433 * marshalled representation is highly optimized for local IPC, and as 434 * such does not attempt to maintain compatibility with data created 435 * in different versions of the platform. 436 */ 437 public final byte[] marshall() { 438 return nativeMarshall(mNativePtr); 439 } 440 441 /** 442 * Set the bytes in data to be the raw bytes of this Parcel. 443 */ 444 public final void unmarshall(byte[] data, int offset, int length) { 445 nativeUnmarshall(mNativePtr, data, offset, length); 446 } 447 448 public final void appendFrom(Parcel parcel, int offset, int length) { 449 nativeAppendFrom(mNativePtr, parcel.mNativePtr, offset, length); 450 } 451 452 /** 453 * Report whether the parcel contains any marshalled file descriptors. 454 */ 455 public final boolean hasFileDescriptors() { 456 return nativeHasFileDescriptors(mNativePtr); 457 } 458 459 /** 460 * Store or read an IBinder interface token in the parcel at the current 461 * {@link #dataPosition}. This is used to validate that the marshalled 462 * transaction is intended for the target interface. 463 */ 464 public final void writeInterfaceToken(String interfaceName) { 465 nativeWriteInterfaceToken(mNativePtr, interfaceName); 466 } 467 468 public final void enforceInterface(String interfaceName) { 469 nativeEnforceInterface(mNativePtr, interfaceName); 470 } 471 472 /** 473 * Write a byte array into the parcel at the current {@link #dataPosition}, 474 * growing {@link #dataCapacity} if needed. 475 * @param b Bytes to place into the parcel. 476 */ 477 public final void writeByteArray(byte[] b) { 478 writeByteArray(b, 0, (b != null) ? b.length : 0); 479 } 480 481 /** 482 * Write a byte array into the parcel at the current {@link #dataPosition}, 483 * growing {@link #dataCapacity} if needed. 484 * @param b Bytes to place into the parcel. 485 * @param offset Index of first byte to be written. 486 * @param len Number of bytes to write. 487 */ 488 public final void writeByteArray(byte[] b, int offset, int len) { 489 if (b == null) { 490 writeInt(-1); 491 return; 492 } 493 Arrays.checkOffsetAndCount(b.length, offset, len); 494 nativeWriteByteArray(mNativePtr, b, offset, len); 495 } 496 497 /** 498 * Write a blob of data into the parcel at the current {@link #dataPosition}, 499 * growing {@link #dataCapacity} if needed. 500 * @param b Bytes to place into the parcel. 501 * {@hide} 502 * {@SystemApi} 503 */ 504 public final void writeBlob(byte[] b) { 505 writeBlob(b, 0, (b != null) ? b.length : 0); 506 } 507 508 /** 509 * Write a blob of data into the parcel at the current {@link #dataPosition}, 510 * growing {@link #dataCapacity} if needed. 511 * @param b Bytes to place into the parcel. 512 * @param offset Index of first byte to be written. 513 * @param len Number of bytes to write. 514 * {@hide} 515 * {@SystemApi} 516 */ 517 public final void writeBlob(byte[] b, int offset, int len) { 518 if (b == null) { 519 writeInt(-1); 520 return; 521 } 522 Arrays.checkOffsetAndCount(b.length, offset, len); 523 nativeWriteBlob(mNativePtr, b, offset, len); 524 } 525 526 /** 527 * Write an integer value into the parcel at the current dataPosition(), 528 * growing dataCapacity() if needed. 529 */ 530 public final void writeInt(int val) { 531 nativeWriteInt(mNativePtr, val); 532 } 533 534 /** 535 * Write a long integer value into the parcel at the current dataPosition(), 536 * growing dataCapacity() if needed. 537 */ 538 public final void writeLong(long val) { 539 nativeWriteLong(mNativePtr, val); 540 } 541 542 /** 543 * Write a floating point value into the parcel at the current 544 * dataPosition(), growing dataCapacity() if needed. 545 */ 546 public final void writeFloat(float val) { 547 nativeWriteFloat(mNativePtr, val); 548 } 549 550 /** 551 * Write a double precision floating point value into the parcel at the 552 * current dataPosition(), growing dataCapacity() if needed. 553 */ 554 public final void writeDouble(double val) { 555 nativeWriteDouble(mNativePtr, val); 556 } 557 558 /** 559 * Write a string value into the parcel at the current dataPosition(), 560 * growing dataCapacity() if needed. 561 */ 562 public final void writeString(String val) { 563 nativeWriteString(mNativePtr, val); 564 } 565 566 /** 567 * Write a CharSequence value into the parcel at the current dataPosition(), 568 * growing dataCapacity() if needed. 569 * @hide 570 */ 571 public final void writeCharSequence(CharSequence val) { 572 TextUtils.writeToParcel(val, this, 0); 573 } 574 575 /** 576 * Write an object into the parcel at the current dataPosition(), 577 * growing dataCapacity() if needed. 578 */ 579 public final void writeStrongBinder(IBinder val) { 580 nativeWriteStrongBinder(mNativePtr, val); 581 } 582 583 /** 584 * Write an object into the parcel at the current dataPosition(), 585 * growing dataCapacity() if needed. 586 */ 587 public final void writeStrongInterface(IInterface val) { 588 writeStrongBinder(val == null ? null : val.asBinder()); 589 } 590 591 /** 592 * Write a FileDescriptor into the parcel at the current dataPosition(), 593 * growing dataCapacity() if needed. 594 * 595 * <p class="caution">The file descriptor will not be closed, which may 596 * result in file descriptor leaks when objects are returned from Binder 597 * calls. Use {@link ParcelFileDescriptor#writeToParcel} instead, which 598 * accepts contextual flags and will close the original file descriptor 599 * if {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} is set.</p> 600 */ 601 public final void writeFileDescriptor(FileDescriptor val) { 602 nativeWriteFileDescriptor(mNativePtr, val); 603 } 604 605 /** 606 * {@hide} 607 * This will be the new name for writeFileDescriptor, for consistency. 608 **/ 609 public final void writeRawFileDescriptor(FileDescriptor val) { 610 nativeWriteFileDescriptor(mNativePtr, val); 611 } 612 613 /** 614 * {@hide} 615 * Write an array of FileDescriptor objects into the Parcel. 616 * 617 * @param value The array of objects to be written. 618 */ 619 public final void writeRawFileDescriptorArray(FileDescriptor[] value) { 620 if (value != null) { 621 int N = value.length; 622 writeInt(N); 623 for (int i=0; i<N; i++) { 624 writeRawFileDescriptor(value[i]); 625 } 626 } else { 627 writeInt(-1); 628 } 629 } 630 631 /** 632 * Write a byte value into the parcel at the current dataPosition(), 633 * growing dataCapacity() if needed. 634 */ 635 public final void writeByte(byte val) { 636 writeInt(val); 637 } 638 639 /** 640 * Please use {@link #writeBundle} instead. Flattens a Map into the parcel 641 * at the current dataPosition(), 642 * growing dataCapacity() if needed. The Map keys must be String objects. 643 * The Map values are written using {@link #writeValue} and must follow 644 * the specification there. 645 * 646 * <p>It is strongly recommended to use {@link #writeBundle} instead of 647 * this method, since the Bundle class provides a type-safe API that 648 * allows you to avoid mysterious type errors at the point of marshalling. 649 */ 650 public final void writeMap(Map val) { 651 writeMapInternal((Map<String, Object>) val); 652 } 653 654 /** 655 * Flatten a Map into the parcel at the current dataPosition(), 656 * growing dataCapacity() if needed. The Map keys must be String objects. 657 */ 658 /* package */ void writeMapInternal(Map<String,Object> val) { 659 if (val == null) { 660 writeInt(-1); 661 return; 662 } 663 Set<Map.Entry<String,Object>> entries = val.entrySet(); 664 writeInt(entries.size()); 665 for (Map.Entry<String,Object> e : entries) { 666 writeValue(e.getKey()); 667 writeValue(e.getValue()); 668 } 669 } 670 671 /** 672 * Flatten an ArrayMap into the parcel at the current dataPosition(), 673 * growing dataCapacity() if needed. The Map keys must be String objects. 674 */ 675 /* package */ void writeArrayMapInternal(ArrayMap<String, Object> val) { 676 if (val == null) { 677 writeInt(-1); 678 return; 679 } 680 final int N = val.size(); 681 writeInt(N); 682 if (DEBUG_ARRAY_MAP) { 683 RuntimeException here = new RuntimeException("here"); 684 here.fillInStackTrace(); 685 Log.d(TAG, "Writing " + N + " ArrayMap entries", here); 686 } 687 int startPos; 688 for (int i=0; i<N; i++) { 689 if (DEBUG_ARRAY_MAP) startPos = dataPosition(); 690 writeString(val.keyAt(i)); 691 writeValue(val.valueAt(i)); 692 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Write #" + i + " " 693 + (dataPosition()-startPos) + " bytes: key=0x" 694 + Integer.toHexString(val.keyAt(i) != null ? val.keyAt(i).hashCode() : 0) 695 + " " + val.keyAt(i)); 696 } 697 } 698 699 /** 700 * @hide For testing only. 701 */ 702 public void writeArrayMap(ArrayMap<String, Object> val) { 703 writeArrayMapInternal(val); 704 } 705 706 /** 707 * Flatten a Bundle into the parcel at the current dataPosition(), 708 * growing dataCapacity() if needed. 709 */ 710 public final void writeBundle(Bundle val) { 711 if (val == null) { 712 writeInt(-1); 713 return; 714 } 715 716 val.writeToParcel(this, 0); 717 } 718 719 /** 720 * Flatten a PersistableBundle into the parcel at the current dataPosition(), 721 * growing dataCapacity() if needed. 722 */ 723 public final void writePersistableBundle(PersistableBundle val) { 724 if (val == null) { 725 writeInt(-1); 726 return; 727 } 728 729 val.writeToParcel(this, 0); 730 } 731 732 /** 733 * Flatten a Size into the parcel at the current dataPosition(), 734 * growing dataCapacity() if needed. 735 */ 736 public final void writeSize(Size val) { 737 writeInt(val.getWidth()); 738 writeInt(val.getHeight()); 739 } 740 741 /** 742 * Flatten a SizeF into the parcel at the current dataPosition(), 743 * growing dataCapacity() if needed. 744 */ 745 public final void writeSizeF(SizeF val) { 746 writeFloat(val.getWidth()); 747 writeFloat(val.getHeight()); 748 } 749 750 /** 751 * Flatten a List into the parcel at the current dataPosition(), growing 752 * dataCapacity() if needed. The List values are written using 753 * {@link #writeValue} and must follow the specification there. 754 */ 755 public final void writeList(List val) { 756 if (val == null) { 757 writeInt(-1); 758 return; 759 } 760 int N = val.size(); 761 int i=0; 762 writeInt(N); 763 while (i < N) { 764 writeValue(val.get(i)); 765 i++; 766 } 767 } 768 769 /** 770 * Flatten an Object array into the parcel at the current dataPosition(), 771 * growing dataCapacity() if needed. The array values are written using 772 * {@link #writeValue} and must follow the specification there. 773 */ 774 public final void writeArray(Object[] val) { 775 if (val == null) { 776 writeInt(-1); 777 return; 778 } 779 int N = val.length; 780 int i=0; 781 writeInt(N); 782 while (i < N) { 783 writeValue(val[i]); 784 i++; 785 } 786 } 787 788 /** 789 * Flatten a generic SparseArray into the parcel at the current 790 * dataPosition(), growing dataCapacity() if needed. The SparseArray 791 * values are written using {@link #writeValue} and must follow the 792 * specification there. 793 */ 794 public final void writeSparseArray(SparseArray<Object> val) { 795 if (val == null) { 796 writeInt(-1); 797 return; 798 } 799 int N = val.size(); 800 writeInt(N); 801 int i=0; 802 while (i < N) { 803 writeInt(val.keyAt(i)); 804 writeValue(val.valueAt(i)); 805 i++; 806 } 807 } 808 809 public final void writeSparseBooleanArray(SparseBooleanArray val) { 810 if (val == null) { 811 writeInt(-1); 812 return; 813 } 814 int N = val.size(); 815 writeInt(N); 816 int i=0; 817 while (i < N) { 818 writeInt(val.keyAt(i)); 819 writeByte((byte)(val.valueAt(i) ? 1 : 0)); 820 i++; 821 } 822 } 823 824 public final void writeBooleanArray(boolean[] val) { 825 if (val != null) { 826 int N = val.length; 827 writeInt(N); 828 for (int i=0; i<N; i++) { 829 writeInt(val[i] ? 1 : 0); 830 } 831 } else { 832 writeInt(-1); 833 } 834 } 835 836 public final boolean[] createBooleanArray() { 837 int N = readInt(); 838 // >>2 as a fast divide-by-4 works in the create*Array() functions 839 // because dataAvail() will never return a negative number. 4 is 840 // the size of a stored boolean in the stream. 841 if (N >= 0 && N <= (dataAvail() >> 2)) { 842 boolean[] val = new boolean[N]; 843 for (int i=0; i<N; i++) { 844 val[i] = readInt() != 0; 845 } 846 return val; 847 } else { 848 return null; 849 } 850 } 851 852 public final void readBooleanArray(boolean[] val) { 853 int N = readInt(); 854 if (N == val.length) { 855 for (int i=0; i<N; i++) { 856 val[i] = readInt() != 0; 857 } 858 } else { 859 throw new RuntimeException("bad array lengths"); 860 } 861 } 862 863 public final void writeCharArray(char[] val) { 864 if (val != null) { 865 int N = val.length; 866 writeInt(N); 867 for (int i=0; i<N; i++) { 868 writeInt((int)val[i]); 869 } 870 } else { 871 writeInt(-1); 872 } 873 } 874 875 public final char[] createCharArray() { 876 int N = readInt(); 877 if (N >= 0 && N <= (dataAvail() >> 2)) { 878 char[] val = new char[N]; 879 for (int i=0; i<N; i++) { 880 val[i] = (char)readInt(); 881 } 882 return val; 883 } else { 884 return null; 885 } 886 } 887 888 public final void readCharArray(char[] val) { 889 int N = readInt(); 890 if (N == val.length) { 891 for (int i=0; i<N; i++) { 892 val[i] = (char)readInt(); 893 } 894 } else { 895 throw new RuntimeException("bad array lengths"); 896 } 897 } 898 899 public final void writeIntArray(int[] val) { 900 if (val != null) { 901 int N = val.length; 902 writeInt(N); 903 for (int i=0; i<N; i++) { 904 writeInt(val[i]); 905 } 906 } else { 907 writeInt(-1); 908 } 909 } 910 911 public final int[] createIntArray() { 912 int N = readInt(); 913 if (N >= 0 && N <= (dataAvail() >> 2)) { 914 int[] val = new int[N]; 915 for (int i=0; i<N; i++) { 916 val[i] = readInt(); 917 } 918 return val; 919 } else { 920 return null; 921 } 922 } 923 924 public final void readIntArray(int[] val) { 925 int N = readInt(); 926 if (N == val.length) { 927 for (int i=0; i<N; i++) { 928 val[i] = readInt(); 929 } 930 } else { 931 throw new RuntimeException("bad array lengths"); 932 } 933 } 934 935 public final void writeLongArray(long[] val) { 936 if (val != null) { 937 int N = val.length; 938 writeInt(N); 939 for (int i=0; i<N; i++) { 940 writeLong(val[i]); 941 } 942 } else { 943 writeInt(-1); 944 } 945 } 946 947 public final long[] createLongArray() { 948 int N = readInt(); 949 // >>3 because stored longs are 64 bits 950 if (N >= 0 && N <= (dataAvail() >> 3)) { 951 long[] val = new long[N]; 952 for (int i=0; i<N; i++) { 953 val[i] = readLong(); 954 } 955 return val; 956 } else { 957 return null; 958 } 959 } 960 961 public final void readLongArray(long[] val) { 962 int N = readInt(); 963 if (N == val.length) { 964 for (int i=0; i<N; i++) { 965 val[i] = readLong(); 966 } 967 } else { 968 throw new RuntimeException("bad array lengths"); 969 } 970 } 971 972 public final void writeFloatArray(float[] val) { 973 if (val != null) { 974 int N = val.length; 975 writeInt(N); 976 for (int i=0; i<N; i++) { 977 writeFloat(val[i]); 978 } 979 } else { 980 writeInt(-1); 981 } 982 } 983 984 public final float[] createFloatArray() { 985 int N = readInt(); 986 // >>2 because stored floats are 4 bytes 987 if (N >= 0 && N <= (dataAvail() >> 2)) { 988 float[] val = new float[N]; 989 for (int i=0; i<N; i++) { 990 val[i] = readFloat(); 991 } 992 return val; 993 } else { 994 return null; 995 } 996 } 997 998 public final void readFloatArray(float[] val) { 999 int N = readInt(); 1000 if (N == val.length) { 1001 for (int i=0; i<N; i++) { 1002 val[i] = readFloat(); 1003 } 1004 } else { 1005 throw new RuntimeException("bad array lengths"); 1006 } 1007 } 1008 1009 public final void writeDoubleArray(double[] val) { 1010 if (val != null) { 1011 int N = val.length; 1012 writeInt(N); 1013 for (int i=0; i<N; i++) { 1014 writeDouble(val[i]); 1015 } 1016 } else { 1017 writeInt(-1); 1018 } 1019 } 1020 1021 public final double[] createDoubleArray() { 1022 int N = readInt(); 1023 // >>3 because stored doubles are 8 bytes 1024 if (N >= 0 && N <= (dataAvail() >> 3)) { 1025 double[] val = new double[N]; 1026 for (int i=0; i<N; i++) { 1027 val[i] = readDouble(); 1028 } 1029 return val; 1030 } else { 1031 return null; 1032 } 1033 } 1034 1035 public final void readDoubleArray(double[] val) { 1036 int N = readInt(); 1037 if (N == val.length) { 1038 for (int i=0; i<N; i++) { 1039 val[i] = readDouble(); 1040 } 1041 } else { 1042 throw new RuntimeException("bad array lengths"); 1043 } 1044 } 1045 1046 public final void writeStringArray(String[] val) { 1047 if (val != null) { 1048 int N = val.length; 1049 writeInt(N); 1050 for (int i=0; i<N; i++) { 1051 writeString(val[i]); 1052 } 1053 } else { 1054 writeInt(-1); 1055 } 1056 } 1057 1058 public final String[] createStringArray() { 1059 int N = readInt(); 1060 if (N >= 0) { 1061 String[] val = new String[N]; 1062 for (int i=0; i<N; i++) { 1063 val[i] = readString(); 1064 } 1065 return val; 1066 } else { 1067 return null; 1068 } 1069 } 1070 1071 public final void readStringArray(String[] val) { 1072 int N = readInt(); 1073 if (N == val.length) { 1074 for (int i=0; i<N; i++) { 1075 val[i] = readString(); 1076 } 1077 } else { 1078 throw new RuntimeException("bad array lengths"); 1079 } 1080 } 1081 1082 public final void writeBinderArray(IBinder[] val) { 1083 if (val != null) { 1084 int N = val.length; 1085 writeInt(N); 1086 for (int i=0; i<N; i++) { 1087 writeStrongBinder(val[i]); 1088 } 1089 } else { 1090 writeInt(-1); 1091 } 1092 } 1093 1094 /** 1095 * @hide 1096 */ 1097 public final void writeCharSequenceArray(CharSequence[] val) { 1098 if (val != null) { 1099 int N = val.length; 1100 writeInt(N); 1101 for (int i=0; i<N; i++) { 1102 writeCharSequence(val[i]); 1103 } 1104 } else { 1105 writeInt(-1); 1106 } 1107 } 1108 1109 /** 1110 * @hide 1111 */ 1112 public final void writeCharSequenceList(ArrayList<CharSequence> val) { 1113 if (val != null) { 1114 int N = val.size(); 1115 writeInt(N); 1116 for (int i=0; i<N; i++) { 1117 writeCharSequence(val.get(i)); 1118 } 1119 } else { 1120 writeInt(-1); 1121 } 1122 } 1123 1124 public final IBinder[] createBinderArray() { 1125 int N = readInt(); 1126 if (N >= 0) { 1127 IBinder[] val = new IBinder[N]; 1128 for (int i=0; i<N; i++) { 1129 val[i] = readStrongBinder(); 1130 } 1131 return val; 1132 } else { 1133 return null; 1134 } 1135 } 1136 1137 public final void readBinderArray(IBinder[] val) { 1138 int N = readInt(); 1139 if (N == val.length) { 1140 for (int i=0; i<N; i++) { 1141 val[i] = readStrongBinder(); 1142 } 1143 } else { 1144 throw new RuntimeException("bad array lengths"); 1145 } 1146 } 1147 1148 /** 1149 * Flatten a List containing a particular object type into the parcel, at 1150 * the current dataPosition() and growing dataCapacity() if needed. The 1151 * type of the objects in the list must be one that implements Parcelable. 1152 * Unlike the generic writeList() method, however, only the raw data of the 1153 * objects is written and not their type, so you must use the corresponding 1154 * readTypedList() to unmarshall them. 1155 * 1156 * @param val The list of objects to be written. 1157 * 1158 * @see #createTypedArrayList 1159 * @see #readTypedList 1160 * @see Parcelable 1161 */ 1162 public final <T extends Parcelable> void writeTypedList(List<T> val) { 1163 if (val == null) { 1164 writeInt(-1); 1165 return; 1166 } 1167 int N = val.size(); 1168 int i=0; 1169 writeInt(N); 1170 while (i < N) { 1171 T item = val.get(i); 1172 if (item != null) { 1173 writeInt(1); 1174 item.writeToParcel(this, 0); 1175 } else { 1176 writeInt(0); 1177 } 1178 i++; 1179 } 1180 } 1181 1182 /** 1183 * Flatten a List containing String objects into the parcel, at 1184 * the current dataPosition() and growing dataCapacity() if needed. They 1185 * can later be retrieved with {@link #createStringArrayList} or 1186 * {@link #readStringList}. 1187 * 1188 * @param val The list of strings to be written. 1189 * 1190 * @see #createStringArrayList 1191 * @see #readStringList 1192 */ 1193 public final void writeStringList(List<String> val) { 1194 if (val == null) { 1195 writeInt(-1); 1196 return; 1197 } 1198 int N = val.size(); 1199 int i=0; 1200 writeInt(N); 1201 while (i < N) { 1202 writeString(val.get(i)); 1203 i++; 1204 } 1205 } 1206 1207 /** 1208 * Flatten a List containing IBinder objects into the parcel, at 1209 * the current dataPosition() and growing dataCapacity() if needed. They 1210 * can later be retrieved with {@link #createBinderArrayList} or 1211 * {@link #readBinderList}. 1212 * 1213 * @param val The list of strings to be written. 1214 * 1215 * @see #createBinderArrayList 1216 * @see #readBinderList 1217 */ 1218 public final void writeBinderList(List<IBinder> val) { 1219 if (val == null) { 1220 writeInt(-1); 1221 return; 1222 } 1223 int N = val.size(); 1224 int i=0; 1225 writeInt(N); 1226 while (i < N) { 1227 writeStrongBinder(val.get(i)); 1228 i++; 1229 } 1230 } 1231 1232 /** 1233 * Flatten a heterogeneous array containing a particular object type into 1234 * the parcel, at 1235 * the current dataPosition() and growing dataCapacity() if needed. The 1236 * type of the objects in the array must be one that implements Parcelable. 1237 * Unlike the {@link #writeParcelableArray} method, however, only the 1238 * raw data of the objects is written and not their type, so you must use 1239 * {@link #readTypedArray} with the correct corresponding 1240 * {@link Parcelable.Creator} implementation to unmarshall them. 1241 * 1242 * @param val The array of objects to be written. 1243 * @param parcelableFlags Contextual flags as per 1244 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}. 1245 * 1246 * @see #readTypedArray 1247 * @see #writeParcelableArray 1248 * @see Parcelable.Creator 1249 */ 1250 public final <T extends Parcelable> void writeTypedArray(T[] val, 1251 int parcelableFlags) { 1252 if (val != null) { 1253 int N = val.length; 1254 writeInt(N); 1255 for (int i=0; i<N; i++) { 1256 T item = val[i]; 1257 if (item != null) { 1258 writeInt(1); 1259 item.writeToParcel(this, parcelableFlags); 1260 } else { 1261 writeInt(0); 1262 } 1263 } 1264 } else { 1265 writeInt(-1); 1266 } 1267 } 1268 1269 /** 1270 * Flatten the Parcelable object into the parcel. 1271 * 1272 * @param val The Parcelable object to be written. 1273 * @param parcelableFlags Contextual flags as per 1274 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}. 1275 * 1276 * @see #readTypedObject 1277 */ 1278 public final <T extends Parcelable> void writeTypedObject(T val, int parcelableFlags) { 1279 if (val != null) { 1280 writeInt(1); 1281 val.writeToParcel(this, parcelableFlags); 1282 } else { 1283 writeInt(0); 1284 } 1285 } 1286 1287 /** 1288 * Flatten a generic object in to a parcel. The given Object value may 1289 * currently be one of the following types: 1290 * 1291 * <ul> 1292 * <li> null 1293 * <li> String 1294 * <li> Byte 1295 * <li> Short 1296 * <li> Integer 1297 * <li> Long 1298 * <li> Float 1299 * <li> Double 1300 * <li> Boolean 1301 * <li> String[] 1302 * <li> boolean[] 1303 * <li> byte[] 1304 * <li> int[] 1305 * <li> long[] 1306 * <li> Object[] (supporting objects of the same type defined here). 1307 * <li> {@link Bundle} 1308 * <li> Map (as supported by {@link #writeMap}). 1309 * <li> Any object that implements the {@link Parcelable} protocol. 1310 * <li> Parcelable[] 1311 * <li> CharSequence (as supported by {@link TextUtils#writeToParcel}). 1312 * <li> List (as supported by {@link #writeList}). 1313 * <li> {@link SparseArray} (as supported by {@link #writeSparseArray(SparseArray)}). 1314 * <li> {@link IBinder} 1315 * <li> Any object that implements Serializable (but see 1316 * {@link #writeSerializable} for caveats). Note that all of the 1317 * previous types have relatively efficient implementations for 1318 * writing to a Parcel; having to rely on the generic serialization 1319 * approach is much less efficient and should be avoided whenever 1320 * possible. 1321 * </ul> 1322 * 1323 * <p class="caution">{@link Parcelable} objects are written with 1324 * {@link Parcelable#writeToParcel} using contextual flags of 0. When 1325 * serializing objects containing {@link ParcelFileDescriptor}s, 1326 * this may result in file descriptor leaks when they are returned from 1327 * Binder calls (where {@link Parcelable#PARCELABLE_WRITE_RETURN_VALUE} 1328 * should be used).</p> 1329 */ 1330 public final void writeValue(Object v) { 1331 if (v == null) { 1332 writeInt(VAL_NULL); 1333 } else if (v instanceof String) { 1334 writeInt(VAL_STRING); 1335 writeString((String) v); 1336 } else if (v instanceof Integer) { 1337 writeInt(VAL_INTEGER); 1338 writeInt((Integer) v); 1339 } else if (v instanceof Map) { 1340 writeInt(VAL_MAP); 1341 writeMap((Map) v); 1342 } else if (v instanceof Bundle) { 1343 // Must be before Parcelable 1344 writeInt(VAL_BUNDLE); 1345 writeBundle((Bundle) v); 1346 } else if (v instanceof Parcelable) { 1347 writeInt(VAL_PARCELABLE); 1348 writeParcelable((Parcelable) v, 0); 1349 } else if (v instanceof Short) { 1350 writeInt(VAL_SHORT); 1351 writeInt(((Short) v).intValue()); 1352 } else if (v instanceof Long) { 1353 writeInt(VAL_LONG); 1354 writeLong((Long) v); 1355 } else if (v instanceof Float) { 1356 writeInt(VAL_FLOAT); 1357 writeFloat((Float) v); 1358 } else if (v instanceof Double) { 1359 writeInt(VAL_DOUBLE); 1360 writeDouble((Double) v); 1361 } else if (v instanceof Boolean) { 1362 writeInt(VAL_BOOLEAN); 1363 writeInt((Boolean) v ? 1 : 0); 1364 } else if (v instanceof CharSequence) { 1365 // Must be after String 1366 writeInt(VAL_CHARSEQUENCE); 1367 writeCharSequence((CharSequence) v); 1368 } else if (v instanceof List) { 1369 writeInt(VAL_LIST); 1370 writeList((List) v); 1371 } else if (v instanceof SparseArray) { 1372 writeInt(VAL_SPARSEARRAY); 1373 writeSparseArray((SparseArray) v); 1374 } else if (v instanceof boolean[]) { 1375 writeInt(VAL_BOOLEANARRAY); 1376 writeBooleanArray((boolean[]) v); 1377 } else if (v instanceof byte[]) { 1378 writeInt(VAL_BYTEARRAY); 1379 writeByteArray((byte[]) v); 1380 } else if (v instanceof String[]) { 1381 writeInt(VAL_STRINGARRAY); 1382 writeStringArray((String[]) v); 1383 } else if (v instanceof CharSequence[]) { 1384 // Must be after String[] and before Object[] 1385 writeInt(VAL_CHARSEQUENCEARRAY); 1386 writeCharSequenceArray((CharSequence[]) v); 1387 } else if (v instanceof IBinder) { 1388 writeInt(VAL_IBINDER); 1389 writeStrongBinder((IBinder) v); 1390 } else if (v instanceof Parcelable[]) { 1391 writeInt(VAL_PARCELABLEARRAY); 1392 writeParcelableArray((Parcelable[]) v, 0); 1393 } else if (v instanceof int[]) { 1394 writeInt(VAL_INTARRAY); 1395 writeIntArray((int[]) v); 1396 } else if (v instanceof long[]) { 1397 writeInt(VAL_LONGARRAY); 1398 writeLongArray((long[]) v); 1399 } else if (v instanceof Byte) { 1400 writeInt(VAL_BYTE); 1401 writeInt((Byte) v); 1402 } else if (v instanceof PersistableBundle) { 1403 writeInt(VAL_PERSISTABLEBUNDLE); 1404 writePersistableBundle((PersistableBundle) v); 1405 } else if (v instanceof Size) { 1406 writeInt(VAL_SIZE); 1407 writeSize((Size) v); 1408 } else if (v instanceof SizeF) { 1409 writeInt(VAL_SIZEF); 1410 writeSizeF((SizeF) v); 1411 } else { 1412 Class<?> clazz = v.getClass(); 1413 if (clazz.isArray() && clazz.getComponentType() == Object.class) { 1414 // Only pure Object[] are written here, Other arrays of non-primitive types are 1415 // handled by serialization as this does not record the component type. 1416 writeInt(VAL_OBJECTARRAY); 1417 writeArray((Object[]) v); 1418 } else if (v instanceof Serializable) { 1419 // Must be last 1420 writeInt(VAL_SERIALIZABLE); 1421 writeSerializable((Serializable) v); 1422 } else { 1423 throw new RuntimeException("Parcel: unable to marshal value " + v); 1424 } 1425 } 1426 } 1427 1428 /** 1429 * Flatten the name of the class of the Parcelable and its contents 1430 * into the parcel. 1431 * 1432 * @param p The Parcelable object to be written. 1433 * @param parcelableFlags Contextual flags as per 1434 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}. 1435 */ 1436 public final void writeParcelable(Parcelable p, int parcelableFlags) { 1437 if (p == null) { 1438 writeString(null); 1439 return; 1440 } 1441 writeParcelableCreator(p); 1442 p.writeToParcel(this, parcelableFlags); 1443 } 1444 1445 /** @hide */ 1446 public final void writeParcelableCreator(Parcelable p) { 1447 String name = p.getClass().getName(); 1448 writeString(name); 1449 } 1450 1451 /** 1452 * Write a generic serializable object in to a Parcel. It is strongly 1453 * recommended that this method be avoided, since the serialization 1454 * overhead is extremely large, and this approach will be much slower than 1455 * using the other approaches to writing data in to a Parcel. 1456 */ 1457 public final void writeSerializable(Serializable s) { 1458 if (s == null) { 1459 writeString(null); 1460 return; 1461 } 1462 String name = s.getClass().getName(); 1463 writeString(name); 1464 1465 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 1466 try { 1467 ObjectOutputStream oos = new ObjectOutputStream(baos); 1468 oos.writeObject(s); 1469 oos.close(); 1470 1471 writeByteArray(baos.toByteArray()); 1472 } catch (IOException ioe) { 1473 throw new RuntimeException("Parcelable encountered " + 1474 "IOException writing serializable object (name = " + name + 1475 ")", ioe); 1476 } 1477 } 1478 1479 /** 1480 * Special function for writing an exception result at the header of 1481 * a parcel, to be used when returning an exception from a transaction. 1482 * Note that this currently only supports a few exception types; any other 1483 * exception will be re-thrown by this function as a RuntimeException 1484 * (to be caught by the system's last-resort exception handling when 1485 * dispatching a transaction). 1486 * 1487 * <p>The supported exception types are: 1488 * <ul> 1489 * <li>{@link BadParcelableException} 1490 * <li>{@link IllegalArgumentException} 1491 * <li>{@link IllegalStateException} 1492 * <li>{@link NullPointerException} 1493 * <li>{@link SecurityException} 1494 * <li>{@link NetworkOnMainThreadException} 1495 * </ul> 1496 * 1497 * @param e The Exception to be written. 1498 * 1499 * @see #writeNoException 1500 * @see #readException 1501 */ 1502 public final void writeException(Exception e) { 1503 int code = 0; 1504 if (e instanceof SecurityException) { 1505 code = EX_SECURITY; 1506 } else if (e instanceof BadParcelableException) { 1507 code = EX_BAD_PARCELABLE; 1508 } else if (e instanceof IllegalArgumentException) { 1509 code = EX_ILLEGAL_ARGUMENT; 1510 } else if (e instanceof NullPointerException) { 1511 code = EX_NULL_POINTER; 1512 } else if (e instanceof IllegalStateException) { 1513 code = EX_ILLEGAL_STATE; 1514 } else if (e instanceof NetworkOnMainThreadException) { 1515 code = EX_NETWORK_MAIN_THREAD; 1516 } else if (e instanceof UnsupportedOperationException) { 1517 code = EX_UNSUPPORTED_OPERATION; 1518 } 1519 writeInt(code); 1520 StrictMode.clearGatheredViolations(); 1521 if (code == 0) { 1522 if (e instanceof RuntimeException) { 1523 throw (RuntimeException) e; 1524 } 1525 throw new RuntimeException(e); 1526 } 1527 writeString(e.getMessage()); 1528 } 1529 1530 /** 1531 * Special function for writing information at the front of the Parcel 1532 * indicating that no exception occurred. 1533 * 1534 * @see #writeException 1535 * @see #readException 1536 */ 1537 public final void writeNoException() { 1538 // Despite the name of this function ("write no exception"), 1539 // it should instead be thought of as "write the RPC response 1540 // header", but because this function name is written out by 1541 // the AIDL compiler, we're not going to rename it. 1542 // 1543 // The response header, in the non-exception case (see also 1544 // writeException above, also called by the AIDL compiler), is 1545 // either a 0 (the default case), or EX_HAS_REPLY_HEADER if 1546 // StrictMode has gathered up violations that have occurred 1547 // during a Binder call, in which case we write out the number 1548 // of violations and their details, serialized, before the 1549 // actual RPC respons data. The receiving end of this is 1550 // readException(), below. 1551 if (StrictMode.hasGatheredViolations()) { 1552 writeInt(EX_HAS_REPLY_HEADER); 1553 final int sizePosition = dataPosition(); 1554 writeInt(0); // total size of fat header, to be filled in later 1555 StrictMode.writeGatheredViolationsToParcel(this); 1556 final int payloadPosition = dataPosition(); 1557 setDataPosition(sizePosition); 1558 writeInt(payloadPosition - sizePosition); // header size 1559 setDataPosition(payloadPosition); 1560 } else { 1561 writeInt(0); 1562 } 1563 } 1564 1565 /** 1566 * Special function for reading an exception result from the header of 1567 * a parcel, to be used after receiving the result of a transaction. This 1568 * will throw the exception for you if it had been written to the Parcel, 1569 * otherwise return and let you read the normal result data from the Parcel. 1570 * 1571 * @see #writeException 1572 * @see #writeNoException 1573 */ 1574 public final void readException() { 1575 int code = readExceptionCode(); 1576 if (code != 0) { 1577 String msg = readString(); 1578 readException(code, msg); 1579 } 1580 } 1581 1582 /** 1583 * Parses the header of a Binder call's response Parcel and 1584 * returns the exception code. Deals with lite or fat headers. 1585 * In the common successful case, this header is generally zero. 1586 * In less common cases, it's a small negative number and will be 1587 * followed by an error string. 1588 * 1589 * This exists purely for android.database.DatabaseUtils and 1590 * insulating it from having to handle fat headers as returned by 1591 * e.g. StrictMode-induced RPC responses. 1592 * 1593 * @hide 1594 */ 1595 public final int readExceptionCode() { 1596 int code = readInt(); 1597 if (code == EX_HAS_REPLY_HEADER) { 1598 int headerSize = readInt(); 1599 if (headerSize == 0) { 1600 Log.e(TAG, "Unexpected zero-sized Parcel reply header."); 1601 } else { 1602 // Currently the only thing in the header is StrictMode stacks, 1603 // but discussions around event/RPC tracing suggest we might 1604 // put that here too. If so, switch on sub-header tags here. 1605 // But for now, just parse out the StrictMode stuff. 1606 StrictMode.readAndHandleBinderCallViolations(this); 1607 } 1608 // And fat response headers are currently only used when 1609 // there are no exceptions, so return no error: 1610 return 0; 1611 } 1612 return code; 1613 } 1614 1615 /** 1616 * Throw an exception with the given message. Not intended for use 1617 * outside the Parcel class. 1618 * 1619 * @param code Used to determine which exception class to throw. 1620 * @param msg The exception message. 1621 */ 1622 public final void readException(int code, String msg) { 1623 switch (code) { 1624 case EX_SECURITY: 1625 throw new SecurityException(msg); 1626 case EX_BAD_PARCELABLE: 1627 throw new BadParcelableException(msg); 1628 case EX_ILLEGAL_ARGUMENT: 1629 throw new IllegalArgumentException(msg); 1630 case EX_NULL_POINTER: 1631 throw new NullPointerException(msg); 1632 case EX_ILLEGAL_STATE: 1633 throw new IllegalStateException(msg); 1634 case EX_NETWORK_MAIN_THREAD: 1635 throw new NetworkOnMainThreadException(); 1636 case EX_UNSUPPORTED_OPERATION: 1637 throw new UnsupportedOperationException(msg); 1638 } 1639 throw new RuntimeException("Unknown exception code: " + code 1640 + " msg " + msg); 1641 } 1642 1643 /** 1644 * Read an integer value from the parcel at the current dataPosition(). 1645 */ 1646 public final int readInt() { 1647 return nativeReadInt(mNativePtr); 1648 } 1649 1650 /** 1651 * Read a long integer value from the parcel at the current dataPosition(). 1652 */ 1653 public final long readLong() { 1654 return nativeReadLong(mNativePtr); 1655 } 1656 1657 /** 1658 * Read a floating point value from the parcel at the current 1659 * dataPosition(). 1660 */ 1661 public final float readFloat() { 1662 return nativeReadFloat(mNativePtr); 1663 } 1664 1665 /** 1666 * Read a double precision floating point value from the parcel at the 1667 * current dataPosition(). 1668 */ 1669 public final double readDouble() { 1670 return nativeReadDouble(mNativePtr); 1671 } 1672 1673 /** 1674 * Read a string value from the parcel at the current dataPosition(). 1675 */ 1676 public final String readString() { 1677 return nativeReadString(mNativePtr); 1678 } 1679 1680 /** 1681 * Read a CharSequence value from the parcel at the current dataPosition(). 1682 * @hide 1683 */ 1684 public final CharSequence readCharSequence() { 1685 return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(this); 1686 } 1687 1688 /** 1689 * Read an object from the parcel at the current dataPosition(). 1690 */ 1691 public final IBinder readStrongBinder() { 1692 return nativeReadStrongBinder(mNativePtr); 1693 } 1694 1695 /** 1696 * Read a FileDescriptor from the parcel at the current dataPosition(). 1697 */ 1698 public final ParcelFileDescriptor readFileDescriptor() { 1699 FileDescriptor fd = nativeReadFileDescriptor(mNativePtr); 1700 return fd != null ? new ParcelFileDescriptor(fd) : null; 1701 } 1702 1703 /** {@hide} */ 1704 public final FileDescriptor readRawFileDescriptor() { 1705 return nativeReadFileDescriptor(mNativePtr); 1706 } 1707 1708 /** 1709 * {@hide} 1710 * Read and return a new array of FileDescriptors from the parcel. 1711 * @return the FileDescriptor array, or null if the array is null. 1712 **/ 1713 public final FileDescriptor[] createRawFileDescriptorArray() { 1714 int N = readInt(); 1715 if (N < 0) { 1716 return null; 1717 } 1718 FileDescriptor[] f = new FileDescriptor[N]; 1719 for (int i = 0; i < N; i++) { 1720 f[i] = readRawFileDescriptor(); 1721 } 1722 return f; 1723 } 1724 1725 /** 1726 * {@hide} 1727 * Read an array of FileDescriptors from a parcel. 1728 * The passed array must be exactly the length of the array in the parcel. 1729 * @return the FileDescriptor array, or null if the array is null. 1730 **/ 1731 public final void readRawFileDescriptorArray(FileDescriptor[] val) { 1732 int N = readInt(); 1733 if (N == val.length) { 1734 for (int i=0; i<N; i++) { 1735 val[i] = readRawFileDescriptor(); 1736 } 1737 } else { 1738 throw new RuntimeException("bad array lengths"); 1739 } 1740 } 1741 1742 1743 /*package*/ static native FileDescriptor openFileDescriptor(String file, 1744 int mode) throws FileNotFoundException; 1745 /*package*/ static native FileDescriptor dupFileDescriptor(FileDescriptor orig) 1746 throws IOException; 1747 /*package*/ static native void closeFileDescriptor(FileDescriptor desc) 1748 throws IOException; 1749 /*package*/ static native void clearFileDescriptor(FileDescriptor desc); 1750 1751 /** 1752 * Read a byte value from the parcel at the current dataPosition(). 1753 */ 1754 public final byte readByte() { 1755 return (byte)(readInt() & 0xff); 1756 } 1757 1758 /** 1759 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have 1760 * been written with {@link #writeBundle}. Read into an existing Map object 1761 * from the parcel at the current dataPosition(). 1762 */ 1763 public final void readMap(Map outVal, ClassLoader loader) { 1764 int N = readInt(); 1765 readMapInternal(outVal, N, loader); 1766 } 1767 1768 /** 1769 * Read into an existing List object from the parcel at the current 1770 * dataPosition(), using the given class loader to load any enclosed 1771 * Parcelables. If it is null, the default class loader is used. 1772 */ 1773 public final void readList(List outVal, ClassLoader loader) { 1774 int N = readInt(); 1775 readListInternal(outVal, N, loader); 1776 } 1777 1778 /** 1779 * Please use {@link #readBundle(ClassLoader)} instead (whose data must have 1780 * been written with {@link #writeBundle}. Read and return a new HashMap 1781 * object from the parcel at the current dataPosition(), using the given 1782 * class loader to load any enclosed Parcelables. Returns null if 1783 * the previously written map object was null. 1784 */ 1785 public final HashMap readHashMap(ClassLoader loader) 1786 { 1787 int N = readInt(); 1788 if (N < 0) { 1789 return null; 1790 } 1791 HashMap m = new HashMap(N); 1792 readMapInternal(m, N, loader); 1793 return m; 1794 } 1795 1796 /** 1797 * Read and return a new Bundle object from the parcel at the current 1798 * dataPosition(). Returns null if the previously written Bundle object was 1799 * null. 1800 */ 1801 public final Bundle readBundle() { 1802 return readBundle(null); 1803 } 1804 1805 /** 1806 * Read and return a new Bundle object from the parcel at the current 1807 * dataPosition(), using the given class loader to initialize the class 1808 * loader of the Bundle for later retrieval of Parcelable objects. 1809 * Returns null if the previously written Bundle object was null. 1810 */ 1811 public final Bundle readBundle(ClassLoader loader) { 1812 int length = readInt(); 1813 if (length < 0) { 1814 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length); 1815 return null; 1816 } 1817 1818 final Bundle bundle = new Bundle(this, length); 1819 if (loader != null) { 1820 bundle.setClassLoader(loader); 1821 } 1822 return bundle; 1823 } 1824 1825 /** 1826 * Read and return a new Bundle object from the parcel at the current 1827 * dataPosition(). Returns null if the previously written Bundle object was 1828 * null. 1829 */ 1830 public final PersistableBundle readPersistableBundle() { 1831 return readPersistableBundle(null); 1832 } 1833 1834 /** 1835 * Read and return a new Bundle object from the parcel at the current 1836 * dataPosition(), using the given class loader to initialize the class 1837 * loader of the Bundle for later retrieval of Parcelable objects. 1838 * Returns null if the previously written Bundle object was null. 1839 */ 1840 public final PersistableBundle readPersistableBundle(ClassLoader loader) { 1841 int length = readInt(); 1842 if (length < 0) { 1843 if (Bundle.DEBUG) Log.d(TAG, "null bundle: length=" + length); 1844 return null; 1845 } 1846 1847 final PersistableBundle bundle = new PersistableBundle(this, length); 1848 if (loader != null) { 1849 bundle.setClassLoader(loader); 1850 } 1851 return bundle; 1852 } 1853 1854 /** 1855 * Read a Size from the parcel at the current dataPosition(). 1856 */ 1857 public final Size readSize() { 1858 final int width = readInt(); 1859 final int height = readInt(); 1860 return new Size(width, height); 1861 } 1862 1863 /** 1864 * Read a SizeF from the parcel at the current dataPosition(). 1865 */ 1866 public final SizeF readSizeF() { 1867 final float width = readFloat(); 1868 final float height = readFloat(); 1869 return new SizeF(width, height); 1870 } 1871 1872 /** 1873 * Read and return a byte[] object from the parcel. 1874 */ 1875 public final byte[] createByteArray() { 1876 return nativeCreateByteArray(mNativePtr); 1877 } 1878 1879 /** 1880 * Read a byte[] object from the parcel and copy it into the 1881 * given byte array. 1882 */ 1883 public final void readByteArray(byte[] val) { 1884 // TODO: make this a native method to avoid the extra copy. 1885 byte[] ba = createByteArray(); 1886 if (ba.length == val.length) { 1887 System.arraycopy(ba, 0, val, 0, ba.length); 1888 } else { 1889 throw new RuntimeException("bad array lengths"); 1890 } 1891 } 1892 1893 /** 1894 * Read a blob of data from the parcel and return it as a byte array. 1895 * {@hide} 1896 * {@SystemApi} 1897 */ 1898 public final byte[] readBlob() { 1899 return nativeReadBlob(mNativePtr); 1900 } 1901 1902 /** 1903 * Read and return a String[] object from the parcel. 1904 * {@hide} 1905 */ 1906 public final String[] readStringArray() { 1907 String[] array = null; 1908 1909 int length = readInt(); 1910 if (length >= 0) 1911 { 1912 array = new String[length]; 1913 1914 for (int i = 0 ; i < length ; i++) 1915 { 1916 array[i] = readString(); 1917 } 1918 } 1919 1920 return array; 1921 } 1922 1923 /** 1924 * Read and return a CharSequence[] object from the parcel. 1925 * {@hide} 1926 */ 1927 public final CharSequence[] readCharSequenceArray() { 1928 CharSequence[] array = null; 1929 1930 int length = readInt(); 1931 if (length >= 0) 1932 { 1933 array = new CharSequence[length]; 1934 1935 for (int i = 0 ; i < length ; i++) 1936 { 1937 array[i] = readCharSequence(); 1938 } 1939 } 1940 1941 return array; 1942 } 1943 1944 /** 1945 * Read and return an ArrayList<CharSequence> object from the parcel. 1946 * {@hide} 1947 */ 1948 public final ArrayList<CharSequence> readCharSequenceList() { 1949 ArrayList<CharSequence> array = null; 1950 1951 int length = readInt(); 1952 if (length >= 0) { 1953 array = new ArrayList<CharSequence>(length); 1954 1955 for (int i = 0 ; i < length ; i++) { 1956 array.add(readCharSequence()); 1957 } 1958 } 1959 1960 return array; 1961 } 1962 1963 /** 1964 * Read and return a new ArrayList object from the parcel at the current 1965 * dataPosition(). Returns null if the previously written list object was 1966 * null. The given class loader will be used to load any enclosed 1967 * Parcelables. 1968 */ 1969 public final ArrayList readArrayList(ClassLoader loader) { 1970 int N = readInt(); 1971 if (N < 0) { 1972 return null; 1973 } 1974 ArrayList l = new ArrayList(N); 1975 readListInternal(l, N, loader); 1976 return l; 1977 } 1978 1979 /** 1980 * Read and return a new Object array from the parcel at the current 1981 * dataPosition(). Returns null if the previously written array was 1982 * null. The given class loader will be used to load any enclosed 1983 * Parcelables. 1984 */ 1985 public final Object[] readArray(ClassLoader loader) { 1986 int N = readInt(); 1987 if (N < 0) { 1988 return null; 1989 } 1990 Object[] l = new Object[N]; 1991 readArrayInternal(l, N, loader); 1992 return l; 1993 } 1994 1995 /** 1996 * Read and return a new SparseArray object from the parcel at the current 1997 * dataPosition(). Returns null if the previously written list object was 1998 * null. The given class loader will be used to load any enclosed 1999 * Parcelables. 2000 */ 2001 public final SparseArray readSparseArray(ClassLoader loader) { 2002 int N = readInt(); 2003 if (N < 0) { 2004 return null; 2005 } 2006 SparseArray sa = new SparseArray(N); 2007 readSparseArrayInternal(sa, N, loader); 2008 return sa; 2009 } 2010 2011 /** 2012 * Read and return a new SparseBooleanArray object from the parcel at the current 2013 * dataPosition(). Returns null if the previously written list object was 2014 * null. 2015 */ 2016 public final SparseBooleanArray readSparseBooleanArray() { 2017 int N = readInt(); 2018 if (N < 0) { 2019 return null; 2020 } 2021 SparseBooleanArray sa = new SparseBooleanArray(N); 2022 readSparseBooleanArrayInternal(sa, N); 2023 return sa; 2024 } 2025 2026 /** 2027 * Read and return a new ArrayList containing a particular object type from 2028 * the parcel that was written with {@link #writeTypedList} at the 2029 * current dataPosition(). Returns null if the 2030 * previously written list object was null. The list <em>must</em> have 2031 * previously been written via {@link #writeTypedList} with the same object 2032 * type. 2033 * 2034 * @return A newly created ArrayList containing objects with the same data 2035 * as those that were previously written. 2036 * 2037 * @see #writeTypedList 2038 */ 2039 public final <T> ArrayList<T> createTypedArrayList(Parcelable.Creator<T> c) { 2040 int N = readInt(); 2041 if (N < 0) { 2042 return null; 2043 } 2044 ArrayList<T> l = new ArrayList<T>(N); 2045 while (N > 0) { 2046 if (readInt() != 0) { 2047 l.add(c.createFromParcel(this)); 2048 } else { 2049 l.add(null); 2050 } 2051 N--; 2052 } 2053 return l; 2054 } 2055 2056 /** 2057 * Read into the given List items containing a particular object type 2058 * that were written with {@link #writeTypedList} at the 2059 * current dataPosition(). The list <em>must</em> have 2060 * previously been written via {@link #writeTypedList} with the same object 2061 * type. 2062 * 2063 * @return A newly created ArrayList containing objects with the same data 2064 * as those that were previously written. 2065 * 2066 * @see #writeTypedList 2067 */ 2068 public final <T> void readTypedList(List<T> list, Parcelable.Creator<T> c) { 2069 int M = list.size(); 2070 int N = readInt(); 2071 int i = 0; 2072 for (; i < M && i < N; i++) { 2073 if (readInt() != 0) { 2074 list.set(i, c.createFromParcel(this)); 2075 } else { 2076 list.set(i, null); 2077 } 2078 } 2079 for (; i<N; i++) { 2080 if (readInt() != 0) { 2081 list.add(c.createFromParcel(this)); 2082 } else { 2083 list.add(null); 2084 } 2085 } 2086 for (; i<M; i++) { 2087 list.remove(N); 2088 } 2089 } 2090 2091 /** 2092 * Read and return a new ArrayList containing String objects from 2093 * the parcel that was written with {@link #writeStringList} at the 2094 * current dataPosition(). Returns null if the 2095 * previously written list object was null. 2096 * 2097 * @return A newly created ArrayList containing strings with the same data 2098 * as those that were previously written. 2099 * 2100 * @see #writeStringList 2101 */ 2102 public final ArrayList<String> createStringArrayList() { 2103 int N = readInt(); 2104 if (N < 0) { 2105 return null; 2106 } 2107 ArrayList<String> l = new ArrayList<String>(N); 2108 while (N > 0) { 2109 l.add(readString()); 2110 N--; 2111 } 2112 return l; 2113 } 2114 2115 /** 2116 * Read and return a new ArrayList containing IBinder objects from 2117 * the parcel that was written with {@link #writeBinderList} at the 2118 * current dataPosition(). Returns null if the 2119 * previously written list object was null. 2120 * 2121 * @return A newly created ArrayList containing strings with the same data 2122 * as those that were previously written. 2123 * 2124 * @see #writeBinderList 2125 */ 2126 public final ArrayList<IBinder> createBinderArrayList() { 2127 int N = readInt(); 2128 if (N < 0) { 2129 return null; 2130 } 2131 ArrayList<IBinder> l = new ArrayList<IBinder>(N); 2132 while (N > 0) { 2133 l.add(readStrongBinder()); 2134 N--; 2135 } 2136 return l; 2137 } 2138 2139 /** 2140 * Read into the given List items String objects that were written with 2141 * {@link #writeStringList} at the current dataPosition(). 2142 * 2143 * @return A newly created ArrayList containing strings with the same data 2144 * as those that were previously written. 2145 * 2146 * @see #writeStringList 2147 */ 2148 public final void readStringList(List<String> list) { 2149 int M = list.size(); 2150 int N = readInt(); 2151 int i = 0; 2152 for (; i < M && i < N; i++) { 2153 list.set(i, readString()); 2154 } 2155 for (; i<N; i++) { 2156 list.add(readString()); 2157 } 2158 for (; i<M; i++) { 2159 list.remove(N); 2160 } 2161 } 2162 2163 /** 2164 * Read into the given List items IBinder objects that were written with 2165 * {@link #writeBinderList} at the current dataPosition(). 2166 * 2167 * @return A newly created ArrayList containing strings with the same data 2168 * as those that were previously written. 2169 * 2170 * @see #writeBinderList 2171 */ 2172 public final void readBinderList(List<IBinder> list) { 2173 int M = list.size(); 2174 int N = readInt(); 2175 int i = 0; 2176 for (; i < M && i < N; i++) { 2177 list.set(i, readStrongBinder()); 2178 } 2179 for (; i<N; i++) { 2180 list.add(readStrongBinder()); 2181 } 2182 for (; i<M; i++) { 2183 list.remove(N); 2184 } 2185 } 2186 2187 /** 2188 * Read and return a new array containing a particular object type from 2189 * the parcel at the current dataPosition(). Returns null if the 2190 * previously written array was null. The array <em>must</em> have 2191 * previously been written via {@link #writeTypedArray} with the same 2192 * object type. 2193 * 2194 * @return A newly created array containing objects with the same data 2195 * as those that were previously written. 2196 * 2197 * @see #writeTypedArray 2198 */ 2199 public final <T> T[] createTypedArray(Parcelable.Creator<T> c) { 2200 int N = readInt(); 2201 if (N < 0) { 2202 return null; 2203 } 2204 T[] l = c.newArray(N); 2205 for (int i=0; i<N; i++) { 2206 if (readInt() != 0) { 2207 l[i] = c.createFromParcel(this); 2208 } 2209 } 2210 return l; 2211 } 2212 2213 public final <T> void readTypedArray(T[] val, Parcelable.Creator<T> c) { 2214 int N = readInt(); 2215 if (N == val.length) { 2216 for (int i=0; i<N; i++) { 2217 if (readInt() != 0) { 2218 val[i] = c.createFromParcel(this); 2219 } else { 2220 val[i] = null; 2221 } 2222 } 2223 } else { 2224 throw new RuntimeException("bad array lengths"); 2225 } 2226 } 2227 2228 /** 2229 * @deprecated 2230 * @hide 2231 */ 2232 @Deprecated 2233 public final <T> T[] readTypedArray(Parcelable.Creator<T> c) { 2234 return createTypedArray(c); 2235 } 2236 2237 /** 2238 * Read and return a typed Parcelable object from a parcel. 2239 * Returns null if the previous written object was null. 2240 * The object <em>must</em> have previous been written via 2241 * {@link #writeTypedObject} with the same object type. 2242 * 2243 * @return A newly created object of the type that was previously 2244 * written. 2245 * 2246 * @see #writeTypedObject 2247 */ 2248 public final <T> T readTypedObject(Parcelable.Creator<T> c) { 2249 if (readInt() != 0) { 2250 return c.createFromParcel(this); 2251 } else { 2252 return null; 2253 } 2254 } 2255 2256 /** 2257 * Write a heterogeneous array of Parcelable objects into the Parcel. 2258 * Each object in the array is written along with its class name, so 2259 * that the correct class can later be instantiated. As a result, this 2260 * has significantly more overhead than {@link #writeTypedArray}, but will 2261 * correctly handle an array containing more than one type of object. 2262 * 2263 * @param value The array of objects to be written. 2264 * @param parcelableFlags Contextual flags as per 2265 * {@link Parcelable#writeToParcel(Parcel, int) Parcelable.writeToParcel()}. 2266 * 2267 * @see #writeTypedArray 2268 */ 2269 public final <T extends Parcelable> void writeParcelableArray(T[] value, 2270 int parcelableFlags) { 2271 if (value != null) { 2272 int N = value.length; 2273 writeInt(N); 2274 for (int i=0; i<N; i++) { 2275 writeParcelable(value[i], parcelableFlags); 2276 } 2277 } else { 2278 writeInt(-1); 2279 } 2280 } 2281 2282 /** 2283 * Read a typed object from a parcel. The given class loader will be 2284 * used to load any enclosed Parcelables. If it is null, the default class 2285 * loader will be used. 2286 */ 2287 public final Object readValue(ClassLoader loader) { 2288 int type = readInt(); 2289 2290 switch (type) { 2291 case VAL_NULL: 2292 return null; 2293 2294 case VAL_STRING: 2295 return readString(); 2296 2297 case VAL_INTEGER: 2298 return readInt(); 2299 2300 case VAL_MAP: 2301 return readHashMap(loader); 2302 2303 case VAL_PARCELABLE: 2304 return readParcelable(loader); 2305 2306 case VAL_SHORT: 2307 return (short) readInt(); 2308 2309 case VAL_LONG: 2310 return readLong(); 2311 2312 case VAL_FLOAT: 2313 return readFloat(); 2314 2315 case VAL_DOUBLE: 2316 return readDouble(); 2317 2318 case VAL_BOOLEAN: 2319 return readInt() == 1; 2320 2321 case VAL_CHARSEQUENCE: 2322 return readCharSequence(); 2323 2324 case VAL_LIST: 2325 return readArrayList(loader); 2326 2327 case VAL_BOOLEANARRAY: 2328 return createBooleanArray(); 2329 2330 case VAL_BYTEARRAY: 2331 return createByteArray(); 2332 2333 case VAL_STRINGARRAY: 2334 return readStringArray(); 2335 2336 case VAL_CHARSEQUENCEARRAY: 2337 return readCharSequenceArray(); 2338 2339 case VAL_IBINDER: 2340 return readStrongBinder(); 2341 2342 case VAL_OBJECTARRAY: 2343 return readArray(loader); 2344 2345 case VAL_INTARRAY: 2346 return createIntArray(); 2347 2348 case VAL_LONGARRAY: 2349 return createLongArray(); 2350 2351 case VAL_BYTE: 2352 return readByte(); 2353 2354 case VAL_SERIALIZABLE: 2355 return readSerializable(loader); 2356 2357 case VAL_PARCELABLEARRAY: 2358 return readParcelableArray(loader); 2359 2360 case VAL_SPARSEARRAY: 2361 return readSparseArray(loader); 2362 2363 case VAL_SPARSEBOOLEANARRAY: 2364 return readSparseBooleanArray(); 2365 2366 case VAL_BUNDLE: 2367 return readBundle(loader); // loading will be deferred 2368 2369 case VAL_PERSISTABLEBUNDLE: 2370 return readPersistableBundle(loader); 2371 2372 case VAL_SIZE: 2373 return readSize(); 2374 2375 case VAL_SIZEF: 2376 return readSizeF(); 2377 2378 default: 2379 int off = dataPosition() - 4; 2380 throw new RuntimeException( 2381 "Parcel " + this + ": Unmarshalling unknown type code " + type + " at offset " + off); 2382 } 2383 } 2384 2385 /** 2386 * Read and return a new Parcelable from the parcel. The given class loader 2387 * will be used to load any enclosed Parcelables. If it is null, the default 2388 * class loader will be used. 2389 * @param loader A ClassLoader from which to instantiate the Parcelable 2390 * object, or null for the default class loader. 2391 * @return Returns the newly created Parcelable, or null if a null 2392 * object has been written. 2393 * @throws BadParcelableException Throws BadParcelableException if there 2394 * was an error trying to instantiate the Parcelable. 2395 */ 2396 @SuppressWarnings("unchecked") 2397 public final <T extends Parcelable> T readParcelable(ClassLoader loader) { 2398 Parcelable.Creator<?> creator = readParcelableCreator(loader); 2399 if (creator == null) { 2400 return null; 2401 } 2402 if (creator instanceof Parcelable.ClassLoaderCreator<?>) { 2403 Parcelable.ClassLoaderCreator<?> classLoaderCreator = 2404 (Parcelable.ClassLoaderCreator<?>) creator; 2405 return (T) classLoaderCreator.createFromParcel(this, loader); 2406 } 2407 return (T) creator.createFromParcel(this); 2408 } 2409 2410 /** @hide */ 2411 @SuppressWarnings("unchecked") 2412 public final <T extends Parcelable> T readCreator(Parcelable.Creator<?> creator, 2413 ClassLoader loader) { 2414 if (creator instanceof Parcelable.ClassLoaderCreator<?>) { 2415 Parcelable.ClassLoaderCreator<?> classLoaderCreator = 2416 (Parcelable.ClassLoaderCreator<?>) creator; 2417 return (T) classLoaderCreator.createFromParcel(this, loader); 2418 } 2419 return (T) creator.createFromParcel(this); 2420 } 2421 2422 /** @hide */ 2423 public final Parcelable.Creator<?> readParcelableCreator(ClassLoader loader) { 2424 String name = readString(); 2425 if (name == null) { 2426 return null; 2427 } 2428 Parcelable.Creator<?> creator; 2429 synchronized (mCreators) { 2430 HashMap<String,Parcelable.Creator<?>> map = mCreators.get(loader); 2431 if (map == null) { 2432 map = new HashMap<>(); 2433 mCreators.put(loader, map); 2434 } 2435 creator = map.get(name); 2436 if (creator == null) { 2437 try { 2438 // If loader == null, explicitly emulate Class.forName(String) "caller 2439 // classloader" behavior. 2440 ClassLoader parcelableClassLoader = 2441 (loader == null ? getClass().getClassLoader() : loader); 2442 // Avoid initializing the Parcelable class until we know it implements 2443 // Parcelable and has the necessary CREATOR field. http://b/1171613. 2444 Class<?> parcelableClass = Class.forName(name, false /* initialize */, 2445 parcelableClassLoader); 2446 if (!Parcelable.class.isAssignableFrom(parcelableClass)) { 2447 throw new BadParcelableException("Parcelable protocol requires that the " 2448 + "class implements Parcelable"); 2449 } 2450 Field f = parcelableClass.getField("CREATOR"); 2451 if ((f.getModifiers() & Modifier.STATIC) == 0) { 2452 throw new BadParcelableException("Parcelable protocol requires " 2453 + "the CREATOR object to be static on class " + name); 2454 } 2455 Class<?> creatorType = f.getType(); 2456 if (!Parcelable.Creator.class.isAssignableFrom(creatorType)) { 2457 // Fail before calling Field.get(), not after, to avoid initializing 2458 // parcelableClass unnecessarily. 2459 throw new BadParcelableException("Parcelable protocol requires a " 2460 + "Parcelable.Creator object called " 2461 + "CREATOR on class " + name); 2462 } 2463 creator = (Parcelable.Creator<?>) f.get(null); 2464 } 2465 catch (IllegalAccessException e) { 2466 Log.e(TAG, "Illegal access when unmarshalling: " + name, e); 2467 throw new BadParcelableException( 2468 "IllegalAccessException when unmarshalling: " + name); 2469 } 2470 catch (ClassNotFoundException e) { 2471 Log.e(TAG, "Class not found when unmarshalling: " + name, e); 2472 throw new BadParcelableException( 2473 "ClassNotFoundException when unmarshalling: " + name); 2474 } 2475 catch (NoSuchFieldException e) { 2476 throw new BadParcelableException("Parcelable protocol requires a " 2477 + "Parcelable.Creator object called " 2478 + "CREATOR on class " + name); 2479 } 2480 if (creator == null) { 2481 throw new BadParcelableException("Parcelable protocol requires a " 2482 + "non-null Parcelable.Creator object called " 2483 + "CREATOR on class " + name); 2484 } 2485 2486 map.put(name, creator); 2487 } 2488 } 2489 2490 return creator; 2491 } 2492 2493 /** 2494 * Read and return a new Parcelable array from the parcel. 2495 * The given class loader will be used to load any enclosed 2496 * Parcelables. 2497 * @return the Parcelable array, or null if the array is null 2498 */ 2499 public final Parcelable[] readParcelableArray(ClassLoader loader) { 2500 int N = readInt(); 2501 if (N < 0) { 2502 return null; 2503 } 2504 Parcelable[] p = new Parcelable[N]; 2505 for (int i = 0; i < N; i++) { 2506 p[i] = readParcelable(loader); 2507 } 2508 return p; 2509 } 2510 2511 /** 2512 * Read and return a new Serializable object from the parcel. 2513 * @return the Serializable object, or null if the Serializable name 2514 * wasn't found in the parcel. 2515 */ 2516 public final Serializable readSerializable() { 2517 return readSerializable(null); 2518 } 2519 2520 private final Serializable readSerializable(final ClassLoader loader) { 2521 String name = readString(); 2522 if (name == null) { 2523 // For some reason we were unable to read the name of the Serializable (either there 2524 // is nothing left in the Parcel to read, or the next value wasn't a String), so 2525 // return null, which indicates that the name wasn't found in the parcel. 2526 return null; 2527 } 2528 2529 byte[] serializedData = createByteArray(); 2530 ByteArrayInputStream bais = new ByteArrayInputStream(serializedData); 2531 try { 2532 ObjectInputStream ois = new ObjectInputStream(bais) { 2533 @Override 2534 protected Class<?> resolveClass(ObjectStreamClass osClass) 2535 throws IOException, ClassNotFoundException { 2536 // try the custom classloader if provided 2537 if (loader != null) { 2538 Class<?> c = Class.forName(osClass.getName(), false, loader); 2539 if (c != null) { 2540 return c; 2541 } 2542 } 2543 return super.resolveClass(osClass); 2544 } 2545 }; 2546 return (Serializable) ois.readObject(); 2547 } catch (IOException ioe) { 2548 throw new RuntimeException("Parcelable encountered " + 2549 "IOException reading a Serializable object (name = " + name + 2550 ")", ioe); 2551 } catch (ClassNotFoundException cnfe) { 2552 throw new RuntimeException("Parcelable encountered " + 2553 "ClassNotFoundException reading a Serializable object (name = " 2554 + name + ")", cnfe); 2555 } 2556 } 2557 2558 // Cache of previously looked up CREATOR.createFromParcel() methods for 2559 // particular classes. Keys are the names of the classes, values are 2560 // Method objects. 2561 private static final HashMap<ClassLoader,HashMap<String,Parcelable.Creator<?>>> 2562 mCreators = new HashMap<>(); 2563 2564 /** @hide for internal use only. */ 2565 static protected final Parcel obtain(int obj) { 2566 throw new UnsupportedOperationException(); 2567 } 2568 2569 /** @hide */ 2570 static protected final Parcel obtain(long obj) { 2571 final Parcel[] pool = sHolderPool; 2572 synchronized (pool) { 2573 Parcel p; 2574 for (int i=0; i<POOL_SIZE; i++) { 2575 p = pool[i]; 2576 if (p != null) { 2577 pool[i] = null; 2578 if (DEBUG_RECYCLE) { 2579 p.mStack = new RuntimeException(); 2580 } 2581 p.init(obj); 2582 return p; 2583 } 2584 } 2585 } 2586 return new Parcel(obj); 2587 } 2588 2589 private Parcel(long nativePtr) { 2590 if (DEBUG_RECYCLE) { 2591 mStack = new RuntimeException(); 2592 } 2593 //Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack); 2594 init(nativePtr); 2595 } 2596 2597 private void init(long nativePtr) { 2598 if (nativePtr != 0) { 2599 mNativePtr = nativePtr; 2600 mOwnsNativeParcelObject = false; 2601 } else { 2602 mNativePtr = nativeCreate(); 2603 mOwnsNativeParcelObject = true; 2604 } 2605 } 2606 2607 private void freeBuffer() { 2608 if (mOwnsNativeParcelObject) { 2609 nativeFreeBuffer(mNativePtr); 2610 } 2611 } 2612 2613 private void destroy() { 2614 if (mNativePtr != 0) { 2615 if (mOwnsNativeParcelObject) { 2616 nativeDestroy(mNativePtr); 2617 } 2618 mNativePtr = 0; 2619 } 2620 } 2621 2622 @Override 2623 protected void finalize() throws Throwable { 2624 if (DEBUG_RECYCLE) { 2625 if (mStack != null) { 2626 Log.w(TAG, "Client did not call Parcel.recycle()", mStack); 2627 } 2628 } 2629 destroy(); 2630 } 2631 2632 /* package */ void readMapInternal(Map outVal, int N, 2633 ClassLoader loader) { 2634 while (N > 0) { 2635 Object key = readValue(loader); 2636 Object value = readValue(loader); 2637 outVal.put(key, value); 2638 N--; 2639 } 2640 } 2641 2642 /* package */ void readArrayMapInternal(ArrayMap outVal, int N, 2643 ClassLoader loader) { 2644 if (DEBUG_ARRAY_MAP) { 2645 RuntimeException here = new RuntimeException("here"); 2646 here.fillInStackTrace(); 2647 Log.d(TAG, "Reading " + N + " ArrayMap entries", here); 2648 } 2649 int startPos; 2650 while (N > 0) { 2651 if (DEBUG_ARRAY_MAP) startPos = dataPosition(); 2652 String key = readString(); 2653 Object value = readValue(loader); 2654 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Read #" + (N-1) + " " 2655 + (dataPosition()-startPos) + " bytes: key=0x" 2656 + Integer.toHexString((key != null ? key.hashCode() : 0)) + " " + key); 2657 outVal.append(key, value); 2658 N--; 2659 } 2660 outVal.validate(); 2661 } 2662 2663 /* package */ void readArrayMapSafelyInternal(ArrayMap outVal, int N, 2664 ClassLoader loader) { 2665 if (DEBUG_ARRAY_MAP) { 2666 RuntimeException here = new RuntimeException("here"); 2667 here.fillInStackTrace(); 2668 Log.d(TAG, "Reading safely " + N + " ArrayMap entries", here); 2669 } 2670 while (N > 0) { 2671 String key = readString(); 2672 if (DEBUG_ARRAY_MAP) Log.d(TAG, " Read safe #" + (N-1) + ": key=0x" 2673 + (key != null ? key.hashCode() : 0) + " " + key); 2674 Object value = readValue(loader); 2675 outVal.put(key, value); 2676 N--; 2677 } 2678 } 2679 2680 /** 2681 * @hide For testing only. 2682 */ 2683 public void readArrayMap(ArrayMap outVal, ClassLoader loader) { 2684 final int N = readInt(); 2685 if (N < 0) { 2686 return; 2687 } 2688 readArrayMapInternal(outVal, N, loader); 2689 } 2690 2691 private void readListInternal(List outVal, int N, 2692 ClassLoader loader) { 2693 while (N > 0) { 2694 Object value = readValue(loader); 2695 //Log.d(TAG, "Unmarshalling value=" + value); 2696 outVal.add(value); 2697 N--; 2698 } 2699 } 2700 2701 private void readArrayInternal(Object[] outVal, int N, 2702 ClassLoader loader) { 2703 for (int i = 0; i < N; i++) { 2704 Object value = readValue(loader); 2705 //Log.d(TAG, "Unmarshalling value=" + value); 2706 outVal[i] = value; 2707 } 2708 } 2709 2710 private void readSparseArrayInternal(SparseArray outVal, int N, 2711 ClassLoader loader) { 2712 while (N > 0) { 2713 int key = readInt(); 2714 Object value = readValue(loader); 2715 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value); 2716 outVal.append(key, value); 2717 N--; 2718 } 2719 } 2720 2721 2722 private void readSparseBooleanArrayInternal(SparseBooleanArray outVal, int N) { 2723 while (N > 0) { 2724 int key = readInt(); 2725 boolean value = this.readByte() == 1; 2726 //Log.i(TAG, "Unmarshalling key=" + key + " value=" + value); 2727 outVal.append(key, value); 2728 N--; 2729 } 2730 } 2731 2732 /** 2733 * @hide For testing 2734 */ 2735 public long getBlobAshmemSize() { 2736 return nativeGetBlobAshmemSize(mNativePtr); 2737 } 2738} 2739