Android-那些年我们进过的坑-ByteBuffer导致的bug
2015-06-27 09:53
543 查看
Android-那些年我们进过的坑-ByteBuffer导致的bug
前几天发现这么一个问题,自己实现的序列化,按字节操作。5.0一直没测试,发现反序列化有问题,一直以为数据库的问题。折腾了一晚上。都知道在5.0 google做了好多优化。
我们使用了allocateDirect,debug发现5.0上出问题的时候offset不是0,而5.0一下的时候offset都是0
4.4中的源码
DirectByteBuffer第三个参数是offset,5.0一下是写死的
/** * Creates a direct byte buffer based on a newly allocated memory block. * * @param capacity * the capacity of the new buffer * @return the created byte buffer. * @throws IllegalArgumentException * if {@code capacity < 0}. */ public static ByteBuffer allocateDirect(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("capacity < 0: " + capacity); } return new DirectByteBuffer(MemoryBlock.allocate(capacity), capacity, 0, false, null); }
5.0的源码这样子
/** * Creates a direct byte buffer based on a newly allocated memory block. * * @param capacity * the capacity of the new buffer * @return the created byte buffer. * @throws IllegalArgumentException * if {@code capacity < 0}. */ public static ByteBuffer allocateDirect(int capacity) { if (capacity < 0) { throw new IllegalArgumentException("capacity < 0: " + capacity); } // Ensure alignment by 8. MemoryBlock memoryBlock = MemoryBlock.allocate(capacity + 7); long address = memoryBlock.toLong(); long alignedAddress = (address + 7) & ~(long)7; return new DirectByteBuffer(memoryBlock, capacity, (int)(alignedAddress - address), false, null); }
在5.0后 做了内存对齐alignedAddress - address,直接读取的字节array还是从地址最开始,导致读取了一堆0.反序列化就出问题了。
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories