Android五種數據傳遞方法彙總

Android開發中,在不一樣模塊(如Activity)間常常會有各類各樣的數據須要相互傳遞,我把經常使用的幾種java

方法都收集到了一塊兒。它們各有利弊,有各自的應用場景。安全

我如今把它們集中到一個例子中展現,在例子中每個按紐表明了一種實現方法。多線程

1. 利用Intent對象攜帶簡單數據ide

利用Intent的Extra部分來存儲咱們想要傳遞的數據,能夠傳送int, long, char等一些基礎類型,對複雜的對象就無能爲力了。this

        1.1 設置參數spa

//傳遞些簡單的參數  
Intent intentSimple = new Intent();  
intentSimple.setClass(MainActivity.this,SimpleActivity.class);  
  
Bundle bundleSimple = new Bundle();  
bundleSimple.putString("usr", "xcl");  
bundleSimple.putString("pwd", "zj");  
intentSimple.putExtras(bundleSimple);  
               
startActivity(intentSimple);

1.2 接收參數線程

this.setTitle("簡單的參數傳遞例子");  
  
//接收參數  
Bundle bunde = this.getIntent().getExtras();  
String eml = bunde.getString("usr");  
String pwd = bunde.getString("pwd");


2. 利用Intent對象攜帶如ArrayList之類複雜些的數據code

這種原理是和上面一種是同樣的,只是要注意下。 在傳參數前,要用新增長一個List將對象包起來。對象

2.1 設置參數接口

//傳遞複雜些的參數  
Map<String, Object> map1 = new HashMap<String, Object>();  
map1.put("key1", "value1");  
map1.put("key2", "value2");  
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
list.add(map1);  
                       
Intent intent = new Intent();  
intent.setClass(MainActivity.this,ComplexActivity.class);  
Bundle bundle = new Bundle();  
//須定義一個list用於在budnle中傳遞須要傳遞的ArrayList<Object>,這個是必需要的  
ArrayList bundlelist = new ArrayList();   
bundlelist.add(list);   
bundle.putParcelableArrayList("list",bundlelist);  
intent.putExtras(bundle);                
startActivity(intent);

2.1 接收參數

<span style="white-space:pre">  </span>   this.setTitle("複雜參數傳遞例子");  
          
        //接收參數  
         Bundle bundle = getIntent().getExtras();   
         ArrayList list = bundle.getParcelableArrayList("list");  
        //從List中將參數轉回 List<Map<String, Object>>  
         List<Map<String, Object>> lists= (List<Map<String, Object>>)list.get(0);  
         
         String sResult = "";  
         for (Map<String, Object> m : lists)    
         {    
             for (String k : m.keySet())    
             {    
                  sResult += "\r\n"+k + " : " + m.get(k);    
             }            
         }

3. 經過實現Serializable接口

3.1 設置參數

利用Java語言自己的特性,經過將數據序列化後,再將其傳遞出去。

//經過Serializable接口傳參數的例子  
HashMap<String,String> map2 = new HashMap<String,String>();  
map2.put("key1", "value1");  
map2.put("key2", "value2");  
  
Bundle bundleSerializable = new Bundle();  
bundleSerializable.putSerializable("serializable", map2);  
Intent intentSerializable = new Intent();     
intentSerializable.putExtras(bundleSerializable);  
intentSerializable.setClass(MainActivity.this,   
                            SerializableActivity.class);                      
startActivity(intentSerializable);

3.2 接收參數

this.setTitle("Serializable例子");  
  
  //接收參數  
   Bundle bundle = this.getIntent().getExtras();      
   //若是傳 LinkedHashMap,則bundle.getSerializable轉換時會報ClassCastException,不知道什麼緣由  
   //傳HashMap倒沒有問題。        
   HashMap<String,String> map =  (HashMap<String,String>)bundle.getSerializable("serializable");  
                              
String sResult = "map.size() ="+map.size();  
  
Iterator iter = map.entrySet().iterator();  
while(iter.hasNext())  
{  
    Map.Entry entry = (Map.Entry)iter.next();  
    Object key = entry.getKey();  
    Object value = entry.getValue();  
    sResult +="\r\n key----> "+(String)key;  
    sResult +="\r\n value----> "+(String)value;            
}


4. 經過實現Parcelable接口

這個是經過實現Parcelable接口,把要傳的數據打包在裏面,而後在接收端本身分解出來。這個是Android獨有的,在其自己的源碼中也用得不少,

效率要比Serializable相對要好。

4.1 首先要定義一個類,用於 實現Parcelable接口

由於其本質也是序列化數據,因此這裏要注意定義順序要與解析順序要一致噢。

public class XclParcelable implements Parcelable {  
      
    //定義要被傳輸的數據  
    public int mInt;  
    public String mStr;  
    public HashMap<String,String> mMap = new HashMap<String,String>();  
      
    //Describe the kinds of special objects contained in this Parcelable's marshalled representation.  
    public int describeContents() {  
        return 0;  
    }  
  
    //Flatten this object in to a Parcel.  
    public void writeToParcel(Parcel out, int flags) {  
        //等於將數據映射到Parcel中去  
        out.writeInt(mInt);          
        out.writeString(mStr);  
        out.writeMap(mMap);  
    }  
  
    //Interface that must be implemented and provided as a public CREATOR field   
    //that generates instances of your Parcelable class from a Parcel.   
    public static final Parcelable.Creator<XclParcelable> CREATOR  
            = new Parcelable.Creator<XclParcelable>() {  
        public XclParcelable createFromParcel(Parcel in) {  
            return new XclParcelable(in);  
        }  
  
        public XclParcelable[] newArray(int size) {  
            return new XclParcelable[size];  
        }  
    };  
      
    private XclParcelable(Parcel in) {  
        //將映射在Parcel對象中的數據還原回來  
        //警告,這裏順序必定要和writeToParcel中定義的順序一致才行!!!  
        mInt = in.readInt();          
        mStr  = in.readString();  
        mMap  = in.readHashMap(HashMap.class.getClassLoader());  
    }  
  
    public XclParcelable() {  
        // TODO Auto-generated constructor stub  
    }  
}

4.2  設置參數

//經過實現Parcelable接口傳參的例子  
                    Intent intentParcelable = new Intent();                   
                    XclParcelable xp = new XclParcelable();               
                    xp.mInt = 1;  
                    xp.mStr = "字符串";  
                    xp.mMap = new HashMap<String,String>();  
                    xp.mMap.put("key", "value");                      
                    intentParcelable.putExtra("Parcelable", xp);                      
                    intentParcelable.setClass(MainActivity.this,   
                                              ParcelableActivity.class);     
                    startActivity(intentParcelable);

4.3 接收參數

<span style="white-space:pre">      </span>this.setTitle("Parcelable例子");  
          
        //接收參數  
        Intent i = getIntent();     
        XclParcelable xp = i.getParcelableExtra("Parcelable");     
  
        TextView  tv = (TextView)findViewById(R.id.tv);  
        tv.setText(  " mInt ="+xp.mInt   
                    +"\r\n mStr"+xp.mStr  
                    +"\r\n size()="+xp.mMap.size());


5. 經過單例模式實現參數傳遞

        單例模式的特色就是能夠保證系統中一個類有且只有一個實例。這樣很容易就能實現,

 

在A中設置參數,在B中直接訪問了。這是幾種方法中效率最高的。

5.1  定義一個單實例的類

public class XclSingleton  
{  
    //單例模式實例  
    private static XclSingleton instance = null;  
      
    //synchronized 用於線程安全,防止多線程同時建立實例  
    public synchronized static XclSingleton getInstance(){  
        if(instance == null){  
            instance = new XclSingleton();  
        }     
        return instance;  
    }     
      
    final HashMap<String, Object> mMap;  
    public XclSingleton()  
    {  
        mMap = new HashMap<String,Object>();  
    }  
      
    public void put(String key,Object value){  
        mMap.put(key,value);  
    }  
      
    public Object get(String key)  
    {  
        return mMap.get(key);  
    }  
      
}

5.2 設置參數

//經過單例模式傳參數的例子  
XclSingleton.getInstance().put("key1", "value1");  
XclSingleton.getInstance().put("key2", "value2");  
  
Intent intentSingleton = new Intent();                
intentSingleton.setClass(MainActivity.this,   
                        SingletonActivity.class);                     
startActivity(intentSingleton);   
5.3 接收參數
[java] 
<span style="white-space:pre">      </span>this.setTitle("單例模式例子");  
          
        //接收參數  
        HashMap<String,Object> map = XclSingleton.getInstance().mMap;                           
        String sResult = "map.size() ="+map.size();       
          
        //遍歷參數  
        Iterator iter = map.entrySet().iterator();  
        while(iter.hasNext())  
        {  
            Map.Entry entry = (Map.Entry)iter.next();  
            Object key = entry.getKey();  
            Object value = entry.getValue();  
            sResult +="\r\n key----> "+(String)key;  
            sResult +="\r\n value----> "+(String)value;                
        }
相關文章
相關標籤/搜索