在Android中使用捆绑,而不是直接故意putExtra()的优点而不是、优点、直接、Android

2023-09-12 04:21:09 作者:嘻哈男孩

在我的Andr​​oid应用程序,我总是用意图类的直接 putExtra()函数来传递任何数量有价值的新的活动。 像这样的:

In my android application I'm always using direct putExtra() function of Intent class to pass any number of value to new Activity. Like this:

Intent i = new Intent(this, MyActivity.class);
i.putExtra(ID_EXTRA1, "1");
i.putExtra(ID_EXTRA2, "111");
startActivity(i);

我知道捆绑在Android和我所看到的人都在用捆绑传递值,新的活动。 像这样的:

I know about Bundle in Android and I have seen people are using Bundle for passing values to new Activity. Like this:

Intent intent = new Intent(this, MyActivity.class);
Bundle extras = new Bundle();
extras.putString("EXTRA_USERNAME","my_username");
extras.putString("EXTRA_PASSWORD","my_password");
intent.putExtras(extras);
startActivity(intent);

在这里,我有2个疑问。为什么要使用捆绑如果我能值传递给新的活动通过把它直接意图? 什么是使用了捆绑,而不是直接意图 putExtra()?

Here I have 2 doubts.Why should I use Bundle if I can pass values to new Activity by putting it directly to Intent? What are the advantages of using Bundle instead of direct Intent putExtra()?

推荐答案

这让小(如果有区别)。使用附加捆绑的code是稍重(它不会做任何实际应用中任何区别),并稍微更易于管理,更加普遍。

It makes little (if any difference). The code using an additional bundle is slightly heavier (it won't make any difference in any practical application) and slightly easier to manage, being more general.

如果有一天你决定 - 要数据以数据库的序列化 - - 发送意图的内部信息之前,这将是一个有点清洁有一个包,你可以序列化,增加意图再喂到PendingBundle - 全部用一个对象

If one day you decide that - before sending information inside an intent - you want to serialize the data to database - it will be a bit cleaner to have a bundle that you can serialize, add to an intent and then feed to a PendingBundle - all with one object.

[更新]

一个澄清(因为一些其他的答案)。

A clarification (because of some other answers).

额外的是一个额外的包,每个意图可能进行(但不一定),所以用包或不使用它的无可奈何。您使用的是捆绑两种方式。

Extras is an additional bundle that each Intent might carry (but doesn't have to), so there is no alternative between using a bundle or not using it. You are using a bundle either way.

第一次使用 putExtra ,一个 mExtras 包内意图被初始化,以下所有putExtra委派给它。该包本身无法访问到你(这是由设计,以避免某些类型的错误)。

The first time you use putExtra, a mExtras bundle inside Intent is initialized and all the following putExtra are delegated to it. The bundle itself is inaccessible to you (this is by design, to avoid certain kind of bugs).

putExtras 不把你的包里面的意向。相反,它会将其移交给目前的意图包(或创建一个,如 putExtra )。这就是为什么它稍重(你有两个包,而不是一个,并支付复印的价格)。

putExtras does not put your bundle inside Intent. Instead, it copies it over to the current intent bundle (or creates one, as with putExtra). This is why it's slightly heavier (you have two bundles instead of one and pay the price of copying).

关键是 - 如果你使用 putExtras ,你仍然无法访问的意图内真正的捆绑。但是 - 你有任何其他你可能想用它做一个副本。像保持周围复制到另一个意图(如果你发送大量类似的意图的)。

The crux is - if you use putExtras, you still cannot access the real bundle inside the intent. BUT - you have a copy for whatever else you might want to do with it. Like keep around to copy into another intent (if you send a lot of similar intents).