Intent可以传递序列化对象, 但要求实现Parcelable 或 Serializable接口
Intent传递序列化对象有如下方法
public Intent putExtra(String name, Parcelable value)
public Intent putExtra(String name, Serializable value)
如果一次传递多个序列化对象, 可以放到一个集合里面一起传递.
intent.putExtra("key", (Serializable) list);
需要将list强转为Serializable
源码中可以看到ArrayList也是实现了Serializable接口的
public class ArrayList<E> extends AbstractList<E> implements Cloneable, Serializable, RandomAccess
注意: Bean也需要序列化
public class Music implements Serializable {
private String name;
private String artist;
public Music(String name, String artist) {
this.name = name;
this.artist = artist;
}
}
List<Music> list = new ArrayList<>();
list.add(new Music("Delicious Way", "Mai Kuraki"));
list.add(new Music("STAND BY YOU", "Mai Kuraki"));
Intent intent = new Intent();
intent.putExtra("key", (Serializable) list);
setResult(RESULT_OK, intent);
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK) {
List<Music> musics = (List<Music>) data.getSerializableExtra("key");
for (Music music : musics) {
if (BuildConfig.DEBUG) Log.d("MainActivity", "music:" + music.toString());
}
}
}
logcat中打印出
D/MainActivity: music:Music{name='Delicious Way', artist='Mai Kuraki'}
D/MainActivity: music:Music{name='STAND BY YOU', artist='Mai Kuraki'}
Bundle中同样可以put序列化对象, 对应的方法:
public void putSerializable(@Nullable String key, @Nullable Serializable value)
public void putParcelable(@Nullable String key, @Nullable Parcelable value)
public void putParcelableArray(@Nullable String key, @Nullable Parcelable[] value)
public void putParcelableArrayList(@Nullable String key,@Nullable ArrayList<? extends Parcelable> value)