Wire protocol buffers的好处
- 轻量级的protocol buffers,针对移动设备的java库。
- (和protoc产生的代码相比较)由Wire生成的代码方法数量将大大减少,这将有助于android应用避免方法数65k的限制。
- 用public final的字段代替常规的getter方法,对安卓系统来说代码越少越好。
使用准备:
1 在gradle里引入依赖的wire-runtime库
compile 'com.squareup.wire:wire-runtime:2.0.2'
2 在本地编译出bean文件,(可以批量编译)编译命令:
% java -jar wire-compiler-VERSION-jar-with-dependencies.jar \
--proto_path=src/main/proto \
--java_out=out \
例子:我常用的编译命令:
java -jar /Users/mtime/Downloads/wire-compiler-2.0.2-jar-with-dependencies.jar --proto_path=/Users/mtime/Desktop/wanda/Source/mtime_app/mTimeMovie/src/com/mtimex/app/protoNew --java_out=/Users/mtime/Desktop/out
把项目中放proto文件的文件夹一起编译出来,然后整个替换掉protobeans包
使用protobean的方法:
//new对象
ActorImage actorimage =new ActorImage.Builder().id(1).image("哈哈").type(2).build();
//对象转字节数组
byte[] actorimageBytes = ActorImage.ADAPTER.encode(actorimage);
//字节数组转对象
try {
ActorImage actorimage2 = ActorImage.ADAPTER.decode(actorimageBytes);
} catch (IOException e) {
e.printStackTrace();
}
当访问一个字段的时候使用Wire.get()相应的默认值去替换空值
Period period = Wire.get(stegosaurus.period, Dinosaur.DEFAULT_PERIOD);
或者这么写:
Period period = stegosaurus.period != null ? stegosaurus.period : Dinosaur.DEFAULT_PERIOD;
测试的时候不要用Wire.get(),调用的时候用Wire.get()可以防止空指针
混淆代码需注意:
If you use Proguard, then you need to add keep
rules. The simplest option is to tell Proguard not
to touch the Wire runtime library and your generated protocol buffers (of course these simple rules
will miss opportunities to shrink and optimize the code):
混淆的时候注意添加“keep”规则
-keep class com.squareup.wire.** { *; }
-keep class com.yourcompany.yourgeneratedcode.** { *; }