TL;DR Android Programming Tips #1 — Context

Ozan Topuz
1 min readDec 8, 2019

Context

It is the context of the current state of the application/object.
getApplicationContext() and getActivityContext() are both instances of Context. So when should you use them and what is the best way to use a context? Let’s clarify them with examples.

getActivityContext() which tied to the lifecycle of an Activity. So you should only use getActivityContext() if you need a context whose lifecycle is attached to the current context.

getApplicationContext() is tied to the lifecycle of an Application. So you should only use getApplicationContext() if you need a context whose lifecycle is separate from the current context.

If you use getActivityContext() here, it will lead to the memory leak and Activity of the context cannot be garbage collected.

For example, if you are using Toast, you can use both of them because a toast can be raised from anywhere within your application and is not attached to a window.

Last but not least, if you are launching a new Activity, you should use getActivityContext() in its Intent so that the new launching activity is connected to the current activity in terms of the Activity stack. However, you should use getApplicationContext(), If you want to set the flag Intent.FLAG_ACTIVITY_NEW_TASK.

--

--