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