Android: 无法将多个值放入 Intent/Bundle

Android: Unable to put multiple values into Intent/Bundle

我一直在尝试使用 Intent 在两个 Activity 之间传递多个值(不同类型)。到目前为止,我已经尝试了这两种方法:

Intent intent = new Intent(context, Receiver.class);
Bundle bundle = new Bundle();
bundle.putInt("key1", v1);
bundle.putString("key2", v2);
bundle.putString("key3", v3);
bundle.putInt("key4", v4);
intent.putExtras(bundle);

和:

Intent intent = new Intent(context, Receiver.class);
intent.putInt("key1", v1);
intent.putString("key2", v2);
intent.putString("key3", v3);
intent.putInt("key4", v4);

然而,在这两种情况下似乎只保留了 key1 的值(当使用 Bundle 时,它​​显然只包含 1 个键)。我错过了什么?

编辑: 这就是我在 Receiver:

中检索值的方式
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_video);

    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    v1 = bundle.getInt("key1", DEFAULT1);
    v2 = bundle.getString("key2", "DEFAULT2");
    v3 = bundle.getString("key3", "DEFAULT3");
    v4 = bundle.getInt("key4", DEFAULT4);

    // ...
}

或者:

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

    Intent intent = getIntent();
    v1 = intent.getIntExtra("key1", DEFAULT1);
    v2 = intent.getStringExtra("key2");
    v3 = intent.getStringExtra("key3");
    v4 = intent.getIntExtra("key4", DEFAULT2);

    // ...
}

当我打印出 v1v2v3v4 的值时,v1 是唯一带有 non-null/non-default 值(我最初输入 key1 的值 - 实际上,我最初输入 Intent 的所有值都是非默认值)。

编辑 2:

我试过像这样使用 getBundleExtra()

intent.putExtra("bundle", bundle);

然后在Receiver

Bundle bundle = intent.getBundleExtra("bundle");

然而,bundle 为空。

编辑 3:

更改 Intent 中值的放置顺序 in/retrieved 似乎没有任何影响。也没有指定 Bundle 的容量。如果有帮助,请在 PendingIntent 中使用此 Intent。

您可以在不使用 Bundle 的情况下简单地传递和接收 Intent Extras。

SenderClass.java

Intent intent = new Intent(getApplicationContext(), Receiver.class);
intent.putExtra("key1", key1);
intent.putExtra("key2", key2);
intent.putExtra("key3", key3);
startActivity(intent)

Receiver.java

String key1 = getIntent().getStringExtra("key1");
String key2 = getIntent().getStringExtra("key");
String key3 = getIntent().getStringExtra("key3");

原来我忽略了一些非常简单的事情——我的 Intent 在 PendingIntent 中用于触发接收器然后启动服务,但我忘记将 Bundle 从原始 Intent 正确转移到(新的,不同的)Intent最终由第二个 Activity 接收(由服务启动)。问题现已解决。