activity之间有个很好的传递数据的工具–>Intent。
传递基本数据类型
如果是八大基本数据类型,可以直接传递:
Intent intent = new Intent(activityA,activityB);
intent.putExtra("key1",111);
startActivity(intent);
在activityB中接收
Intent intent = getIntent();
int value1 = intent.getInt("key1",1);
传递可序列化对象
序列化Student类
public class Student implements Serializable{
private String username;
private int age;
public void setUsername(String username){
this.username = username;
}
public String getUsername(){
return this.username;
}
public void setAge(){
this.age = age;
}
public int getAge(){
return this.age;
}
}
activityA中发送数据
Student student = new Student();
student.setUsername("大飞");
student.setAge(18);
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable("student",student);
intent.putExtras(bundle);
startActivity(activityA,activityB);
在activityB中接收数据
Student student = (Student)getIntent.getExtras("student");
传递bitmap
思路:将bitmap对象转换为字节数组传递
activityA发送数据:
Intent intent = new Intent(activityA,activityB);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//下面方法表示压缩图片,中间的值越小,压缩比例越大,失真也约厉害,100表示不压缩
bitmap.compress(Bitmap.CompressFormat.PNG,100,baos);
byte[] byteArray = baos.toByteArray();
intent.putExtra("photoByte",byteArray);
startActivity(intent);
activityB接收数据
byte[] byteArray = getIntent().getByteArrayExtra("photoByte");
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray,0,byteArray.length);