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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response