Android System anonymous shared memory (Anonymous shared Memories) Java Call Interface analysis

Source: Internet
Author: User
Tags mremote

One, Ashmem driver

~/android/kernel/goldfish

----include

----Linux

----ashmem.h

----mm

----ASHMEM.C

For a detailed description of the driver, see "Android system source code scenario analysis", author Luo Shenyang.


Second, the runtime library cutils anonymous shared memory Access interface

~/android/system/core

----Libcutils

----ASHMEM-DEV.C

Please see "Android system source code scenario analysis", author Luo Shenyang.


Third, Memoryfile

~/android/frameworks/base/core/java/android/os

----Memoryfile.java

~/android/frameworks/base/core/jni

----Android_os_memoryfile.cpp

Please see "Android system source code scenario analysis", author Luo Shenyang.

~/android/frameworks/base/core/java/android/os

----Memoryfile.java

    Public Parcelfiledescriptor Getparcelfiledescriptor () throws IOException {        FileDescriptor fd = Getfiledescriptor () ;        return FD! = null? New Parcelfiledescriptor (FD): null;    }    .......    Public FileDescriptor Getfiledescriptor () throws IOException {        return mFD;    }


Iv. Examples of applications

Please see "Android system source code scenario analysis", author Luo Shenyang.

In this section, we will create an Android application Ashmem, which consists of a service component server and an activity component client. The server component runs in a separate process, which internally has a memory access service Memoryservice, which creates an anonymous shared memory through the Memoryfile class. The client component runs in another process, which maps the anonymous shared memory created by the Memory Access service Memoryservice to the address space of the process so that its contents can be accessed so that it can share an anonymous shared memory with the server component.

~/android/packages/experimental/ashmem

----Androidmanifest.java

----ANDROID.MK

----SRC

----SHY/LUO/ASHMEM

----Imemoryservice.java

----Memoryservice.java

----Server.java

----Client.java

----Res

----layout

----Main.xml

----values

----Strings.xml

----drawable

----Icon.png


Imemoryservice.java

Package Shy.luo.ashmem;import Android.util.log;import Android.os.iinterface;import android.os.binder;import Android.os.ibinder;import Android.os.parcel;import Android.os.parcelfiledescriptor;import Android.os.remoteexception;public interface Imemoryservice extends IInterface {public static abstract class Stub extends Binder implements Imemoryservice {private static final String descriptor = "Shy.luo.ashmem.IMemoryService";p ublic Stub () {Attachinterface (this, descriptor);} public static Imemoryservice asinterface (IBinder obj) {if (obj = = null) {return null;} IInterface iin = (iinterface) obj.querylocalinterface (descriptor); if (iin! = null && iin instanceof Imemoryservice) {return (Imemoryservice) iin;} return new IMemoryService.Stub.Proxy (obj); Public IBinder Asbinder () {return this;} @Override public boolean ontransact (int code, PARCEL data, Parcel reply, int flags) throws Android.os.RemoteException {SWI TCH (code) {case Interface_transaction: {reply.writestring (descriptor); return True;} Case Transaction_getfiledescriptor: {data.enforceinterface (descriptor); Parcelfiledescriptor result = This.getfiledescriptor (); reply.writenoexception (); if (result! = null) {Reply.writeint (1 ); Result.writetoparcel (reply, 0);} else {reply.writeint (0);} return true;} Case Transaction_setvalue: {data.enforceinterface (descriptor); int val = Data.readint (); SetValue (Val); Reply.writenoexception (); return true;}} Return Super.ontransact (Code, data, reply, flags);} private static class Proxy implements Imemoryservice {private IBinder mremote; Proxy (IBinder remote) {mremote = remote;} Public IBinder Asbinder () {return mremote;} Public String Getinterfacedescriptor () {return descriptor;} Public Parcelfiledescriptor Getfiledescriptor () throws RemoteException {Parcel data = Parcel.obtain (); Parcel reply = Parcel.obtain (); Parcelfiledescriptor Result;try {data.writeinterfacetoken (descriptor); Mremote.transact (Stub.TRANSACTION_ Getfiledescriptor, data, reply, 0); reply.readexception (); if (0! = Reply.readint ()) {resUlt = ParcelFileDescriptor.CREATOR.createFromParcel (reply);} else {result = null;}} finally {reply.recycle ();d ata.recycle ();} return result;} public void SetValue (int val) throws RemoteException {Parcel data = Parcel.obtain (); Parcel reply = Parcel.obtain (); try {Data.writeinterfacetoken (descriptor);d Ata.writeint (val); Mremote.transact ( Stub.transaction_setvalue, data, reply, 0); Reply.readexception ();} finally {reply.recycle ();d ata.recycle ();}}} static final int transaction_getfiledescriptor = ibinder.first_call_transaction + 0;static final int transaction_ SetValue = ibinder.first_call_transaction + 1;} Public Parcelfiledescriptor Getfiledescriptor () throws remoteexception;public void SetValue (int val) throws RemoteException;}

Memoryservice.java

Package Shy.luo.ashmem;import Java.io.filedescriptor;import Java.io.ioexception;import android.os.Parcel;import Android.os.memoryfile;import Android.os.parcelfiledescriptor;import Android.util.log;public class MemoryService Extends Imemoryservice.stub {Private final static String Log_tag = "Shy.luo.ashmem.MemoryService";p rivate memoryfile                        File = Null;public Memoryservice () {try {file = new Memoryfile ("Ashmem", 4);                SetValue (0);                        } catch (IOException ex) {log.i (Log_tag, "Failed to create memory file.");                Ex.printstacktrace (); }}public parcelfiledescriptor Getfiledescriptor () {log.i (Log_tag, "Get File descriptor."); Parcelfiledescriptor PFD = null;try {PFD = File.getparcelfiledescriptor ();} catch (IOException ex) {log.i (Log_tag, " Failed to get file descriptor. "); Ex.printstacktrace ();} return PFD;} public void SetValue (int val) {if (file = = null) {return;} byte[] buffer = new BYTE[4]; Buffer[0] = (byte) ((Val >>>) & 0xFF), buffer[1] = (byte) ((Val >>> +) & 0xFF); buffer[2] = (byt e) ((Val >>> 8) & 0xFF); BUFFER[3] = (byte) (Val & 0xFF); try {file.writebytes (buffer, 0, 0, 4); LOG.I (Log_tag, "Set value" + val + "to memory file"); catch (IOException ex) {log.i (Log_tag, "Failed to write bytes to memory file."); Ex.printstacktrace ();}}}

Server.java

Package Shy.luo.ashmem;import Android.app.service;import Android.content.intent;import android.os.IBinder;import Android.util.log;import Android.os.servicemanager;public class Server extends Service {private final static String Log    _tag = "Shy.luo.ashmem.Server";    Private Memoryservice memoryservice = null;    @Override public IBinder onbind (Intent Intent) {return null;        } @Override public void OnCreate () {log.i (Log_tag, "Create Memory Service ..."); memoryservice = new Memoryservice ();            try {servicemanager.addservice ("anonymoussharedmemory", Memoryservice);        LOG.I (Log_tag, "Succeed to add memory service.");            } catch (RuntimeException ex) {log.i (Log_tag, "Failed to add Memory Service.");        Ex.printstacktrace ();    }} @Override public void OnStart (Intent Intent, int startid) {log.i (Log_tag, "Start Memory Service."); } @Override public void OnDestroy () {log.i (Log_tag, "Destroy MemoRy Service. ");}} 

Client.java

Package Shy.luo.ashmem;import Java.io.filedescriptor;import Java.io.ioexception;import shy.luo.ashmem.R;import Android.app.activity;import Android.content.intent;import Android.os.bundle;import Android.os.MemoryFile;import Android.os.parcelfiledescriptor;import Android.os.servicemanager;import Android.os.remoteexception;import Android.util.log;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.Button; Import Android.widget.edittext;public class Client extends Activity implements Onclicklistener {private final static stri ng Log_tag = "shy.luo.ashmem.Client"; Imemoryservice memoryservice = null;  Memoryfile memoryfile = null;private EditText valueText = null;private button Readbutton = null;private button Writebutton    = null;private Button Clearbutton = null;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); Imemoryservice ms = Getmemoryservice (); if (ms = = NULL){StartService (New Intent ("Shy.luo.ashmem.server"));}        else {log.i (Log_tag, "Memory Service has started.");        ValueText = (EditText) Findviewbyid (R.id.edit_value);        Readbutton = (Button) Findviewbyid (R.id.button_read);        Writebutton = (Button) Findviewbyid (r.id.button_write);        Clearbutton = (Button) Findviewbyid (r.id.button_clear); Readbutton.setonclicklistener (this);        Writebutton.setonclicklistener (this);                Clearbutton.setonclicklistener (this);    LOG.I (Log_tag, "Client Activity Created."); } @Override public void Onresume () {super.onresume ();    LOG.I (Log_tag, "Client Activity resumed."); } @Override public void OnPause () {super.onpause ();    LOG.I (Log_tag, "Client Activity Paused.");        } @Override public void OnClick (View v) {if (V.equals (Readbutton)) {int val = 0;    Memoryfile MF = getmemoryfile ();    if (MF! = null) {try {byte[] buffer = new BYTE[4];        Mf.readbytes (buffer, 0, 0, 4);val = (buffer[0] << 24) | ((Buffer[1] & 0xFF) << 16) | ((Buffer[2] & 0xFF) << 8) | (Buffer[3] & 0xFF);} catch (IOException ex) {log.i (Log_tag, "Failed to read bytes from memory file.");    Ex.printstacktrace ();}    } String Text = String.valueof (val);    Valuetext.settext (text);    } else if (V.equals (Writebutton)) {String text = Valuetext.gettext (). toString ();        int val = integer.parseint (text);    Imemoryservice ms = Getmemoryservice (); if (ms! = NULL) {try {Ms.setvalue (val)} catch (RemoteException ex) {log.i (Log_tag, "Failed to set value to memory servi CE. ");    Ex.printstacktrace ();}    }} else if (V.equals (Clearbutton)) {String text = "";    Valuetext.settext (text);    }} private Imemoryservice Getmemoryservice () {if (Memoryservice! = null) {return memoryservice; } Memoryservice = IMemoryService.Stub.asInterface (Servicemanager.getservice ("Anonymoussharedmemory" )); LOG.I (Log_tag, MemoryserviCE = null?        "Succeed to get Memeory service.": "Failed to get Memory service.");    return memoryservice;    } private Memoryfile Getmemoryfile () {if (memoryfile! = null) {return memoryfile;    } Imemoryservice ms = Getmemoryservice (); if (ms! = NULL) {try {parcelfiledescriptor PFD = Ms.getfiledescriptor (); if (PFD = = null) {LOG.I (Log_tag, "Failed to get Memory file descriptor. "); return null;} try {filedescriptor fd = Pfd.getfiledescriptor (), if (FD = = null) {LOG.I (Log_tag, "Failed to get memeory file descriptor.")                      ; return null; } memoryfile = new Memoryfile (FD, 4, "R");} catch (IOException ex) {log.i (Log_tag, "Failed to create memory file.");    Ex.printstacktrace ();} } catch (RemoteException ex) {log.i (Log_tag, "Failed to get file descriptor from memory service.");        Ex.printstacktrace ();}}    return memoryfile; }}

Start the service on activity,oncreate first. Then click the Read button to execute the corresponding code.

Interprocess communication detailed steps, temporarily omitted, see only the steps indicated, see:


For the next analysis, see the principle analysis of anonymous shared memory Ashmem (Anonymous shared memories) sharing between processes in the Android system http://blog.csdn.net/luoshengyang/article/ details/6666491.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.