background
I encountered a requirement at work that needed to transfer pictures across processes. Android’s SharedMemory was used in the project. Here is a brief introduction to its use.
API to add this feature
API level 27
Class interface
See the official document
https://developer.android.google.cn/reference/android/os/SharedMemory?hl=en
Cross-process use (here to transfer picture bytes as an example)
1. The server creates and saves data:
// 1、使用文件流把文件读入到内存
FileInputStream inputStream = new FileInputStream(jpegFile);
byte[] bytes = new byte[(int) jpegFile.length()];
inputStream.read(bytes);
// 2、创建sharedMemory跨进程传输
SharedMemory sharedMemory = SharedMemory.create("test", bytes.length);
// 3、mapReadWrite获取ByteBuffer
ByteBuffer buffer = sharedMemory.mapReadWrite();
// 4、put数据
buffer.put(bytes);
// 5、把sharedMemory权限设置为只读,create默认是读写权限都有,这里可以避免客户端更改数据
sharedMemory.setProtect(OsConstants.PROT_READ);
// 6、使用完需要unmap
SharedMemory.unmap(buffer);
return sharedMemory;
Two, the client obtains data display
// 1、通过aidl拿到SharedMemory
SharedMemory sharedMemory = iService.takeScreenshot();
if (sharedMemory == null) {
return;
}
// 2、mapReadOnly获取到存了数据的ByteBuffer
ByteBuffer byteBuffer = sharedMemory.mapReadOnly();
int len = byteBuffer.limit() - byteBuffer.position();
byte[] bytes = new byte[len];
// 3、借助byteBuffer获取到数据
byteBuffer.get(bytes);
// 4、把字节转换成bitmap并显示到imageView
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
imageView.setVisibility(View.VISIBLE);
imageView.setImageBitmap(bitmap);
// 5、使用完unmap同时close sharedMemory释放内存
SharedMemory.unmap(byteBuffer);
sharedMemory.close();
Precautions
1. When the server service is destroyed, remember sharedMemory.close
2. When the server transmits sharedMemory, remember to setProtect(OsConstants.PROT_READ)
3. When the client finishes using sharedMemory, it is best to unmap to avoid memory occupation