Android开发-Activity传递信息

一、使用 Intent 传递基本数据类型(最常用)

IntentActivity 之间通信的“信使”。通过 IntentputExtra() 方法,可以轻松传递基本数据类型和 String

1. 传递数据(发送方)

// 在当前 Activity 中
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);

// 传递基本数据类型
intent.putExtra("user_id", 12345);
intent.putExtra("user_name", "张三");
intent.putExtra("is_vip", true);
intent.putExtra("balance", 99.9);

// 启动目标 Activity
startActivity(intent);

2. 接收数据(接收方)

// 在目标 Activity 的 onCreate() 中
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_target);

    // 从 Intent 中获取数据
    int userId = getIntent().getIntExtra("user_id", -1); // -1 是默认值
    String userName = getIntent().getStringExtra("user_name");
    boolean isVip = getIntent().getBooleanExtra("is_vip", false);
    double balance = getIntent().getDoubleExtra("balance", 0.0);

    // 使用这些数据...
    Log.d("Data", "User: " + userName + ", Balance: " + balance);
}

支持的数据类型

  • booleanbytecharshortintlongfloatdouble
  • String
  • boolean[]byte[]char[]short[]int[]long[]float[]double[]String[]
  • ArrayList<String>ArrayList<Integer> 等

二、使用 Bundle 打包传递(推荐用于多数据)

当需要传递的数据较多时,使用 Bundle 可以让代码更清晰、更易于管理。

1. 发送方

Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);

// 创建 Bundle 对象
Bundle bundle = new Bundle();
bundle.putInt("user_id", 12345);
bundle.putString("user_name", "张三");
bundle.putBoolean("is_vip", true);
bundle.putDouble("balance", 99.9);

// 将 Bundle 添加到 Intent
intent.putExtras(bundle);

startActivity(intent);

2. 接收方

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_target);

    // 获取 Intent 中的 Bundle
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        int userId = bundle.getInt("user_id", -1);
        String userName = bundle.getString("user_name");
        boolean isVip = bundle.getBoolean("is_vip", false);
        double balance = bundle.getDouble("balance", 0.0);
        // ...
    }
}

优点:结构清晰,便于复用和维护。

三、传递复杂对象:Serializable

如果需要传递自定义的 Java 对象(如 UserProduct),该类必须实现 Serializable 接口。

1. 定义可序列化对象

public class User implements Serializable {
    private static final long serialVersionUID = 1L; // 序列化版本号

    private int id;
    private String name;
    private boolean isVip;
    private double balance;

    // 构造函数、Getter、Setter 省略...
}

2. 传递对象

User user = new User(12345, "张三", true, 99.9);

Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
intent.putExtra("user_object", user); // 直接传递对象
startActivity(intent);

3. 接收对象

User user = (User) getIntent().getSerializableExtra("user_object");
if (user != null) {
    Log.d("User", "Name: " + user.getName() + ", Balance: " + user.getBalance());
}

⚠️ 注意

  • Serializable 是 Java 原生序列化,效率较低,占用内存多
  • 仅适用于小对象或简单场景。

四、传递复杂对象:Parcelable(高性能推荐)

Parcelable 是 Android 专用的序列化接口,性能远优于 Serializable,是传递复杂对象的首选方案

1. 定义可打包对象

public class Product implements Parcelable {
    private int id;
    private String name;
    private double price;
    private List<String> images; // Parcelable 也支持集合

    // 构造函数
    public Product(int id, String name, double price, List<String> images) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.images = images;
    }

    // Parcelable 构造函数
    protected Product(Parcel in) {
        id = in.readInt();
        name = in.readString();
        price = in.readDouble();
        images = in.createStringArrayList();
    }

    // 写入 Parcel
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
        dest.writeDouble(price);
        dest.writeStringList(images);
    }

    // 描述符
    @Override
    public int describeContents() {
        return 0;
    }

    // Creator 静态字段
    public static final Creator<Product> CREATOR = new Creator<Product>() {
        @Override
        public Product createFromParcel(Parcel in) {
            return new Product(in);
        }

        @Override
        public Product[] newArray(int size) {
            return new Product[size];
        }
    };

    // Getter、Setter 省略...
}

💡 技巧:使用 Android Studio 插件(如 Android Parcelable Code Generator)可以自动生成 Parcelable 代码。

2. 传递与接收

// 发送方
Product product = new Product(1, "手机", 2999.0, Arrays.asList("img1.jpg", "img2.jpg"));
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra("product", product);
startActivity(intent);

// 接收方
Product product = getIntent().getParcelableExtra("product");

优点:高效、快速,专为 Android 设计。

五、返回结果:startActivityForResult 已过时!

在旧版 Android 中,使用 startActivityForResult()onActivityResult() 返回数据。但在现代 Android 开发中,这种方式已被废弃!

✅ 推荐方案:Activity Result API(AndroidX)

使用 ActivityResultLauncher 实现更安全、更灵活的结果返回。

1. 在接收方 Activity(ResultActivity)
// 定义返回结果的 Contract
public class PickNameContract extends ActivityResultContract<String, String> {
    @NonNull
    @Override
    public Intent createIntent(@NonNull Context context, String input) {
        Intent intent = new Intent(context, ResultActivity.class);
        intent.putExtra("hint", input);
        return intent;
    }

    @Override
    public String parseResult(int resultCode, @Nullable Intent intent) {
        if (resultCode == Activity.RESULT_OK && intent != null) {
            return intent.getStringExtra("picked_name");
        }
        return null;
    }
}
2. 在发送方 Activity(启动并接收结果)
// 创建 launcher
ActivityResultLauncher<String> launcher = registerForActivityResult(
    new PickNameContract(),
    new ActivityResultCallback<String>() {
        @Override
        public void onActivityResult(String result) {
            if (result != null) {
                // 处理返回的结果
                Log.d("Result", "用户输入的名字: " + result);
            }
        }
    }
);

// 启动 Activity 并等待结果
launcher.launch("请输入您的名字");
3. 在 ResultActivity 中返回结果
// 当用户完成操作后
Intent resultIntent = new Intent();
resultIntent.putExtra("picked_name", "李四");
setResult(Activity.RESULT_OK, resultIntent);
finish(); // 关闭当前 Activity

优势

  • 类型安全。
  • 生命周期感知。
  • 代码更简洁、可读性更强。

六、其他数据共享方式(补充)

方式适用场景
SharedPreferences传递少量、持久化的配置数据(如用户设置)。
数据库 (Room)传递大量结构化数据,或需要持久存储的数据。
ViewModel (配合 Fragment)在同一个界面(Activity)内的多个 Fragment 之间共享数据。

七、总结:Activity 传值选型指南

数据类型推荐方式
基本类型 / StringIntent.putExtra()
多个基本数据Bundle + putExtras()
简单自定义对象Serializable
复杂/频繁传递的对象✅ Parcelable
返回结果✅ ActivityResultLauncher
持久化配置SharedPreferences

八、结语

感谢您的阅读!如果你有任何疑问或想要分享的经验,请在评论区留言交流!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值