Android数据传递的五种方法汇总

时间:2023-03-08 18:25:05

Android开发中,在不同模块(如Activity)间经常会有各种各样的数据需要相互传递,我把常用的几种 方法都收集到了一起。它们各有利弊,有各自的应用场景。 我现在把它们集中到一个例子中展示,在例子中每一个按纽代表了一种实现方法。

Android数据传递的五种方法汇总

1. 利用Intent对象携带简单数据

利用Intent的Extra部分来存储我们想要传递的数据,可以传送int, long, char等一些基础类型,对复杂的对象就无能为力了。

        1.1 设置参数

  1. //传递些简单的参数
  2. Intent intentSimple = new Intent();
  3. intentSimple.setClass(MainActivity.this,SimpleActivity.class);
  4. Bundle bundleSimple = new Bundle();
  5. bundleSimple.putString("usr", "xcl");
  6. bundleSimple.putString("pwd", "zj");
  7. intentSimple.putExtras(bundleSimple);
  8. startActivity(intentSimple);

1.2 接收参数

  1. this.setTitle("简单的参数传递例子");
  2. //接收参数
  3. Bundle bunde = this.getIntent().getExtras();
  4. String eml = bunde.getString("usr");
  5. String pwd = bunde.getString("pwd");

2. 利用Intent对象携带如ArrayList之类复杂些的数据

这种原理是和上面一种是一样的,只是要注意下。 在传参数前,要用新增加一个List将对象包起来。

2.1 设置参数

  1. //传递复杂些的参数
  2. Map<String, Object> map1 = new HashMap<String, Object>();
  3. map1.put("key1", "value1");
  4. map1.put("key2", "value2");
  5. List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
  6. list.add(map1);
  7. Intent intent = new Intent();
  8. intent.setClass(MainActivity.this,ComplexActivity.class);
  9. Bundle bundle = new Bundle();
  10. //须定义一个list用于在budnle中传递需要传递的ArrayList<Object>,这个是必须要的
  11. ArrayList bundlelist = new ArrayList();
  12. bundlelist.add(list);
  13. bundle.putParcelableArrayList("list",bundlelist);
  14. intent.putExtras(bundle);
  15. startActivity(intent);

2.1 接收参数

  1. <span style="white-space:pre">  </span>   this.setTitle("复杂参数传递例子");
  2. //接收参数
  3. Bundle bundle = getIntent().getExtras();
  4. ArrayList list = bundle.getParcelableArrayList("list");
  5. //从List中将参数转回 List<Map<String, Object>>
  6. List<Map<String, Object>> lists= (List<Map<String, Object>>)list.get(0);
  7. String sResult = "";
  8. for (Map<String, Object> m : lists)
  9. {
  10. for (String k : m.keySet())
  11. {
  12. sResult += "\r\n"+k + " : " + m.get(k);
  13. }
  14. }

3. 通过实现Serializable接口

3.1 设置参数

利用Java语言本身的特性,通过将数据序列化后,再将其传递出去。

  1. //通过Serializable接口传参数的例子
  2. HashMap<String,String> map2 = new HashMap<String,String>();
  3. map2.put("key1", "value1");
  4. map2.put("key2", "value2");
  5. Bundle bundleSerializable = new Bundle();
  6. bundleSerializable.putSerializable("serializable", map2);
  7. Intent intentSerializable = new Intent();
  8. intentSerializable.putExtras(bundleSerializable);
  9. intentSerializable.setClass(MainActivity.this,
  10. SerializableActivity.class);
  11. startActivity(intentSerializable);

3.2 接收参数

  1. this.setTitle("Serializable例子");
  2. //接收参数
  3. Bundle bundle = this.getIntent().getExtras();
  4. //如果传 LinkedHashMap,则bundle.getSerializable转换时会报ClassCastException,不知道什么原因
  5. //传HashMap倒没有问题。
  6. HashMap<String,String> map =  (HashMap<String,String>)bundle.getSerializable("serializable");
  7. String sResult = "map.size() ="+map.size();
  8. Iterator iter = map.entrySet().iterator();
  9. while(iter.hasNext())
  10. {
  11. Map.Entry entry = (Map.Entry)iter.next();
  12. Object key = entry.getKey();
  13. Object value = entry.getValue();
  14. sResult +="\r\n key----> "+(String)key;
  15. sResult +="\r\n value----> "+(String)value;
  16. }

4. 通过实现Parcelable接口

这个是通过实现Parcelable接口,把要传的数据打包在里面,然后在接收端自己分解出来。这个是Android独有的,在其本身的源码中也用得很多,

效率要比Serializable相对要好。

4.1 首先要定义一个类,用于 实现Parcelable接口

因为其本质也是序列化数据,所以这里要注意定义顺序要与解析顺序要一致噢。

  1. public class XclParcelable implements Parcelable {
  2. //定义要被传输的数据
  3. public int mInt;
  4. public String mStr;
  5. public HashMap<String,String> mMap = new HashMap<String,String>();
  6. //Describe the kinds of special objects contained in this Parcelable's marshalled representation.
  7. public int describeContents() {
  8. return 0;
  9. }
  10. //Flatten this object in to a Parcel.
  11. public void writeToParcel(Parcel out, int flags) {
  12. //等于将数据映射到Parcel中去
  13. out.writeInt(mInt);
  14. out.writeString(mStr);
  15. out.writeMap(mMap);
  16. }
  17. //Interface that must be implemented and provided as a public CREATOR field
  18. //that generates instances of your Parcelable class from a Parcel.
  19. public static final Parcelable.Creator<XclParcelable> CREATOR
  20. = new Parcelable.Creator<XclParcelable>() {
  21. public XclParcelable createFromParcel(Parcel in) {
  22. return new XclParcelable(in);
  23. }
  24. public XclParcelable[] newArray(int size) {
  25. return new XclParcelable[size];
  26. }
  27. };
  28. private XclParcelable(Parcel in) {
  29. //将映射在Parcel对象中的数据还原回来
  30. //警告,这里顺序一定要和writeToParcel中定义的顺序一致才行!!!
  31. mInt = in.readInt();
  32. mStr  = in.readString();
  33. mMap  = in.readHashMap(HashMap.class.getClassLoader());
  34. }
  35. public XclParcelable() {
  36. // TODO Auto-generated constructor stub
  37. }
  38. }

4.2  设置参数

  1. //通过实现Parcelable接口传参的例子
  2. Intent intentParcelable = new Intent();
  3. XclParcelable xp = new XclParcelable();
  4. xp.mInt = 1;
  5. xp.mStr = "字符串";
  6. xp.mMap = new HashMap<String,String>();
  7. xp.mMap.put("key", "value");
  8. intentParcelable.putExtra("Parcelable", xp);
  9. intentParcelable.setClass(MainActivity.this,
  10. ParcelableActivity.class);
  11. startActivity(intentParcelable);

4.3 接收参数

  1. <span style="white-space:pre">      </span>this.setTitle("Parcelable例子");
  2. //接收参数
  3. Intent i = getIntent();
  4. XclParcelable xp = i.getParcelableExtra("Parcelable");
  5. TextView  tv = (TextView)findViewById(R.id.tv);
  6. tv.setText(  " mInt ="+xp.mInt
  7. +"\r\n mStr"+xp.mStr
  8. +"\r\n size()="+xp.mMap.size());

5. 通过单例模式实现参数传递

单例模式的特点就是可以保证系统中一个类有且只有一个实例。这样很容易就能实现,
在A中设置参数,在B中直接访问了。这是几种方法中效率最高的。

5.1  定义一个单实例的类

  1. //单例模式
  2. public class XclSingleton
  3. {
  4. //单例模式实例
  5. private static XclSingleton instance = null;
  6. //synchronized 用于线程安全,防止多线程同时创建实例
  7. public synchronized static XclSingleton getInstance(){
  8. if(instance == null){
  9. instance = new XclSingleton();
  10. }
  11. return instance;
  12. }
  13. final HashMap<String, Object> mMap;
  14. private XclSingleton()
  15. {
  16. mMap = new HashMap<String,Object>();
  17. }
  18. public void put(String key,Object value){
  19. mMap.put(key,value);
  20. }
  21. public Object get(String key)
  22. {
  23. return mMap.get(key);
  24. }
  25. }

5.2 设置参数

  1. //通过单例模式传参数的例子
  2. XclSingleton.getInstance().put("key1", "value1");
  3. XclSingleton.getInstance().put("key2", "value2");
  4. Intent intentSingleton = new Intent();
  5. intentSingleton.setClass(MainActivity.this,
  6. SingletonActivity.class);
  7. startActivity(intentSingleton);

5.3 接收参数

  1. <span style="white-space:pre">          </span>this.setTitle("单例模式例子");
  2. //接收参数
  3. HashMap<String,Object> map = XclSingleton.getInstance().mMap;
  4. String sResult = "map.size() ="+map.size();
  5. //遍历参数
  6. Iterator iter = map.entrySet().iterator();
  7. while(iter.hasNext())
  8. {
  9. Map.Entry entry = (Map.Entry)iter.next();
  10. Object key = entry.getKey();
  11. Object value = entry.getValue();
  12. sResult +="\r\n key----> "+(String)key;
  13. sResult +="\r\n value----> "+(String)value;
  14. }

例子源码放在: 下载