系统入门(3): Android中的Parcel是什么

Parcel,翻译过来是“打包”的意思。打包干什么呢?是为了序列化。
    如果要在进程之间传递一个整数,很简单,直接传就是行了;如果要传一个字符串,就稍微复杂了点:需先分配一块可以容纳字符串的内存,然后将字符串复制到内存中,再传递(新手可能问:为啥不直接把字符串的引用传过去呢?学过C/C++的地球人都知道:进程有自己的内存地址空间,一个进程中的1000地址可能在另一个进程中是100000,java对象的引用跟本上还是内存地址);再如果要传递一个类的实例呢?也是先为类分配内存,然后复制一份再传递可以吗?我认为不可以,我至少可以找到一个理由:类中成员除了属性还有方法,即使属性能完整传过去,但还有方法呢?方法是独立于类对象存在的,所以到另一个进程中再引用同一个方法就要出错了,还是因为独立地址空间的原因。
    Android开发中,很经常在各activity之间传递数据,而跟据Android的设计架构,即使同一个程序中的Activity都不一定运行在同一个进程中,所以处理数据传递时你不能老假设两个activity都运行于同一进程,那么只能按进程间传递数据来处理,使之具有最广泛的适应性。
  那么到底如何在进程之间传递类对象呢?简单来说可以这样做:在进程A中把类中的非默认值的属性和类的唯一标志打成包(这就叫序列化),把这个包传递到进程B,进程B接收到包后,跟据类的唯一标志把类创建出来,然后把传来的属性更新到类对象中,这样进程A和进程B中就包含了两个完全一样的类对象。
    简单点来说:Parcel就是一个存放读取数据的容器, android系统中的binder进程间通信(IPC)就使用了Parcel类来进行客户端与服务端数据的交互,而且AIDL的数据也是通过Parcel来交互的。在Java空间和C++都实现了Parcel,由于它在C/C++中,直接使用了内存来读取数据,因此,它更有效率。
     分析Binder机制中的客户端与服务器端进行实际操作ontransact()函数 :
//参数说明:  
// code :是请求的ID号   
// data :客户端请求发送的参数  
// reply:服务器端返回的结果  
// flags:一些额外的标识,如FLAG_ONEWAY等,通常为0.  
virtual status_t    onTransact( uint32_t code,  
                                const Parcel& data,  
                                Parcel* reply,  

                                uint32_t flags = 0);  

从中我们可以看到Parcel的重要性以及窥探它的使用情况,接下来,我主要分析它的存储机制。  
常用方法介绍:
            obtain()                    获得一个新的parcel ,相当于new一个对象
            dataSize()                  得到当前parcel对象的实际存储空间
            dataCapacity()              得到当前parcel对象的已分配的存储空间, >=dataSize()值  (以空间换时间)
            dataPostion()               获得当前parcel对象的偏移量(类似于文件流指针的偏移量)
            setDataPosition()           设置偏移量
            recyle()                    清空、回收parcel对象的内存
            writeInt(int)               写入一个整数
            writeFloat(float)           写入一个浮点数
            writeDouble(double)         写入一个双精度数
            writeString(string)         写入一个字符串
   当然,还有更多的writeXXX()方法,与之对应的就是readXXX(),具体方法请参阅SDK。
          其中几个值得注意的方法为:
             writeException()        Parcel队头写入“无异常“
             readException()        在Parcel队头读取,若读取值为异常,则抛出该异常;否则,程序正常运行。
一、Parcel的分析
       相信看了前面的值,对Parcel的使用该有了初步印象。那么,Parcel的内部存储机制是怎么样的?偏移量又是什么情况?让我们回忆一下基本数据类型的取值范围:
                   boolean     1bit          1字节
                   char          16bit         2字节
                   int             32bit        4字节
                   long          64bit        8字节
                   float          32bit        4字节
                  double       64bit         8字节
        如果大家对C语言熟悉的话,C语言中结构体的内存对齐和Parcel采用的内存存放机制一样,即读取最小字节为32bit,也即4个字节。高于4个字节的,以实际数据类型进行存放,但得为4byte的倍数。基本公式如下:
             实际存放字节:
                       判别一:  32bit      (<=32bit)             例如:boolean,char,int
                       判别二:  实际占用字节(>32bit)     例如:long,float,String,数组等
        当我们使用readXXX()方法时,读取方法也如上述:
              实际读取字节:
                        判别一:  32bit      (<=32bit)            例如:boolean,char,int
                        判别二:  实际字节大小(>32bit)     例如:long,float,String,数值等
      由上可以知道,当我们写入/读取一个数据时,偏移量至少为4byte(32bit),于是,偏移量的公式如下:
                 f(x)= 4x  (x=0,1,…n)
        事实上,我们可以显示的通过setDataPostion(int postion) 来直接操作我们欲读取数据时的偏移量。毫无疑问,你可以设置任何偏移量,但所读取的值是类型可能有误。因此显示设置偏移量读取值的时候,需要小心。
      另外一个注意点就是我们在writeXXX()和readXXX()时,导致的偏移量是共用的,例如,我们在writeInt(23)后,此时的datapostion=4,如果我们想读取5,简单的通过readInt()是不行的,只能得到0。这时我们只能通过setDataPosition(0)设置为起始偏移量,从起始位置读取四个字节,即23。因此,在读取某个值时,可能需要使用setDataPostion(int postion)使偏移量装换到我们的值处。
      巧用setDataPosition()方法,当我们的parcel对象中只存在某一类型时,我们就可以通过这个方法来快速的读取所有值。具体方法如下:
/**  
     * 前提条件,Parcel存在多个类型相同的对象,本例子以10个float对象说明:  
     */  
    public void readSameType() {  
        Parcel parcel =Parcel.obtain() ;  
        for (int i = 0; i < 10; i++) {  
            parcel.writeDouble(i);  
            Log.i(TAG, "write double ----> " + getParcelInfo());  
        }  
        //方法一 ,显示设置偏移量   
        int i = 0;  
        int datasize = parcel.dataSize();  
        while (i < datasize) {  
            parcel.setDataPosition(i);  
            double fvalue = parcel.readDouble();  
            Log.i(TAG, " read double is=" + fvalue + ", --->" + getParcelInfo());  
            i += 8; // double占用字节为 8byte   
        }  
//      方法二,由于对象的类型一致,我们可以直接利用readXXX()读取值会产生偏移量  
//      parcel.setDataPosition(0)  ;  //  
//      while(parcel.dataPosition()<parcel.dataSize()){  
//          double fvalue = parcel.readDouble();  
//          Log.i(TAG, " read double is=" + fvalue + ", --->" + getParcelInfo());  
//      }  
    }  

由于可能存在读取值的偏差,一个默认的取值规范为:
        1、  读取复杂对象时: 对象匹配时,返回当前偏移位置的该对象;
                 对象不匹配时,返回null对象 ;
        2、  读取简单对象时: 对象匹配时,返回当前偏移位置的该对象 ;
                 对象不匹配时,返回0;

 下面,给出一张浅显的Parcel的存放空间图,希望大家在理解的同时,更能体味其中滋味。有点简单,求谅解。
相信通过前面的介绍,你一定很了解了了Parcel的存储机制,下面给定一应用程序来实践。

 1、布局文件如下:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     android:orientation="vertical" android:layout_width="fill_parent"    
  4.     android:layout_height="fill_parent">    
  5.     <TextView android:layout_width="fill_parent"    
  6.         android:layout_height="wrap_content" android:text="@string/hello" />    
  7.     <LinearLayout android:orientation="horizontal"    
  8.         android:layout_width="fill_parent" android:layout_height="wrap_content">    
  9.         <Button android:id="@+id/btWriteByte" android:layout_width="wrap_content"    
  10.             android:layout_height="wrap_content" android:text="写入一个byte值"></Button>    
  11.         <Button android:id="@+id/btWriteInt" android:layout_width="wrap_content"    
  12.             android:layout_height="wrap_content" android:text="写入一个int值"></Button>    
  13.     </LinearLayout>    
  14.     <LinearLayout android:orientation="horizontal"    
  15.         android:layout_width="fill_parent" android:layout_height="wrap_content">    
  16.         <Button android:id="@+id/btWriteDouble" android:layout_width="wrap_content"    
  17.             android:layout_height="wrap_content" android:text="写入一个double值"></Button>    
  18.         <Button android:id="@+id/btWriteString" android:layout_width="wrap_content"    
  19.             android:layout_height="wrap_content" android:text="写入一个String值"></Button>    
  20.     </LinearLayout>    
  21.     <View android:layout_width="fill_parent" android:layout_height="2dip"    
  22.         android:background="#FF1493"></View>    
  23.     <LinearLayout android:orientation="horizontal"    
  24.         android:layout_marginTop="5dip" android:layout_width="fill_parent"    
  25.         android:layout_height="wrap_content">    
  26.         <Button android:id="@+id/btReadByte" android:layout_width="wrap_content"    
  27.             android:layout_height="wrap_content" android:text="读取一个byte值"></Button>    
  28.         <Button android:id="@+id/btReadInt" android:layout_width="wrap_content"    
  29.             android:layout_height="wrap_content" android:text="读取一个int值"></Button>    
  30.     </LinearLayout>    
  31.     <LinearLayout android:orientation="horizontal"    
  32.         android:layout_width="fill_parent" android:layout_height="wrap_content">    
  33.         <Button android:id="@+id/btReadDouble" android:layout_width="wrap_content"    
  34.             android:layout_height="wrap_content" android:text="读取一个double值"></Button>    
  35.         <Button android:id="@+id/btReadString" android:layout_width="wrap_content"    
  36.             android:layout_height="wrap_content" android:text="读取一个String值"></Button>    
  37.     </LinearLayout>    
  38.     <View android:layout_width="fill_parent" android:layout_height="2dip"    
  39.         android:background="#FF1493"></View>    
  40.     <Button android:id="@+id/btSameType" android:layout_width="wrap_content"    
  41.         android:layout_height="wrap_content" android:text="利用setDataPosition读取多个值"></Button>    
  42. </LinearLayout>    

2、配置文件如下:

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"    
  3.       package="com.qinjuning.parcel"    
  4.       android:versionCode="1"    
  5.       android:versionName="1.0">    
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">    
  7.         <activity android:name=".PracelAcitivity"  android:label="@string/app_name">    
  8.             <intent-filter>    
  9.                 <action android:name="android.intent.action.MAIN" />    
  10.                 <category android:name="android.intent.category.LAUNCHER" />    
  11.             </intent-filter>    
  12.         </activity>    
  13.     </application>    
  14. </manifest>     

3、程序主文件如下:

[java]  view plain copy
  1. package org.newfacer.MainActivity;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.os.Parcel;  
  6. import android.util.Log;  
  7. import android.view.View;  
  8. import android.widget.Button;  
  9.   
  10.  class PracelAcitivity extends Activity  {  
  11.   
  12.     private static String TAG = "PARCELTEST";  
  13.     // Button ID  
  14.     private static int[] btIds = new int[] { R.id.btWriteByte, R.id.btWriteInt,  
  15.             R.id.btReadDouble, R.id.btWriteString, R.id.btReadByte,  
  16.             R.id.btReadInt, R.id.btReadDouble, R.id.btReadString,  
  17.             R.id.btSameType };  
  18.     // 每种类型的当前值  
  19.     private byte cur_byte = 1// 每次总写入 false  
  20.     private int cur_int = 10// 写入值 cur_int ++ ;  
  21.     private double cur_float = 100.0d; // 写入值 cur_float++ ;  
  22.     private String cur_str = "QinJun -->" + cur_int; // 写入值 "QinJun -->"+cur_int  
  23.   
  24.     private Parcel parcel = null;  
  25.   
  26.     @Override  
  27.     public void onCreate(Bundle savedInstanceState) {  
  28.         super.onCreate(savedInstanceState);  
  29.         setContentView(R.layout.main);  
  30.         for (int i = 0; i < btIds.length; i++) {  
  31.             Button bt = (Button) findViewById(btIds[i]);  
  32.             bt.setOnClickListener(new MYClickListener() );  
  33.   
  34.         }  
  35.         parcel = Parcel.obtain(); // 获得一个Parcel对象 ,相当于new一个,初始大小为0  
  36.         Log.i(TAG, "The original parcel info" + getParcelInfo());  
  37.     }  
  38.     class MYClickListener implements View.OnClickListener  
  39.     {  
  40.          @Override  
  41.          public void onClick(View view) {  
  42.             // TODO Auto-generated method stub  
  43.             int viewId = view.getId();  
  44.             switch (viewId) {  
  45.             case R.id.btWriteByte:  
  46.                 parcel.setDataPosition(0);  
  47.                 parcel.writeByte(cur_byte);  
  48.                 Log.i(TAG, " after write byte, --->" + getParcelInfo());  
  49.                 break;  
  50.             case R.id.btWriteInt:  
  51.                 parcel.writeInt(cur_int);  
  52.                 Log.i(TAG, " after write int, --->" + getParcelInfo());  
  53.                 break;  
  54.             case R.id.btWriteDouble:  
  55.                 parcel.writeDouble(cur_float);  
  56.                 Log.i(TAG, " after write float, --->" + getParcelInfo());  
  57.                 break;  
  58.             case R.id.btWriteString:  
  59.                 parcel.writeString(cur_str);  
  60.                 Log.i(TAG, " after write String, --->" + getParcelInfo());  
  61.                 break;  
  62.             case R.id.btReadByte:  
  63.                 byte b = parcel.readByte();  
  64.                 Log.i(TAG, " read byte is=" + b + ", --->" + getParcelInfo()  
  65.                         + "String");  
  66.                 break;  
  67.             case R.id.btReadInt:  
  68.                 int i = parcel.readInt();  
  69.                 Log.i(TAG, " read int is=" + i + ", --->" + getParcelInfo());  
  70.                 break;  
  71.             case R.id.btReadDouble:  
  72.                 float f = parcel.readFloat();  
  73.                 readSameType();  
  74.                 Log.i(TAG, " read float is=" + f + ", --->" + getParcelInfo());  
  75.                 break;  
  76.             case R.id.btReadString:  
  77.                 parcel.setDataPosition(0);  
  78.                 String str = parcel.readString();  
  79.                 Log.i(TAG, " read float is=" + str + ", --->" + getParcelInfo());  
  80.                 break;  
  81.             case R.id.btSameType:  
  82.                 readSameType();  
  83.                 break;  
  84.             default:  
  85.                 break;  
  86.             }  
  87.         }  
  88.   
  89.   
  90.     }  
  91.   
  92.     private String getParcelInfo() {// 得到parcel的信息  
  93.         return "dataSize = " + parcel.dataSize() + ", dataCapacity="  
  94.                 + parcel.dataCapacity() + ", dataPositon = "  
  95.                 + parcel.dataPosition();  
  96.     }  
  97.   
  98.     /** 
  99.      * 前提条件,Parcel存在多个类型相同的对象,本例子以10个float对象说明: 
  100.      */  
  101.     public void readSameType() {  
  102.   
  103.         for (int i = 0; i < 10; i++) {  
  104.             parcel.writeDouble(i);  
  105.             Log.i(TAG, "write double ----> " + getParcelInfo());  
  106.         }  
  107.         //方法一 ,显示设置偏移量  
  108.         int i = 0;  
  109.         int datasize = parcel.dataSize();  
  110.         while (i < datasize) {  
  111.             parcel.setDataPosition(i);  
  112.             double fvalue = parcel.readDouble();  
  113.             Log.i(TAG, " read double is=" + fvalue + ", --->" + getParcelInfo());  
  114.             i += 8// double占用字节为 8byte  
  115.         }  
  116. //      方法二,由于对象的类型一致,我们可以直接利用readXXX()读取值会产生偏移量  
  117. //      parcel.setDataPosition(0)  ;  //  
  118. //      while(parcel.dataPosition()<parcel.dataSize()){  
  119. //          double fvalue = parcel.readDouble();  
  120. //          Log.i(TAG, " read double is=" + fvalue + ", --->" + getParcelInfo());  
  121. //      }  
  122.     }  
  123. }  

由于取值时,可能存在类型的转换,因此点击按钮时,可能不会产生预期结果。因此,得保证偏移量对应数值的正确性。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值