Android AIDL传递包含枚举的自定义类型

AIDL使用过程中会遇到自定义类型的数据传输,自定义类型可能会包含枚举类型,使用错误,会出现各种错误:

E/JavaBinder: *** Uncaught remote exception!  (Exceptions are not yet supported across processes.)
    java.lang.ArrayIndexOutOfBoundsException: length=8; index=3014765
        at com.Data.(Data.java:96)
        at com.Data$1.createFromParcel(Data.java:116)
        at com.Data$1.createFromParcel(Data.java:113)
        at com.DataListener$Stub.onTransact(DataListener.java:65)
        at android.os.Binder.execTransactInternal(Binder.java:1154)
        at android.os.Binder.execTransact(Binder.java:1123)

整理了下使用枚举注意事项

  1. 定义枚举

     public enum CameraStatus {
         WORKING(0),
         CAMERA_FAILURE(1),
         UNRECOGNIZED(2);
       public static CameraStatus forNumber(int value) {
             switch (value) {
                 case 0:
                     return WORKING;
                 case 1:
                     return CAMERA_FAILURE;
                 default:
                     return UNRECOGNIZED;
             }
         }
      }
    
  2. 自定义类型添加枚举变量

     public class Data implements Parcelable {
         public Data () {
         }
         public int size;
         public boolean valid;
         public CameraStatus camera_status = CameraStatus.UNRECOGNIZED;
     }
    
  3. 修改writeToParcel和构造方法

    public void writeToParcel(Parcel dest, int flags) {
         dest.writeInt(size);
         dest.writeByte((byte) (valid? 1 : 0));
         dest.writeInt(camera_status.ordinal());
     }
    protected Data(Parcel in) {
         size= in.readInt();
         valid = in.readByte() != 0;
         camera_status = CameraStatus.values()[in.readInt()];
    

read和write顺序要对应上,不然会出问题。

你可能感兴趣的:(android,java,开发语言,AIDL,ENUM)