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