这完全取决于您想要对象的地点和时间。你可以这样做:
class Artist implements Serializable{
public static final String EXTRA = "com.your.package.ARTIST_EXTRA";
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
活动一:
public void onCreate(Bundle savedInstance){
// ....
Artist artist = new Artist();
artist.setName("Rolf");
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(Artist.EXTRA, artist);
startActivity(intent);
}
活动二:
然后,您可以在第二个活动中引用您的艺术家:
public void onCreate(Bundle savedInstance){
// ....
Artist artist = (Artist) getIntent().getSerializableExtra(Artist.EXTRA);
Log.d("YourApp", "I have the artist! "+ artist.getName());
}
注意您正在序列化的内容,因为您无法序列化某些对象。
另一种方法是拥有一个扩展 Application 并在其中保留引用的类,然后您可以从任何 Activity 上下文中检索它。