The Intent constructors parameters

2019-04-20 22:58发布

问题:

The Intent class had 6 constructors

Intent()

Create an empty intent.


Intent(Intent o)

Copy constructor.


Intent(String action)

Create an intent with a given action.


Intent(String action, Uri uri)

Create an intent with a given action and for a given data url.


Intent(Context packageContext, Class cls)

Create an intent for a specific component.


Intent(String action, Uri uri, Context packageContext, Class cls)

Create an intent for a specific component with a specified action and data.

I'm almost new in android programming and mostly using the fifth one when i need to start another Activity or Fragment:

Intent(Context packageContext, Class<?> cls)

When i want to start an Activity from a Fragment i do this:

Intent i = new Intent(getActivity(), DestinationActivity.class);

as far as i know, getActivity() will return an Activity

But the constructor expect a Context, how is this possible???

is it possible because of that the Activity that had returned by getActivity() implicitly invoke getApplicationContext()???

回答1:

Take a look at the argument Context very closely in the fifth Intent declaration. It reflects polymorphism. The Intent takes a Context argument so you can pass any object that is a Context or derives from the Context class.

Activity, AppCompatActivity, IntentService, Service all derive from the Context class and hence can be passed as an argument to the method.



回答2:

Activity inherits context. Thus, if you are in an activity, you only need to pass itself to use the context. It also contains a pointer to getBaseContext(). You might occasionally need to reference that, if you need the entire application context, but most likely you won't for a while.

You can find more details about the Activity class here.

This question about the intent constructor parameters is similar to yours and has a really good answer. I think you'd like to check it out.

Hope it helps.



回答3:

Activity extends Context so you can just cast it:

Intent i = new Intent((Context)getActivity(), DestinationActivity.class);