Why is 'this' passed while creating an instance of Intent?

74 Views Asked by At

I am new to android app development. I am trying to understand what is intent and its uses.

My question is that while starting another activity, why is 'this' keyword passed as the context parameter for the intent?

Intent foo = new Intent(this, viewContacts.class);

I understand that the any activity extends Context class, but why is it that we are passing the activity context and not the application context?

My Point-

When another activity starts the current activity will get destroyed but its context will be passed to the other one. Referring to this article, it says that

The most obvious way of avoiding context related memory leak is to avoid escaping the context outside of its own scope.

So aren't we passing the context of current activity to another one where the first one goes out of scope? Isn't it an example of memory leak?

1

There are 1 best solutions below

3
On BEST ANSWER

why is it that we are passing the activity context and not the application context?

Either would work here. this is less typing and faster to execute than is getApplicationContext().

When another activity starts the current activity will get destroyed but its context will passed to the other one.

You are assuming that the Intent holds onto this Context. It does not.

So aren't we passing the context of current activity to another one where the first one goes out of scope?

No.

An Intent can either be implicit or explicit. An explicit Intent is one that has a ComponentName attached, identifying the specific app (by package name) and Java class (by fully-qualified class name) of the component for which this Intent is intended. The two-parameter constructor, providing the Context and Class object, is used to build that ComponentName. Neither the Intent nor the ComponentName hold onto the Context after the constructor work is completed.