An Intent
is a passive data structure that carries information from one Activity
to another. An Intent
is also capable of holding data in the form of name-value pairs (via putExtra()
). But while overriding the onCreate()
method we pass a Bundle
as the parameter, which ultimately also holds values in the form of name-value pairs and is able to store information with the help of onSaveInstanceState()
.
In such a scenario why do we need both and what differentiates the two?
I suppose I have led you guys into a misbelief that I have misunderstood what an Intent
is:
When I said "An Intent
is a passive data structure that carries information from one Activity
to another", what I intended to point out was that even an Intent
can carry information (other than the context and action description) with the help of putExtra()
method. Why do we need to use a Bundle
then?
Bundles are used with intent and values are sent and retrieved in the same fashion, as it is done in the case of Intent. It depends on the user what type of values the user wants to pass, but bundles can hold all types of values (int, String, boolean, char) and pass them to the new activity.
An intent is to perform an action on the screen. It is mostly used to start activity, send broadcast receiver,start services and send message between two activities.
An Android App Bundle is a publishing format that includes all your app's compiled code and resources, and defers APK generation and signing to Google Play.
PutExtra() - we can store any primitive data type directly with (key,value) pair. And PutExtras() - hold object of Bundle class object . Bundle class provide us method of specific primitive data type methods to store data in it.
I think you already have understood what a Bundle
is: a collection of key-value pairs.
However, an Intent is much more. It contains information about an operation that should be performed. This new operation is defined by the action it can be used for, and the data it should show/edit/add. The system uses this information for finding a suitable app component (activity/broadcast/service) for the requested action.
Think of the Intent as a Bundle that also contains information on who should receive the contained data, and how it should be presented.
From the source of Intent class, there really is no difference between the two. Check below code from Intent class:
public Intent putExtra(String name, String value) { if (mExtras == null) { mExtras = new Bundle(); } mExtras.putString(name, value); return this; }
And
public Intent putExtras(Bundle extras) { if (mExtras == null) { mExtras = new Bundle(); } mExtras.putAll(extras); return this; }
So I think, only difference is ease of use.. :) for 1st, you don't need to create your bundle explicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With