在 Android 中使用 Bundle 而不是直接使用 InentputUltra()的优点

在我的 android 应用程序中,我总是使用 Intent类的直接 putExtra()函数来向新的 Activity传递任意数量的值。
像这样:

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

我知道安卓系统中的 Bundle,我也看到人们使用 Bundle将值传递给新的 Activity
像这样:

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);

我有两个疑问。< br/> 如果我可以通过将值直接传递给 Intent来将值传递给新的 Activity,为什么要使用 Bundle
使用 Bundle代替直接 Intent putExtra()的优点是什么?

40487 次浏览

Bundles are cool because you can isolate their creation/reading more easily, therefore separating the code handling the bundles from the code of the UI.

In most case that's useless as you'll want to transmit the smallest possible amount of data (usually just a couple of strings, an id ...)

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.

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.

[update]

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.

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 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).

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).

you can refer Intent and Bundle Relation (Stackoverflow) and also What is the importance of bundle in an Android program (Stackoverflow).

you can send multiple or bunch of data in one bundle and send it through Intent. or another way is add multiple statements of PutExtra().

And there is not any such important difference as per my knowledge.

Additional advantage: Once data is put in a Bundle, you can send the same data through multiple intents. (Only in the case, multiple intents are to be sent).