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