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