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