下面我们将要实现的功能是是将一个MyObject 对象从CurrrentActivity 中传递到 AimActivity中
要在不同的Activity传递对象,首先这个对象必须实现Serializable 以说明它是可序列化的。
如
public class MyObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = 3040176837769962141L;
public String url;
public String localFileName;
}
android中Activity之间传递数据使用的是Intent,现在我们就把一个BriefAttachment 对象实例用Itent 从一个Activity中传到另一个。
1 首先我们要把这个对象写入ByteArrayOutputStream 中 在以ByteArray的形式表示这个对象,然后把这个ByteArray 装到Intent中
MyObject myObject = new MyObject ();
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
try {
ObjectOutputStream objStream = new ObjectOutputStream(byteStream);
objStream.writeObject(myObject );
} catch (IOException e) {
log.warn("fail to serialize BriefAttachment!");
return; // should not happen, so donot do error handling
}
Intent intent = new Intent(CurrentActivity.this, AimActivity.class);
intent.putExtra(AimActivity.IMAGES, byteStream.toByteArray());
startActivityForResult(intent, 2);
下面是AimActivity 从Intent中取出这个对象的方法
Intent intent = getIntent();
byte[] bytes = intent.getByteArrayExtra(IMAGES);
if (bytes != null) {
ByteArrayInputStream byteStream = new ByteArrayInputStream(bytes);
List<BriefAttachment> images = null;
try {
ObjectInputStream objStream = new ObjectInputStream(byteStream);
myObject = objStream.readObject();
这样就完成了对象在不同的Activity中传递的任务
Note:这里我们是将对象写入ByteArrayOutputStream 输出流当中,但是我们需要一个ObjectOutputStream
作为连接myObjecy 和 ByteArrayOutputStream 之间的管道,在将对象读到ObjectOutputStream 中。