探索Android中的Parcel机制

来源:互联网 发布:手机英语口语交流软件 编辑:程序博客网 时间:2024/05/16 07:06

一.先从Serialize说起

         我们都知道JAVA中的Serialize机制,译成串行化、序列化……,其作用是能将数据对象存入字节流当中,在需要时重新生成对象。主要应用是利用外部存储设备保存对象状态,以及通过网络传输对象等。

 

二.Android中的新的序列化机制

         在Android系统中,定位为针对内存受限的设备,因此对性能要求更高,另外系统中采用了新的IPC(进程间通信)机制,必然要求使用性能更出色的对象传输方式。在这样的环境下,Parcel被设计出来,其定位就是轻量级的高效的对象序列化和反序列化机制。

 

三.Parcel类的背后

         在Framework中有parcel类,源码路径是:

Frameworks/base/core/java/android/os/Parcel.java

典型的源码片断如下:

 

 

view plain
  1. /** 
  2.  * Write an integer value into the parcel at the current dataPosition(), 
  3.  * growing dataCapacity() if needed. 
  4.  */  
  5. public final native void writeInt(int val);  
  6.   
  7. /** 
  8.  * Write a long integer value into the parcel at the current dataPosition(), 
  9.  * growing dataCapacity() if needed. 
  10.  */  
  11. public final native void writeLong(long val);  
  

 

         从中我们看到,从这个源程序文件中我们看不到真正的功能是如何实现的,必须透过JNI往下走了。于是,Frameworks/base/core/jni/android_util_Binder.cpp中找到了线索

 

view plain
  1. static void android_os_Parcel_writeInt(JNIEnv* env, jobject clazz, jint val)  
  2. {  
  3.     Parcel* parcel = parcelForJavaObject(env, clazz);  
  4.     if (parcel != NULL) {  
  5.         const status_t err = parcel->writeInt32(val);  
  6.         if (err != NO_ERROR) {  
  7.             jniThrowException(env, "java/lang/OutOfMemoryError", NULL);  
  8.         }  
  9.     }  
  10. }  
  11.   
  12. static void android_os_Parcel_writeLong(JNIEnv* env, jobject clazz, jlong val)  
  13. {  
  14.     Parcel* parcel = parcelForJavaObject(env, clazz);  
  15.     if (parcel != NULL) {  
  16.         const status_t err = parcel->writeInt64(val);  
  17.         if (err != NO_ERROR) {  
  18.             jniThrowException(env, "java/lang/OutOfMemoryError", NULL);  
  19.         }  
  20.     }  
  21. }  

  

         从这里我们可以得到的信息是函数的实现依赖于Parcel指针,因此还需要找到Parcel的类定义,注意,这里的类已经是用C++语言实现的了。

         找到Frameworks/base/include/binder/parcel.h和Frameworks/base/libs/binder/parcel.cpp。终于找到了最终的实现代码了。

         有兴趣的朋友可以自己读一下,不难理解,这里把基本的思路总结一下:

1.       整个读写全是在内存中进行,主要是通过malloc()、realloc()、memcpy()等内存操作进行,所以效率比JAVA序列化中使用外部存储器会高很多;

2.       读写时是4字节对齐的,可以看到#define PAD_SIZE(s) (((s)+3)&~3)这句宏定义就是在做这件事情;

3.       如果预分配的空间不够时newSize = ((mDataSize+len)*3)/2;会一次多分配50%;

4.       对于普通数据,使用的是mData内存地址,对于IBinder类型的数据以及FileDescriptor使用的是mObjects内存地址。后者是通过flatten_binder()和unflatten_binder()实现的,目的是反序列化时读出的对象就是原对象而不用重新new一个新对象。

 

好了,这就是Parcel背后的动作,全是在一块内存里进行读写操作,就不啰嗦了,把parcel的代码贴在这供没有源码的朋友参考吧。接下来我会用一个小DEMO演示一下Parcel类在应用程序中的使用,详见《探索Android中的Parcel机制(下)》。

 





探索Android中的Parcel机制(下)


上一篇中我们透过源码看到了Parcel背后的机制,本质上把它当成一个Serialize就可以了,只是它是在内存中完成的序列化和反序列化,利用的是连续的内存空间,因此会更加高效。

         我们接下来要说的是Parcel类如何应用。就应用程序而言,最常见使用Parcel类的场景就是在Activity间传递数据。没错,在Activity间使用Intent传递数据的时候,可以通过Parcelable机制传递复杂的对象。

         在下面的程序中,MyColor用于保存一个颜色值,MainActivity在用户点击屏幕时将MyColor对象设成红色,传递到SubActivity中,此时SubActivity的TextView显示为红色的背景;当点击SubActivity时,将颜色值改为绿色,返回MainActivity,期望的是MainActivity的TextView显示绿色背景。

         来看一下MyColor类的实现代码:

        

view plain
  1. package com.wenbin.test;  
  2.   
  3. import android.graphics.Color;  
  4. import android.os.Parcel;  
  5. import android.os.Parcelable;  
  6.   
  7. /** 
  8.  * @author 曹文斌 
  9.  * http://blog.csdn.net/caowenbin 
  10.  * 
  11.  */  
  12. public class MyColor implements Parcelable {  
  13.     private int color=Color.BLACK;  
  14.       
  15.     MyColor(){  
  16.         color=Color.BLACK;  
  17.     }  
  18.       
  19.     MyColor(Parcel in){  
  20.         color=in.readInt();  
  21.     }  
  22.       
  23.     public int getColor(){  
  24.         return color;  
  25.     }  
  26.       
  27.     public void setColor(int color){  
  28.         this.color=color;  
  29.     }  
  30.       
  31.     @Override  
  32.     public int describeContents() {  
  33.         return 0;  
  34.     }  
  35.   
  36.     @Override  
  37.     public void writeToParcel(Parcel dest, int flags) {  
  38.         dest.writeInt(color);  
  39.     }  
  40.   
  41.     public static final Parcelable.Creator<MyColor> CREATOR  
  42.         = new Parcelable.Creator<MyColor>() {  
  43.         public MyColor createFromParcel(Parcel in) {  
  44.             return new MyColor(in);  
  45.         }  
  46.           
  47.         public MyColor[] newArray(int size) {  
  48.             return new MyColor[size];  
  49.         }  
  50.     };  
  51. }  

 

         该类实现了Parcelable接口,提供了默认的构造函数,同时也提供了可从Parcel对象开始的构造函数,另外还实现了一个static的构造器用于构造对象和数组。代码很简单,不一一解释了。

         再看MainActivity的代码:

 

view plain
  1. package com.wenbin.test;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.graphics.Color;  
  6. import android.os.Bundle;  
  7. import android.view.MotionEvent;  
  8.   
  9. /** 
  10.  * @author 曹文斌 
  11.  * http://blog.csdn.net/caowenbin 
  12.  * 
  13.  */  
  14. public class MainActivity extends Activity {  
  15.     private final int SUB_ACTIVITY=0;  
  16.     private MyColor color=new MyColor();  
  17.       
  18.     @Override  
  19.     public void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main);  
  22.     }  
  23.   
  24.     @Override  
  25.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  26.         super.onActivityResult(requestCode, resultCode, data);  
  27.         if (requestCode==SUB_ACTIVITY){  
  28.             if (resultCode==RESULT_OK){  
  29.                 if (data.hasExtra("MyColor")){  
  30.                     color=data.getParcelableExtra("MyColor");  //Notice  
  31.                     findViewById(R.id.text).setBackgroundColor(color.getColor());  
  32.                 }  
  33.             }  
  34.         }  
  35.     }  
  36.   
  37.     @Override  
  38.     public boolean onTouchEvent(MotionEvent event){  
  39.         if (event.getAction()==MotionEvent.ACTION_UP){  
  40.             Intent intent=new Intent();  
  41.             intent.setClass(this, SubActivity.class);  
  42.             color.setColor(Color.RED);  
  43.             intent.putExtra("MyColor", color);  
  44.             startActivityForResult(intent,SUB_ACTIVITY);      
  45.         }  
  46.         return super.onTouchEvent(event);  
  47.     }  
  48.   
  49. }  

 

        下面是SubActivity的代码:

 

view plain
  1. package com.wenbin.test;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.graphics.Color;  
  6. import android.os.Bundle;  
  7. import android.view.MotionEvent;  
  8. import android.widget.TextView;  
  9.   
  10. /** 
  11.  * @author 曹文斌 
  12.  * http://blog.csdn.net/caowenbin 
  13.  * 
  14.  */  
  15. public class SubActivity extends Activity {  
  16.     private MyColor color;  
  17.       
  18.     @Override  
  19.     public void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main);  
  22.         ((TextView)findViewById(R.id.text)).setText("SubActivity");  
  23.         Intent intent=getIntent();  
  24.         if (intent!=null){  
  25.             if (intent.hasExtra("MyColor")){  
  26.                 color=intent.getParcelableExtra("MyColor");  
  27.                 findViewById(R.id.text).setBackgroundColor(color.getColor());  
  28.             }  
  29.         }  
  30.     }  
  31.       
  32.     @Override  
  33.     public boolean onTouchEvent(MotionEvent event){  
  34.         if (event.getAction()==MotionEvent.ACTION_UP){  
  35.             Intent intent=new Intent();  
  36.             if (color!=null){  
  37.                 color.setColor(Color.GREEN);  
  38.                 intent.putExtra("MyColor", color);  
  39.             }  
  40.             setResult(RESULT_OK,intent);  
  41.             finish();  
  42.         }  
  43.         return super.onTouchEvent(event);  
  44.     }  
  45. }  

 

        下面是main.xml的代码:

 

view plain
  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. <TextView    
  8.     android:layout_width="fill_parent"   
  9.     android:layout_height="wrap_content"   
  10.     android:text="@string/hello"  
  11.     android:id="@+id/text"  
  12.     />  
  13. </LinearLayout>  

 

        注意的是在MainActivity的onActivityResult()中,有一句color=data.getParcelableExtra("MyColor"),这说明的是反序列化后是一个新的MyColor对象,因此要想使用这个对象,我们做了这个赋值语句。

         记得在上一篇《探索Android中的Parcel机制(上)》中提到,如果数据本身是IBinder类型,那么反序列化的结果就是原对象,而不是新建的对象,很显然,如果是这样的话,在反序列化后在MainActivity中就不再需要color=data.getParcelableExtra("MyColor")这句了。因此,换一种MyColor的实现方法,令其中的int color成员变量使用IBinder类型的成员变量来表示。

         新建一个BinderData类继承自Binder,代码如下:

 

view plain
  1. package com.wenbin.test;  
  2.   
  3. import android.os.Binder;  
  4.   
  5. /** 
  6.  * @author 曹文斌 
  7.  * http://blog.csdn.net/caowenbin 
  8.  * 
  9.  */  
  10. public class BinderData extends Binder {  
  11.     public int color;  
  12. }  

  

       修改MyColor的代码如下:

 

view plain
  1. package com.wenbin.test;  
  2.   
  3. import android.graphics.Color;  
  4. import android.os.Parcel;  
  5. import android.os.Parcelable;  
  6.   
  7. /** 
  8.  * @author 曹文斌 
  9.  * http://blog.csdn.net/caowenbin 
  10.  * 
  11.  */  
  12. public class MyColor implements Parcelable {  
  13.     private BinderData data=new BinderData();  
  14.       
  15.     MyColor(){  
  16.         data.color=Color.BLACK;  
  17.     }  
  18.       
  19.     MyColor(Parcel in){  
  20.         data=(BinderData) in.readValue(BinderData.class.getClassLoader());  
  21.     }  
  22.       
  23.     public int getColor(){  
  24.         return data.color;  
  25.     }  
  26.       
  27.     public void setColor(int color){  
  28.         data.color=color;  
  29.     }  
  30.       
  31.     @Override  
  32.     public int describeContents() {  
  33.         return 0;  
  34.     }  
  35.   
  36.     @Override  
  37.     public void writeToParcel(Parcel dest, int flags) {  
  38.         dest.writeValue(data);  
  39.     }  
  40.   
  41.     public static final Parcelable.Creator<MyColor> CREATOR  
  42.         = new Parcelable.Creator<MyColor>() {  
  43.         public MyColor createFromParcel(Parcel in) {  
  44.             return new MyColor(in);  
  45.         }  
  46.           
  47.         public MyColor[] newArray(int size) {  
  48.             return new MyColor[size];  
  49.         }  
  50.     };  
  51. }  

         去掉MainActivity的onActivityResult()中的color=data.getParcelableExtra("MyColor")一句,变成:

 

view plain
  1. @Override  
  2. protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  3.     super.onActivityResult(requestCode, resultCode, data);  
  4.     if (requestCode==SUB_ACTIVITY){  
  5.         if (resultCode==RESULT_OK){  
  6.             if (data.hasExtra("MyColor")){  
  7.                 findViewById(R.id.text).setBackgroundColor(color.getColor());  
  8.             }  
  9.         }  
  10.     }  
  11. }  

         再次运行程序,结果符合预期。

 

         以上就是Parcel在应用程序中的使用方法,与Serialize还是挺相似的,详细的资料当然还是要参考Android SDK的开发文档了。

——欢迎转载,请注明出处 http://blog.csdn.net/caowenbin ——


原创粉丝点击