Andriod Parcel子类读写 boolean(布尔值)的一种写法

Andriod Parcelable Parcel在aidl通讯中经常用到,查看Parcel源码或者调用其读写方法。

readB方法列表:

writeB方法列表:

可以发现Parcel提供的方法中没有直接读写boolean类型的方法,可以看到读写BooleanArray的方法和Byte的相关方法。

这里主要推荐使用读写Byte方法,即,将布尔值转byte进行写,读的时候把byte还原为布尔值。

如:

dest.writeByte(groupFormed ? (byte)1 : (byte)0);
info.groupFormed = (in.readByte() == 1);

在android源码中可以找到相关的例子:

如:/frameworks/base/wifi/java/android/net/wifi/p2p/WifiP2pInfo.java

66      /** Implement the Parcelable interface */
67      public void writeToParcel(Parcel dest, int flags) {
68          dest.writeByte(groupFormed ? (byte)1 : (byte)0);
69          dest.writeByte(isGroupOwner ? (byte)1 : (byte)0);
70  
71          if (groupOwnerAddress != null) {
72              dest.writeByte((byte)1);
73              dest.writeByteArray(groupOwnerAddress.getAddress());
74          } else {
75              dest.writeByte((byte)0);
76          }
77      }
78  
79      /** Implement the Parcelable interface */
80      public static final Creator<WifiP2pInfo> CREATOR =
81          new Creator<WifiP2pInfo>() {
82              public WifiP2pInfo createFromParcel(Parcel in) {
83                  WifiP2pInfo info = new WifiP2pInfo();
84                  info.groupFormed = (in.readByte() == 1);
85                  info.isGroupOwner = (in.readByte() == 1);
86                  if (in.readByte() == 1) {
87                      try {
88                          info.groupOwnerAddress = InetAddress.getByAddress(in.createByteArray());
89                      } catch (UnknownHostException e) {}
90                  }
91                  return info;
92              }
93  
94              public WifiP2pInfo[] newArray(int size) {
95                  return new WifiP2pInfo[size];
96              }
97          };
微信扫码更精彩
发布了142 篇原创文章 · 获赞 258 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/conconbenben/article/details/103079600