模式 1:直接通过 Intent
传递数据(最简单)
发送方
Intent intent = new Intent(MainActivity.this, TargetActivity.class);
intent.putExtra("key_string", "文本数据");
intent.putExtra("key_int", 100);
intent.putExtra("key_boolean", true);
startActivity(intent);
接收方
Intent intent = getIntent();
String text = intent.getStringExtra("key_string");
int number = intent.getIntExtra("key_int", 0); // 0是默认值
boolean flag = intent.getBooleanExtra("key_boolean", false);
模式 2:通过 Bundle
打包传递(适合批量数据)
发送方
Intent intent = new Intent(MainActivity.this, TargetActivity.class);
Bundle bundle = new Bundle();
bundle.putString("key_string", "文本数据");
bundle.putInt("key_int", 100);
intent.putExtras(bundle); // 关键!将Bundle附加到Intent
startActivity(intent);
接收方
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String text = bundle.getString("key_string");
int number = bundle.getInt("key_int", 0);
}
模式 3:传递复杂对象(需实现 Parcelable
或 Serializable
)
对象类实现 Parcelable
(推荐)
public class User implements Parcelable {
private String name;
private int age;
// 构造方法、Getter/Setter 省略...
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel in) {
return new User(in.readString(), in.readInt());
}
};
}
发送方
User user = new User("张三", 25);
Intent intent = new Intent(this, TargetActivity.class);
intent.putExtra("key_user", user); // 直接传递对象
startActivity(intent);
接收方
User user = getIntent().getParcelableExtra("key_user");
模式 4:传递数组或集合
发送方
Intent intent = new Intent(this, TargetActivity.class);
// 传递String数组
intent.putExtra("key_array", new String[]{"A", "B", "C"});
// 传递ArrayList(需指定泛型)
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
intent.putIntegerArrayListExtra("key_list", list);
startActivity(intent);
接收方
String[] array = getIntent().getStringArrayExtra("key_array");
ArrayList<Integer> list = getIntent().getIntegerArrayListExtra("key_list");
模式 5:通过 Bundle
传递二进制数据(如文件字节流)
发送方
byte[] fileData = getFileBytes(); // 获取文件的字节数组
Intent intent = new Intent(this, TargetActivity.class);
Bundle bundle = new Bundle();
bundle.putByteArray("key_file_data", fileData);
intent.putExtras(bundle);
startActivity(intent);
接收方
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
byte[] fileData = bundle.getByteArray("key_file_data");
// 处理二进制数据...
}
最佳实践总结
- 简单数据:直接用
Intent.putExtra()
。 - 批量数据:用
Bundle
打包后传递。 - 对象传递:优先实现
Parcelable
(性能优于Serializable
)。 - 集合数据:使用专用方法如
putStringArrayListExtra()
。 - 二进制数据:用
putByteArray()
避免编码问题。
关键注意事项:
- 接收方始终检查
Intent
或Bundle
是否为null
。 - 键名(如
"key_string"
)需保持发送和接收端一致。 - 跨进程传输时,
Bundle
大小限制为 1MB(Android 8.0+)。