Android – Creating Shared Memory using Ashmem

In API 27 , Google added SharedMemory class so applications can create and use shared memory using asmem (/dev/ashmem). Today, less than 1% of mobile devices work with API 27 (Android 8.1) so It is useless. In this post I will show you how to work with ashmem, creating and using shared memory between 2 untrusted applications (applications from the Play store) and it is working for API 15 and up (Android 4)

To support this , we will create an Android library, Server application and Client Application , we will use JNI to create and map ashmem objects using native C++ code and we will use the binder to pass the file descriptors between processes.

If you don’t know how to create a service and use it in Android Application read this first

Start with creating a new Android Application, add C++ support, choose API 15 and keep other defaults

Add a new Module -> Android Library

Add a new aidl file:

The type ParcelFileDescriptor is used to pass the file object from one process to another.

The Server Application

The Server application host a service to create and return a file descriptor for the shared memory. It is also contains an Activity for testing the shared memory.

To create or open a shared memory we need to pass name and size. We create a simple class to handle it using native code.

The Java code:

We create an HashMap to store all shared memory objects (the file descriptors) by name. We write 3 native C++ functions to create the shared memory , set a value and get a value

The C++ code

On the server application you can use the above code to create and use shared memory


Creating The Service

To create the service we need to implement the interface defined by the aidl file.

Using ParcelFileDescriptor we can pass any file descriptor we have to another process using the binder. It can be a file, device, socket, IPC object etc.

Add a class for a service:

Add update the manifest file:

Add Activity for testing

The code simply set and get values in the shared memory


Writing A Client Application

First we need to bind the service and get the file descriptor of the shared memory object:

Now we need to write a native code to use mmap and access the shared memory. We create a simple JNI wrapper class:

And the C++ code

Now we can use setMap to mmap the memory and setVal/getVal to access it

You can download / clone the full code from my github

Stay Updated, Sign up to our List:


3 thoughts on “Android – Creating Shared Memory using Ashmem

  1. Please someone provide me, Shared Memory sample code using class “android.os.SharedMemory” ?

  2. Very nice, I used your article as inspiration for

Leave a Reply