Java – Why do intents need context?

Why do intents need context?… here is a solution to the problem.

Why do intents need context?

When it comes to working on different activities and starting them to get results, I have no choice but to use intent. Now that intents need context, it makes no sense to me. I know the context allows access to application resources, but

Why do you need to know about application resources when Intents are just a simple messenger?

Also, I’m not quite sure why some people use getApplicationContext() to create intents while others use it for activity contexts????

Finally, I’m not quite sure when I don’t use “this” for contexts rather than application contexts. I think you have to use “this” or pass in the current activity context that calls startActivityResult() to receive the callback. That’s just simple Java, right? If you pass in a class, the other Activity classes will reference your class, thus allowing it to call a method in your class, which is onActivityForResult(). However, this is not the case, so what am I missing?

Solution

Intents themselves do not require a context. The constructor Intent#Intent(Context, Class) is just a handy constructor that internally derives a ComponentName using the supplied parameters. ComponentName, in turn, is simply the package name of your application and the name of the class to target. So the ComponentName might look like this:

com.foo.bar/com.foo.bar.ui.activity.MyActivity

However, you can also just use the empty constructor Intent#Intent() and provide ComponentName yourself (Intent#setComponentName(ComponentName)).

Therefore, it doesn’t matter whether you provide the context of the application or the context of the activity (the latter is easier to enter). Also keep in mind that classes that require an application context can call Context#getApplicationContext on their own, so you don’t need to worry about that.

About startActivityForResult() – Android manages your activity logging stack internally. Therefore, it passes the result to the previous activity on the stack. When you click Back, it knows where to go back the same way.

Note that this does not mean that it maintains your activity instance stack. These instances may be long gone—destroy and collect garbage to free up memory. However, the stack contains information that allows them to be recreated and their state restored.

Related Problems and Solutions