Reputation: 3969
There are many ways to start another activity. The most of the overloading methods requires you to pass a context.
But when using componentName to launch an activity using
public Intent setComponent (ComponentName component)
and this constructor for ComponentName
ComponentName(String pkg, String cls)
You see above, I am able to launch an activity WITHOUT using any Context argument
But it must use some "context" somehow internally, am I right? If so, which context? Application one or the activity one? Does this mean that every time I use this two methods (above), I do not need to worry about memory leak becuase I am not passing any context around??
Thanks
Upvotes: 5
Views: 10257
Reputation: 48871
adamp's answer is correct (he got to it before I could post).
Just to expand on it this is the source for the Intent(Context packageContext, Class<?> cls)
constructor...
public Intent(Context packageContext, Class<?> cls) {
mComponent = new ComponentName(packageContext, cls);
}
...and this is the source for ComponentName(Context pkg, Class<?> cls)
constructor
public ComponentName(Context pkg, Class<?> cls) {
mPackage = pkg.getPackageName();
mClass = cls.getName();
}
As adamp implies, the Intent
methods that take a Context
are convenience methods that only use it to create the ComponentName
which in turn only deals in String
types (mPackage
and mClass
). Neither the Intent
nor the ComponentName
hold a reference to the Context
.
Upvotes: 5
Reputation: 28932
You don't have to worry about memory leaks in either case, but it's good that you're keeping an eye on where you're passing Context objects. Intent simply uses the Context parameter to look up your package name when you use the Intent(Context, Class)
constructor or setClass(Context, Class)
method. They're just convenience methods.
Upvotes: 5
Reputation: 20936
Maybe I did not understand your question. But you do not use context when you defining intents. You use context to call components using intents. For instance, you use:
context.startActivity(intent)
But usually you call these methods inside your Activities and Services, that extends Context. Thus, you simply use:
startActivity(intent)
Upvotes: 0
Reputation: 39827
startActivity()
does not require a context as a parameter; it's a method within a class which is already derived from (or implements) Context. That is -- you cannot call startActivity()
if you do not have a Context from which to call it.
Upvotes: 0