1. 程式人生 > >android五中資料傳遞方式

android五中資料傳遞方式

Android開發中,在不同模組(如Activity)間經常會有各種各樣的資料需要相互傳遞,我把常用的幾種
方法都收集到了一起。它們各有利弊,有各自的應用場景。
我現在把它們集中到一個例子中展示,在例子中每一個按紐代表了一種實現方法。

1. 利用Intent物件攜帶簡單資料

利用Intent的Extra部分來儲存我們想要傳遞的資料,可以傳送int, long, char等一些基礎型別,對複雜的物件就無能為力了。

1.1 設定引數
[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

//傳遞些簡單的引數
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 接收引數
[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

this.setTitle("簡單的引數傳遞例子");

//接收引數
Bundle bunde = this.getIntent().getExtras();
String eml = bunde.getString("usr");
String pwd = bunde.getString("pwd");


2. 利用Intent物件攜帶如ArrayList之類複雜些的資料

這種原理是和上面一種是一樣的,只是要注意下。 在傳引數前,要用新增加一個List將物件包起來。

2.1 設定引數

[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

//傳遞複雜些的引數
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 接收引數
[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

<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語言本身的特性,通過將資料序列化後,再將其傳遞出去。

[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

//通過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 接收引數
[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

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介面

因為其本質也是序列化資料,所以這裡要注意定義順序要與解析順序要一致噢。

[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

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 設定引數

[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

//通過實現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 接收引數

[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

<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 定義一個單例項的類
[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

//單例模式
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;
private 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 設定引數

[java] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

//通過單例模式傳引數的例子
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] view plaincopy在CODE上檢視程式碼片派生到我的程式碼片

<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;
}