Android系统匿名共享内存Ashmem(Anonymous Shared Memory)简要介绍和学习计划

来源:互联网 发布:外国人用淘宝吗? 编辑:程序博客网 时间:2024/05/16 07:18
在Android系统中,提供了独特的匿名共享内存子系统Ashmem(Anonymous Shared Memory),它以驱动程序的形式实现在内核空间中。它有两个特点,一是能够辅助内存管理系统来有效地管理不再使用的内存块,二是它通过Binder进程间通信机制来实现进程间的内存共享。本文中,我们将通过实例来简要介绍Android系统的匿名共享内存的使用方法,使得我们对Android系统的匿名共享内存机制有一个感性的认识,为进一步学习它的源代码实现打下基础。

        Android系统的匿名共享内存子系统的主体是以驱动程序的形式实现在内核空间的,同时,在系统运行时库层和应用程序框架层提供了访问接口,其中,在系统运行时库层提供了C/C++调用接口,而在应用程序框架层提供了Java调用接口。这里,我们将直接通过应用程序框架层提供的Java调用接口来说明匿名共享内存子系统Ashmem的使用方法,毕竟我们在Android开发应用程序时,是基于Java语言的,而实际上,应用程序框架层的Java调用接口是通过JNI方法来调用系统运行时库层的C/C++调用接口,最后进入到内核空间的Ashmem驱动程序去的。

        我们在这里举的例子是一个名为Ashmem的应用程序,它包含了一个Server端和一个Client端实现,其中,Server端是以Service的形式实现的,在这里Service里面,创建一个匿名共享内存文件,而Client是一个Activity,这个Activity通过Binder进程间通信机制获得前面这个Service创建的匿名共享内存文件的句柄,从而实现共享。在Android应用程序框架层,提供了一个MemoryFile接口来封装了匿名共享内存文件的创建和使用,它实现在frameworks/base/core/java/android/os/MemoryFile.java文件中。下面,我们就来看看Server端是如何通过MemoryFile类来创建匿名共享内存文件的以及Client是如何获得这个匿名共享内存文件的句柄的。

        在MemoryFile类中,提供了两种创建匿名共享内存的方法,我们通过MemoryFile类的构造函数来看看这两种使用方法:

[java] view plaincopy
  1. public class MemoryFile  
  2. {  
  3.     ......  
  4.   
  5.     /** 
  6.     * Allocates a new ashmem region. The region is initially not purgable. 
  7.     * 
  8.     * @param name optional name for the file (can be null). 
  9.     * @param length of the memory file in bytes. 
  10.     * @throws IOException if the memory file could not be created. 
  11.     */  
  12.     public MemoryFile(String name, int length) throws IOException {  
  13.         mLength = length;  
  14.         mFD = native_open(name, length);  
  15.         mAddress = native_mmap(mFD, length, PROT_READ | PROT_WRITE);  
  16.         mOwnsRegion = true;  
  17.     }  
  18.   
  19.     /** 
  20.     * Creates a reference to an existing memory file. Changes to the original file 
  21.     * will be available through this reference. 
  22.     * Calls to {@link #allowPurging(boolean)} on the returned MemoryFile will fail. 
  23.     * 
  24.     * @param fd File descriptor for an existing memory file, as returned by 
  25.     *        {@link #getFileDescriptor()}. This file descriptor will be closed 
  26.     *        by {@link #close()}. 
  27.     * @param length Length of the memory file in bytes. 
  28.     * @param mode File mode. Currently only "r" for read-only access is supported. 
  29.     * @throws NullPointerException if <code>fd</code> is null. 
  30.     * @throws IOException If <code>fd</code> does not refer to an existing memory file, 
  31.     *         or if the file mode of the existing memory file is more restrictive 
  32.     *         than <code>mode</code>. 
  33.     * 
  34.     * @hide 
  35.     */  
  36.     public MemoryFile(FileDescriptor fd, int length, String mode) throws IOException {  
  37.         if (fd == null) {  
  38.             throw new NullPointerException("File descriptor is null.");  
  39.         }  
  40.         if (!isMemoryFile(fd)) {  
  41.             throw new IllegalArgumentException("Not a memory file.");  
  42.         }  
  43.         mLength = length;  
  44.         mFD = fd;  
  45.         mAddress = native_mmap(mFD, length, modeToProt(mode));  
  46.         mOwnsRegion = false;  
  47.     }  
  48.   
  49.     ......  
  50. }  
        从注释中,我们可以看出这两个构造函数的使用方法,这里就不再详述了。两个构造函数的主要区别是第一个参数,第一种构造方法是以指定的字符串调用JNI方法native_open来创建一个匿名共享内存文件,从而得到一个文件描述符,接着就以这个文件描述符为参数调用JNI方法natvie_mmap把这个匿名共享内存文件映射在进程空间中,然后就可以通过这个映射后得到的地址空间来直接访问内存数据了;第二种构造方法是以指定的文件描述符来直接调用JNI方法natvie_mmap把这个匿名共享内存文件映射在进程空间中,然后进行访问,而这个文件描述符就必须要是一个匿名共享内存文件的文件描述符,这是通过一个内部函数isMemoryFile来验证的,而这个内部函数isMemoryFile也是通过JNI方法调用来进一步验证的。前面所提到的这些JNI方法调用,最终都是通过系统运行时库层进入到内核空间的Ashmem驱动程序中去,不过这里我们不关心这些JNI方法、系统运行库层调用以及Ashmem驱动程序的具体实现,在接下来的两篇文章中,我们将会着重介绍,这里我们只关注MemoryFile这个类的使用方法。

        前面我们说到,我们在这里举的例子包含了一个Server端和一个Client端实现,其中, Server端就是通过前面一个构造函数来创建一个匿名共享内存文件,接着,Client端过Binder进程间通信机制来向Server请求这个匿名共享内存的文件描述符,有了这个文件描述符之后,就可以通过后面一个构造函数来共享这个内存文件了。

        因为涉及到Binder进程间通信,我们首先定义好Binder进程间通信接口。Binder进程间通信机制的相关介绍,请参考前面一篇文章Android进程间通信(IPC)机制Binder简要介绍和学习计划,这里就不详细介绍了,直接进入主题。
        首先在源代码工程的packages/experimental目录下创建一个应用程序工程目录Ashmem。关于如何获得Android源代码工程,请参考在Ubuntu上下载、编译和安装Android最新源代码一文;关于如何在Android源代码工程中创建应用程序工程,请参考在Ubuntu上为Android系统内置Java应用程序测试Application Frameworks层的硬件服务一文。这里,工程名称就是Ashmem了,它定义了一个路径为shy.luo.ashmem的package,这个例子的源代码主要就是实现在这里了。下面,将会逐一介绍这个package里面的文件。

        这里要用到的Binder进程间通信接口定义在src/shy/luo/ashmem/IMemoryService.java文件中:

[java] view plaincopy
  1. package shy.luo.ashmem;  
  2.   
  3. import android.util.Log;  
  4. import android.os.IInterface;  
  5. import android.os.Binder;  
  6. import android.os.IBinder;  
  7. import android.os.Parcel;  
  8. import android.os.ParcelFileDescriptor;  
  9. import android.os.RemoteException;  
  10.   
  11. public interface IMemoryService extends IInterface {  
  12.     public static abstract class Stub extends Binder implements IMemoryService {  
  13.         private static final String DESCRIPTOR = "shy.luo.ashmem.IMemoryService";  
  14.   
  15.         public Stub() {  
  16.             attachInterface(this, DESCRIPTOR);  
  17.         }  
  18.   
  19.         public static IMemoryService asInterface(IBinder obj) {  
  20.             if (obj == null) {  
  21.                 return null;  
  22.             }  
  23.   
  24.             IInterface iin = (IInterface)obj.queryLocalInterface(DESCRIPTOR);  
  25.             if (iin != null && iin instanceof IMemoryService) {  
  26.                 return (IMemoryService)iin;  
  27.             }  
  28.   
  29.             return new IMemoryService.Stub.Proxy(obj);  
  30.         }  
  31.   
  32.         public IBinder asBinder() {  
  33.             return this;  
  34.         }  
  35.   
  36.         @Override   
  37.         public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws android.os.RemoteException {  
  38.             switch (code) {  
  39.             case INTERFACE_TRANSACTION: {  
  40.                 reply.writeString(DESCRIPTOR);  
  41.                 return true;  
  42.             }  
  43.             case TRANSACTION_getFileDescriptor: {  
  44.                 data.enforceInterface(DESCRIPTOR);  
  45.                   
  46.                 ParcelFileDescriptor result = this.getFileDescriptor();  
  47.                   
  48.                 reply.writeNoException();  
  49.                   
  50.                 if (result != null) {  
  51.                     reply.writeInt(1);  
  52.                     result.writeToParcel(reply, 0);  
  53.                 } else {  
  54.                     reply.writeInt(0);  
  55.                 }  
  56.   
  57.                 return true;  
  58.             }  
  59.             case TRANSACTION_setValue: {  
  60.                 data.enforceInterface(DESCRIPTOR);  
  61.                   
  62.                 int val = data.readInt();  
  63.                 setValue(val);  
  64.                   
  65.                 reply.writeNoException();  
  66.                   
  67.                 return true;  
  68.             }  
  69.             }  
  70.   
  71.             return super.onTransact(code, data, reply, flags);  
  72.         }  
  73.   
  74.         private static class Proxy implements IMemoryService {  
  75.             private IBinder mRemote;  
  76.   
  77.             Proxy(IBinder remote) {  
  78.                 mRemote = remote;  
  79.             }  
  80.   
  81.             public IBinder asBinder() {  
  82.                 return mRemote;  
  83.             }  
  84.   
  85.             public String getInterfaceDescriptor() {  
  86.                 return DESCRIPTOR;  
  87.             }  
  88.   
  89.             public ParcelFileDescriptor getFileDescriptor() throws RemoteException {  
  90.                 Parcel data = Parcel.obtain();  
  91.                 Parcel reply = Parcel.obtain();  
  92.   
  93.                 ParcelFileDescriptor result;  
  94.       
  95.                 try {  
  96.                     data.writeInterfaceToken(DESCRIPTOR);  
  97.   
  98.                     mRemote.transact(Stub.TRANSACTION_getFileDescriptor, data, reply, 0);  
  99.           
  100.                     reply.readException();  
  101.                     if (0 != reply.readInt()) {  
  102.                         result = ParcelFileDescriptor.CREATOR.createFromParcel(reply);  
  103.                     } else {  
  104.                         result = null;  
  105.                     }  
  106.                 } finally {  
  107.                     reply.recycle();  
  108.                     data.recycle();  
  109.                 }  
  110.       
  111.                 return result;  
  112.             }  
  113.   
  114.             public void setValue(int val) throws RemoteException {  
  115.                 Parcel data = Parcel.obtain();  
  116.                 Parcel reply = Parcel.obtain();  
  117.   
  118.                 try {  
  119.                     data.writeInterfaceToken(DESCRIPTOR);  
  120.                     data.writeInt(val);  
  121.   
  122.                     mRemote.transact(Stub.TRANSACTION_setValue, data, reply, 0);  
  123.                       
  124.                     reply.readException();  
  125.                 } finally {  
  126.                     reply.recycle();  
  127.                     data.recycle();  
  128.                 }  
  129.             }  
  130.         }  
  131.   
  132.         static final int TRANSACTION_getFileDescriptor = IBinder.FIRST_CALL_TRANSACTION + 0;  
  133.         static final int TRANSACTION_setValue = IBinder.FIRST_CALL_TRANSACTION + 1;  
  134.   
  135.     }  
  136.   
  137.     public ParcelFileDescriptor getFileDescriptor() throws RemoteException;  
  138.     public void setValue(int val) throws RemoteException;  
  139. }  
        这里主要是定义了IMemoryService接口,它里面有两个调用接口:
[java] view plaincopy
  1. public ParcelFileDescriptor getFileDescriptor() throws RemoteException;  
  2. public void setValue(int val) throws RemoteException;  
        同时,还分别定义了用于Server端实现的IMemoryService.Stub基类和用于Client端使用的代理IMemoryService.Stub.Proxy类。关于Binder进程间通信机制在应用程序框架层的Java接口定义,请参考前面Android系统进程间通信Binder机制在应用程序框架层的Java接口源代码分析一文。

        有了Binder进程间通信接口之后,接下来就是要在Server端实现一个本地服务了。这里,Server端实现的本地服务名为MemoryService,实现在src/shy/luo/ashmem/MemoryService.java文件中:

[java] view plaincopy
  1. package shy.luo.ashmem;  
  2.   
  3. import java.io.FileDescriptor;  
  4. import java.io.IOException;  
  5.   
  6. import android.os.Parcel;  
  7. import android.os.MemoryFile;  
  8. import android.os.ParcelFileDescriptor;  
  9. import android.util.Log;  
  10.   
  11. public class MemoryService extends IMemoryService.Stub {  
  12.     private final static String LOG_TAG = "shy.luo.ashmem.MemoryService";  
  13.     private MemoryFile file = null;  
  14.       
  15.     public MemoryService() {  
  16.         try {  
  17.                         file = new MemoryFile("Ashmem"4);  
  18.                         setValue(0);  
  19.                 }  
  20.                 catch(IOException ex) {  
  21.                         Log.i(LOG_TAG, "Failed to create memory file.");  
  22.                         ex.printStackTrace();  
  23.                 }  
  24.     }  
  25.   
  26.     public ParcelFileDescriptor getFileDescriptor() {  
  27.         Log.i(LOG_TAG, "Get File Descriptor.");  
  28.   
  29.         ParcelFileDescriptor pfd = null;  
  30.   
  31.         try {  
  32.             pfd = file.getParcelFileDescriptor();  
  33.         } catch(IOException ex) {  
  34.             Log.i(LOG_TAG, "Failed to get file descriptor.");  
  35.             ex.printStackTrace();  
  36.         }  
  37.   
  38.         return pfd;  
  39.     }  
  40.       
  41.     public void setValue(int val) {  
  42.         if(file == null) {  
  43.             return;  
  44.         }  
  45.   
  46.         byte[] buffer = new byte[4];     
  47.         buffer[0] = (byte)((val >>> 24) & 0xFF);  
  48.         buffer[1] = (byte)((val >>> 16) & 0xFF);  
  49.         buffer[2] = (byte)((val >>> 8) & 0xFF);   
  50.         buffer[3] = (byte)(val & 0xFF);  
  51.           
  52.         try {  
  53.             file.writeBytes(buffer, 004);  
  54.             Log.i(LOG_TAG, "Set value " + val + " to memory file. ");  
  55.         }  
  56.         catch(IOException ex) {  
  57.             Log.i(LOG_TAG, "Failed to write bytes to memory file.");  
  58.             ex.printStackTrace();  
  59.         }  
  60.     }  
  61. }  
        注意,这里的MemoryService类实现了IMemoryService.Stub类,表示这是一个Binder服务的本地实现。在构造函数中,通过指定文件名和文件大小来创建了一个匿名共享内存文件,即创建MemoryFile的一个实例,并保存在类成员变量file中。这个匿名共享内存文件名为"Ashmem",大小为4个节字,刚好容纳一个整数,我们这里举的例子就是要说明如果创建一个匿名共享内存来在两个进程间实现共享一个整数了。当然,在实际应用中,可以根据需要创建合适大小的共享内存来共享有意义的数据。

        这里还实现了IMemoryService.Stub的两个接口getFileDescriptor和setVal,一个用来获取匿名共享内存文件的文件描述符,一个来往匿名共享内存文件中写入一个整数,其中,接口getFileDescriptor的返回值是一个ParcelFileDescriptor。在Java中,是用FileDescriptor类来表示一个文件描述符的,而ParcelFileDescriptor是用来序列化FileDescriptor的,以便在进程间调用时传输。
        定义好本地服务好,就要定义一个Server来启动这个服务了。这里定义的Server实现在src/shy/luo/ashmem/Server.java文件中:

[java] view plaincopy
  1. package shy.luo.ashmem;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.IBinder;  
  6. import android.util.Log;  
  7. import android.os.ServiceManager;  
  8.   
  9. public class Server extends Service {  
  10.     private final static String LOG_TAG = "shy.luo.ashmem.Server";  
  11.   
  12.     private MemoryService memoryService = null;  
  13.   
  14.     @Override  
  15.     public IBinder onBind(Intent intent) {  
  16.         return null;  
  17.     }  
  18.   
  19.     @Override  
  20.     public void onCreate() {  
  21.     Log.i(LOG_TAG, "Create Memory Service...");  
  22.   
  23.     memoryService = new MemoryService();  
  24.   
  25.         try {  
  26.             ServiceManager.addService("AnonymousSharedMemory", memoryService);  
  27.             Log.i(LOG_TAG, "Succeed to add memory service.");  
  28.         } catch (RuntimeException ex) {  
  29.             Log.i(LOG_TAG, "Failed to add Memory Service.");  
  30.             ex.printStackTrace();  
  31.         }  
  32.   
  33.     }  
  34.   
  35.     @Override  
  36.     public void onStart(Intent intent, int startId) {  
  37.         Log.i(LOG_TAG, "Start Memory Service.");  
  38.     }  
  39.   
  40.     @Override  
  41.     public void onDestroy() {  
  42.     Log.i(LOG_TAG, "Destroy Memory Service.");  
  43.     }  
  44. }  
        这个Server继承了Android系统应用程序框架层提供的Service类,当它被启动时,运行在一个独立的进程中。当这个Server被启动时,它的onCreate函数就会被调用,然后它就通过ServiceManager的addService接口来添加MemoryService了:
[java] view plaincopy
  1. memoryService = new MemoryService();  
  2.   
  3. try {  
  4.     ServiceManager.addService("AnonymousSharedMemory", memoryService);  
  5.     Log.i(LOG_TAG, "Succeed to add memory service.");  
  6. catch (RuntimeException ex) {  
  7.     Log.i(LOG_TAG, "Failed to add Memory Service.");  
  8.     ex.printStackTrace();  
  9. }  
       这样,当这个Server成功启动了,Client就可以通过ServiceManager的getService接口来获取这个MemoryService了。

       接着,我们就来看Client端的实现。Client端是一个Activity,实现在src/shy/luo/ashmem/Client.java文件中:

[java] view plaincopy
  1. package shy.luo.ashmem;  
  2.   
  3. import java.io.FileDescriptor;  
  4. import java.io.IOException;  
  5.   
  6. import shy.luo.ashmem.R;  
  7. import android.app.Activity;  
  8. import android.content.Intent;  
  9. import android.os.Bundle;  
  10. import android.os.MemoryFile;  
  11. import android.os.ParcelFileDescriptor;  
  12. import android.os.ServiceManager;  
  13. import android.os.RemoteException;  
  14. import android.util.Log;  
  15. import android.view.View;  
  16. import android.view.View.OnClickListener;  
  17. import android.widget.Button;  
  18. import android.widget.EditText;  
  19.   
  20. public class Client extends Activity implements OnClickListener {  
  21.     private final static String LOG_TAG = "shy.luo.ashmem.Client";  
  22.       
  23.     IMemoryService memoryService = null;  
  24.     MemoryFile memoryFile = null;  
  25.       
  26.     private EditText valueText = null;  
  27.     private Button readButton = null;  
  28.     private Button writeButton = null;  
  29.     private Button clearButton = null;  
  30.       
  31.         @Override  
  32.         public void onCreate(Bundle savedInstanceState) {  
  33.             super.onCreate(savedInstanceState);  
  34.             setContentView(R.layout.main);  
  35.   
  36.         IMemoryService ms = getMemoryService();  
  37.         if(ms == null) {          
  38.                 startService(new Intent("shy.luo.ashmem.server"));  
  39.         } else {  
  40.             Log.i(LOG_TAG, "Memory Service has started.");  
  41.         }  
  42.   
  43.             valueText = (EditText)findViewById(R.id.edit_value);  
  44.             readButton = (Button)findViewById(R.id.button_read);  
  45.             writeButton = (Button)findViewById(R.id.button_write);  
  46.             clearButton = (Button)findViewById(R.id.button_clear);  
  47.   
  48.         readButton.setOnClickListener(this);  
  49.             writeButton.setOnClickListener(this);  
  50.             clearButton.setOnClickListener(this);  
  51.           
  52.             Log.i(LOG_TAG, "Client Activity Created.");  
  53.         }  
  54.   
  55.         @Override  
  56.         public void onResume() {  
  57.         super.onResume();  
  58.   
  59.         Log.i(LOG_TAG, "Client Activity Resumed.");  
  60.         }  
  61.   
  62.         @Override  
  63.         public void onPause() {  
  64.         super.onPause();  
  65.   
  66.         Log.i(LOG_TAG, "Client Activity Paused.");  
  67.         }  
  68.       
  69.         @Override  
  70.         public void onClick(View v) {  
  71.             if(v.equals(readButton)) {  
  72.                 int val = 0;  
  73.               
  74.                 MemoryFile mf = getMemoryFile();  
  75.                 if(mf != null) {  
  76.                 try {  
  77.                         byte[] buffer = new byte[4];  
  78.                         mf.readBytes(buffer, 004);  
  79.                   
  80.                         val = (buffer[0] << 24) | ((buffer[1] & 0xFF) << 16) | ((buffer[2] & 0xFF) << 8) | (buffer[3] & 0xFF);  
  81.                 } catch(IOException ex) {  
  82.                     Log.i(LOG_TAG, "Failed to read bytes from memory file.");  
  83.                     ex.printStackTrace();  
  84.                 }  
  85.                 }     
  86.               
  87.                 String text = String.valueOf(val);  
  88.                 valueText.setText(text);  
  89.             } else if(v.equals(writeButton)) {  
  90.                 String text = valueText.getText().toString();  
  91.                 int val = Integer.parseInt(text);  
  92.               
  93.                 IMemoryService ms = getMemoryService();  
  94.                 if(ms != null) {  
  95.                 try {  
  96.                         ms.setValue(val);  
  97.                 } catch(RemoteException ex) {  
  98.                     Log.i(LOG_TAG, "Failed to set value to memory service.");  
  99.                     ex.printStackTrace();  
  100.                 }  
  101.                 }  
  102.             } else if(v.equals(clearButton)) {  
  103.                 String text = "";  
  104.                 valueText.setText(text);  
  105.             }  
  106.         }  
  107.       
  108.         private IMemoryService getMemoryService() {  
  109.             if(memoryService != null) {  
  110.                 return memoryService;  
  111.             }  
  112.           
  113.             memoryService = IMemoryService.Stub.asInterface(  
  114.                             ServiceManager.getService("AnonymousSharedMemory"));  
  115.   
  116.         Log.i(LOG_TAG, memoryService != null ? "Succeed to get memeory service." : "Failed to get memory service.");  
  117.           
  118.             return memoryService;  
  119.         }  
  120.       
  121.         private MemoryFile getMemoryFile() {  
  122.             if(memoryFile != null) {  
  123.                 return memoryFile;  
  124.             }  
  125.               
  126.             IMemoryService ms = getMemoryService();  
  127.             if(ms != null) {  
  128.             try {  
  129.                     ParcelFileDescriptor pfd = ms.getFileDescriptor();  
  130.                 if(pfd == null) {  
  131.                     Log.i(LOG_TAG, "Failed to get memory file descriptor.");  
  132.                     return null;  
  133.                 }  
  134.   
  135.                 try {  
  136.                     FileDescriptor fd = pfd.getFileDescriptor();  
  137.                     if(fd == null) {  
  138.                         Log.i(LOG_TAG, "Failed to get memeory file descriptor.");  
  139.                         return null;                        
  140.                     }     
  141.   
  142.                         memoryFile = new MemoryFile(fd, 4"r");  
  143.                 } catch(IOException ex) {  
  144.                     Log.i(LOG_TAG, "Failed to create memory file.");  
  145.                     ex.printStackTrace();  
  146.                 }  
  147.                 } catch(RemoteException ex) {  
  148.                 Log.i(LOG_TAG, "Failed to get file descriptor from memory service.");  
  149.                 ex.printStackTrace();  
  150.             }  
  151.         }  
  152.           
  153.             return memoryFile;  
  154.         }  
  155. }  
        Client端的界面主要包含了三个按钮Read、Write和Clear,以及一个用于显示内容的文本框。

        这个Activity在onCreate时,会通过startService接口来启动我们前面定义的Server进程。调用startService时,需要指定要启动的服务的名称,这里就是"shy.luo.ashmem.server"了,后面我们会在程序的描述文件AndroidManifest.xml看到前面的Server类是如何和名称"shy.luo.ashmem.server"关联起来的。关于调用startService函数来启动自定义服务的过程,可以参考Android系统在新进程中启动自定义服务过程(startService)的原理分析一文。

        内部函数getMemoryService用来获取IMemoryService。如果是第一次调用该函数,则会通过ServiceManager的getService接口来获得这个IMemoryService接口,然后保存在类成员变量memoryService中,以后再调用这个函数时,就可以直接返回memoryService了。

        内部函数getMemoryFile用来从MemoryService中获得匿名共享内存文件的描述符。同样,如果是第一次调用该函数,则会通过IMemoryService的getFileDescriptor接口来获得MemoryService中的匿名共享内存文件的描述符,然后用这个文件描述符来创建一个MemoryFile实例,并保存在类成员变量memoryFile中,以后再调用这个函数时,就可以直接返回memoryFile了。

        有了memoryService和memoryFile后,我们就可以在Client端访问Server端创建的匿名共享内存了。点击Read按钮时,就通过memoryFile的readBytes接口把共享内存中的整数读出来,并显示在文本框中;点击Write按钮时,就通过memoryService这个代理类的setVal接口来调用MemoryService的本地实现类的setVal服务,从而把文本框中的数值写到Server端创建的匿名共享内存中去;点击Clear按钮时,就会清空文本框的内容。这样,我们就可以通过Read和Write按钮来验证我们是否在Client和Server两个进程中实现内存共享了。

       现在,我们再来看看Client界面的配置文件,它定义在res/layout/main.xml文件中:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="fill_parent"  
  5.     android:layout_height="fill_parent"  
  6.     >  
  7.     <LinearLayout  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:orientation="vertical"   
  11.         android:gravity="center">  
  12.         <TextView   
  13.             android:layout_width="wrap_content"  
  14.             android:layout_height="wrap_content"   
  15.             android:text="@string/value">  
  16.         </TextView>  
  17.         <EditText   
  18.             android:layout_width="fill_parent"  
  19.             android:layout_height="wrap_content"   
  20.             android:id="@+id/edit_value"  
  21.             android:hint="@string/hint">  
  22.         </EditText>  
  23.     </LinearLayout>  
  24.      <LinearLayout  
  25.         android:layout_width="fill_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:orientation="horizontal"   
  28.         android:gravity="center">  
  29.         <Button   
  30.             android:id="@+id/button_read"  
  31.             android:layout_width="wrap_content"  
  32.             android:layout_height="wrap_content"  
  33.             android:text="@string/read">  
  34.         </Button>  
  35.         <Button   
  36.             android:id="@+id/button_write"  
  37.             android:layout_width="wrap_content"  
  38.             android:layout_height="wrap_content"  
  39.             android:text="@string/write">  
  40.         </Button>  
  41.         <Button   
  42.             android:id="@+id/button_clear"  
  43.             android:layout_width="wrap_content"  
  44.             android:layout_height="wrap_content"  
  45.             android:text="@string/clear">  
  46.         </Button>  
  47.     </LinearLayout>  
  48. </LinearLayout>  
        相关的字符串定义在res/values/strings.xml文件中:
[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <string name="app_name">Ashmem</string>  
  4.     <string name="value">Value</string>  
  5.     <string name="hint">Please input a value...</string>  
  6.     <string name="read">Read</string>  
  7.     <string name="write">Write</string>  
  8.     <string name="clear">Clear</string>  
  9. </resources>  
        这样,界面的相关配置文件就介绍完了。

       我们还要再来看程序描述文件AndroidManifest.xml的相关配置,它位于Ashmem目录下:

[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="shy.luo.ashmem"  
  4.       android:sharedUserId="android.uid.system"  
  5.       android:versionCode="1"  
  6.       android:versionName="1.0">  
  7.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  8.         <activity android:name=".Client"  
  9.                   android:label="@string/app_name">  
  10.             <intent-filter>  
  11.                 <action android:name="android.intent.action.MAIN" />  
  12.                 <category android:name="android.intent.category.LAUNCHER" />  
  13.             </intent-filter>  
  14.         </activity>  
  15.         <service   
  16.             android:enabled="true"   
  17.             android:name=".Server"  
  18.             android:process=".Server" >  
  19.             <intent-filter>  
  20.                 <action android:name="shy.luo.ashmem.server"/>  
  21.                 <category android:name="android.intent.category.DEFAULT"/>  
  22.             </intent-filter>  
  23.         </service>  
  24.     </application>  
  25. </manifest>  
        这里我们可以看到,下面的配置项把服务名称"shy.luo.ashmem.server"和本地服务类Server关联了起来:
[html] view plaincopy
  1.    <service   
  2. android:enabled="true"   
  3. android:name=".Server"  
  4. android:process=".Server" >  
  5. <intent-filter>  
  6.             <action android:name="shy.luo.ashmem.server"/>  
  7.             <category android:name="android.intent.category.DEFAULT"/>  
  8.        </intent-filter>  
  9.    </service>  
        这样,我们就可以通过startService(new Intent("shy.luo.ashmem.server"))来启动这个Server了。不过,在Android中,启动服务是需要权限的,所以,下面这一行配置获取了启动服务需要的相应权限:
[html] view plaincopy
  1. android:sharedUserId="android.uid.system"  
        最后,我们来看工程的编译脚本文件Android.mk,它位于Ashmem目录下:
[html] view plaincopy
  1. LOCAL_PATH:= $(call my-dir)  
  2. include $(CLEAR_VARS)  
  3.   
  4. LOCAL_MODULE_TAGS :optional  
  5.   
  6. LOCAL_SRC_FILES += $(call all-subdir-java-files)  
  7.   
  8. LOCAL_PACKAGE_NAME :Ashmem  
  9.   
  10. LOCAL_CERTIFICATE :platform  
  11.   
  12. include $(BUILD_PACKAGE)  
        这里又有一个关键的地方:
[html] view plaincopy
  1. LOCAL_CERTIFICATE :platform  
        因为我们需要在程序中启动Service,所以要配置这一行,并且要把源代码工程放在Android源代码平台中进行编译。

        这样,整个例子的源代码实现就介绍完了,接下来就要编译了。有关如何单独编译Android源代码工程的模块,以及如何打包system.img,请参考如何单独编译Android源代码中的模块一文。

        执行以下命令进行编译和打包:

[html] view plaincopy
  1. USER-NAME@MACHINE-NAME:~/Android$ mmm packages/experimental/Ashmem  
  2. USER-NAME@MACHINE-NAME:~/Android$ make snod  
       这样,打包好的Android系统镜像文件system.img就包含我们前面创建的Ashmem应用程序了。

       再接下来,就是运行模拟器来运行我们的例子了。关于如何在Android源代码工程中运行模拟器,请参考在Ubuntu上下载、编译和安装Android最新源代码一文。

       执行以下命令启动模拟器:

[html] view plaincopy
  1. USER-NAME@MACHINE-NAME:~/Android$ emulator  
       模拟器启动起,就可以在Home Screen上看到Ashmem应用程序图标了:


       点击Ashmem图标,启动Ashmem应用程序,界面如下:


        这样,我们就可以验证程序的功能了,看看是否实现了在两个进程中通过使用Android系统的匿名共享内存机制来共享内存数据的功能。

        通过这个例子的学习,相信读者对Android系统匿名共享内存子系统Ashmem有了一个大概的认识,但是,这种认识还是停留在表面上。我们在文章开始时就提到,Android系统匿名共享内存子系统Ashmem两个特点,一是能够辅助内存管理系统来有效地管理不再使用的内存块,二是它通过Binder进程间通信机制来实现进程间的内存共享。第二个特点我们在上面这个例子中看到了,但是似乎还不够深入,我们知道,在Linux系统中,文件描述符其实就是一个整数,它是用来索引进程保存在内核空间的打开文件数据结构的,而且,这个文件描述符只是在进程内有效,也就是说,在不同的进程中,相同的文件描述符的值,代表的可能是不同的打开文件,既然是这样,把Server进程中的文件描述符传给Client进程,似乎就没有用了,但是不用担心,在传输过程中,Binder驱动程序会帮我们处理好一切,保证Client进程拿到的文件描述符是在本进程中有效的,并且它指向就是Server进程创建的匿名共享内存文件。至于第一个特点,我们也准备在后续学习Android系统匿名共享内存子系统Ashmem时,再详细介绍。

        因此,为了深入了解Android系统匿名共享内存子系统Ashmem,在接下来的两篇文章中,围绕上面提到的两个特点,分别学习:

       1. Android系统匿名共享内存子系统Ashmem是如何够辅助内存管理系统来有效地管理不再使用的内存块的?

       2. Android系统匿名共享内存子系统Ashmem是如何通过Binder进程间通信机制来实现进程间的内存共享的?

       学习完这两篇文章后,相信大家对 Android系统匿名共享内存子系统Ashmem就会有一个更深刻的认识了,敬请关注。


原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 学驾照没有居住证怎么办 居住证到期驾照还没考完怎么办 买车需要居住证怎么办 住亲友家怎么办居住证 审驾照体检近视怎么办 开车忘带行车证怎么办 韩国转机过境签怎么办 身份证掉了坐车怎么办 科目一考试模拟怎么办 小车驾照过期了怎么办 本地驾驶证掉了怎么办 摩托车驾照脱审怎么办 驾驶证撕坏了怎么办 个体营业执照掉了怎么办 天津驾照丢了怎么办 东莞行驶证丢失怎么办 信用社存折丢了怎么办 没有存折和密码怎么办 行驶证没有照片怎么办 驾证吊销了怎么办 吊销驾照后开车怎么办 外地办行驶证怎么办 驾照考试没过怎么办 驾照考爆了怎么办 考驾照老是不过怎么办 考驾照没时间怎么办 驾照不退学费怎么办 驾照报名费不退怎么办 货车撞人保险金额不够怎么办 科目三不懂灯光怎么办 驾照忘记换证怎么办 小车驾驶证丢了怎么办 天津河西区驾驶证过期怎么办 b2证年审过期怎么办 武汉社保卡到期怎么办 杭州市民卡过期怎么办 外地驾驶证脱审怎么办 没有驾驶证脱审怎么办 驾驶证过期一个月怎么办 有证忘带驾驶证怎么办 a2驾驶证吊销了怎么办