The name of the component to use Android to start activity

There are many ways to start another action. Most overload methods need to convey context.

But when using the component name to trigger an action using

public Intent setComponent (ComponentName component) 

and this constructor for ComponentName

 ComponentName(String pkg, String cls) 

You see above, I can trigger an action WITHOUT using any context argument

But he must somehow use some kind of "context", right? If so, what context? One or one of the applications? Does this mean that every time I use these two methods (see above), I do not need to worry about a memory leak, because I do not pass any context around?

thanks

+4
source share
4 answers

You do not need to worry about memory leaks anyway, but it’s good that you keep track of where you are passing the context objects. Intent simply uses the Context parameter to find the name of your package when you use the constructor Intent(Context, Class) or setClass(Context, Class) . These are just convenient methods.

+4
source

Adamp's answer is correct (it got to it before I could post).

Just for extension on it, this is the source of the Intent(Context packageContext, Class<?> cls) constructor Intent(Context packageContext, Class<?> cls) ...

 public Intent(Context packageContext, Class<?> cls) { mComponent = new ComponentName(packageContext, cls); } 

... and this is the source of the ComponentName(Context pkg, Class<?> cls) constructor ComponentName(Context pkg, Class<?> cls)

 public ComponentName(Context pkg, Class<?> cls) { mPackage = pkg.getPackageName(); mClass = cls.getName(); } 

As adamp implies, Intent methods that accept Context are convenient methods that use it only to create a ComponentName , which in turn only deals with String types ( mPackage and mClass ). Neither Intent nor ComponentName contain a reference to Context .

+5
source

startActivity() does not require context as a parameter; it is a method inside a class that is already derived from (or implements) Context. That is, you cannot call startActivity() unless you have a Context from which to call it.

0
source

Perhaps I did not understand your question. But you do not use context when determining intentions. You use context to invoke components using intentions. For example, you use:

 context.startActivity(intent) 

But usually you call these methods in your actions and services that expand the context. So you just use:

 startActivity(intent) 
0
source

Source: https://habr.com/ru/post/1397474/


All Articles