Android数据传递方法汇总

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

1.1 发送数据

 //传递些简单的参数
  Intent intentSimple = new Intent();
  intentSimple.setClass(MainActivity.this, Main2Activity.class);
  Bundle bundleSimple = new Bundle();
  bundleSimple.putString("name", "jay");
  bundleSimple.putString("age", "18");
  intentSimple.putExtras(bundleSimple);
  startActivity(intentSimple);

1.2 接收数据

    //接收参数
        Bundle bunde = this.getIntent().getExtras();
        String name = bunde.getString("name");
        String age = bunde.getString("age");

接收结果日志:

Main2Activity: name: jay   age: 18

2、传递复杂数据,例如map

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

2.1.1 发送数据

		//传递复杂些的参数
		Map map1 = new HashMap();
		map1.put("key1", "value1");
		map1.put("key2", "value2");
		List> list = new ArrayList>();
		list.add(map1);
							 
		Intent intent = new Intent();
		intent.setClass(MainActivity.this,ComplexActivity.class);
		Bundle bundle = new Bundle();
		//须定义一个list用于在budnle中传递需要传递的ArrayList,这个是必须要的
		ArrayList bundlelist = new ArrayList(); 
		bundlelist.add(list); 
		bundle.putParcelableArrayList("list",bundlelist);
		intent.putExtras(bundle);              
		startActivity(intent);
 
  

2.1.2 接收数据

//接收参数
	     Bundle bundle = getIntent().getExtras(); 
	     ArrayList list = bundle.getParcelableArrayList("list");
	    //从List中将参数转回 List>
	     List> lists= (List>)list.get(0);
	   
	     String sResult = "";
	     for (Map m : lists)  
	     {  
	    	 for (String k : m.keySet())  
	         {  
	    	      sResult += "\r\n"+k + " : " + m.get(k);  
	         }  	    
	     } 

2.2 通过实现Serializable接口

2.2.1 发送数据

  //              通过Serializable接口传参数的例子
                HashMap map2 = new HashMap();
                map2.put("key1", "value1");
                map2.put("key2", "value2");
                map2.put("key3", "value3");
                map2.put("key4", "value4");
                map2.put("key5", "value5");

                Bundle bundleSerializable = new Bundle();
                bundleSerializable.putSerializable("serializable", map2);
                Intent intentSerializable = new Intent();
                intentSerializable.putExtras(bundleSerializable);
                intentSerializable.setClass(MainActivity.this,
                        Main2Activity.class);
                startActivity(intentSerializable);

2.2.2 接收数据

  // 接收参数
        Bundle bundle = this.getIntent().getExtras();
        //如果传 LinkedHashMap,则bundle.getSerializable转换时会报ClassCastException,不知道什么原因
        //传HashMap倒没有问题。
        HashMap map =  (HashMap)bundle.getSerializable("serializable");


        for (Map.Entry m:map.entrySet()){
            Log.e(TAG, "onCreate: "+m.getKey()+"  "+m.getValue() );

        }

2.2.3 传递对象

public class Person implements Serializable{  
private String name;  
private int age;  
public String getName() {  
        return name;  
    }  
public void setName(String name) {  
        this.name = name;  
    }  
public int getAge() {  
        return age;  
        }  
public void setAge(int age) {  
        this.age = age;  
    }  
}  

发送数据:

Person person = new Person();  
person.setName("Tom");  
person.setAge(20);  
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);  
intent.putExtra("person_data", person);  
startActivity(intent); 

接收数据:

Person person = (Person) getIntent().getSerializableExtra("person_data"); 

2.3 通过实现Parcelable接口

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

效率要比Serializable相对要好

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

public class XclParcelable  implements Parcelable {
    //定义要被传输的数据
    public int mInt;
    public String mStr;
    public HashMap mMap = new HashMap();

    private XclParcelable(Parcel in) {
        mInt=in.readInt();
        mStr=in.readString();
        mMap=in.readHashMap(HashMap.class.getClassLoader());
    }
    public  XclParcelable(){}

    public static final Creator CREATOR = new Creator() {
        @Override
        public XclParcelable createFromParcel(Parcel in) {
            return new XclParcelable(in);
        }

        @Override
        public XclParcelable[] newArray(int size) {
            return new XclParcelable[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        等于将数据映射到Parcel中
        dest.writeInt(mInt);
        dest.writeString(mStr);
        dest.writeMap(mMap);
    }
}

2.3.2 设置参数

//通过实现Parcelable接口传参的例子
                Intent intentParcelable = new Intent();
                XclParcelable xp = new XclParcelable();
                xp.mInt = 1;
                xp.mStr = "字符串";
                xp.mMap = new HashMap();
                xp.mMap.put("key", "value");
                intentParcelable.putExtra("Parcelable", xp);
                intentParcelable.setClass(MainActivity.this,
                        Main2Activity.class);
                startActivity(intentParcelable);

2.3.3 接受参数

  //接收参数
        Intent i = getIntent();
        XclParcelable xp = i.getParcelableExtra("Parcelable");

        Log.e(TAG, "onCreate: "+" mInt ="+xp.mInt
                +"\r\n mStr"+xp.mStr
                +"\r\n size()="+xp.mMap.size() );

3.EventBus传递数据

引入依赖 

    implementation 'org.greenrobot:eventbus:3.1.1'

构造消息发送类(post调用的对象)

public class Student {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
}

注册:(一般在onCreate( )方法中注册)

EventBus.getDefault().register(this);

发布消息 

EventBus.getDefault().post(new Student("刘哈哈", 27));
//粘性事件
 EventBus.getDefault().postSticky(new Student("刘哈哈", 27));

接收事件:

@Subscribe(threadMode = ThreadMode.MAIN)
public void studentEventBus(Student student){
    mShow.setText("姓名:"+student.getName()+" "+"年龄:"+student.getAge());
}
粘性事件接收

 @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void studentEventBus(Student student){
    mShow.setText("姓名:"+student.getName()+" "+"年龄:"+student.getAge());
}

解注册(防止内存泄漏)(一般在onDestroy( )方法中调用):

EventBus.getDefault().unregister(this);

参考链接:Android五种数据传递方法汇总

你可能感兴趣的:(Android,android,java,开发语言)