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          };
微信扫码更精彩
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT_熊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值