TL;DR Android Programming Tips #1 — Context

Context

It is the context of the current state of the application/object.
and 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.

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

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

If you use 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 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 , If you want to set the flag .

Android Developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store