Context/Application Context?

Context/Application Context?

Context is the bridge between components. You use it to communicate between components, instantiate components, and access components.

When to use what? Be smart enough to know what to use when because you won't feel the changes by using one of them but if you go to DDMS you can find something is leaking memory later on which will lead to the poor performance of your application.

Context to get information about activity and application. It provides access to system information like resources drawable strings database etc. Both are an instance of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.

Application Context

The app context is a singleton by default, This is associated with the lifecycle of your application.

It notes that you should only use this if you need a context whose lifecycle is separate from the current context that means if you move from activity one to another but still you want to use some instance of a particular class so you can use application context, for example, you make retrofit singleton class, database helper class, services which are not bound to a particular activity, broadcast receiver and any third party lib initialization.

(Activity) Context

This is the context of the current activity this exists till the activity is available, Its lifecycle is limited so we need to use it only for its scop-related work like Showing the toast, Progress bar, Snackbar, Launching the activity, Activity helper classes, Registering some listeners only for activity.

CONCLUSION KEYNOTES:

You can use both places with no difference but need to understand the memory leak issue if you want to make robust and memory-efficient apps so use context properly.

Holding context for a long time will lead to a memory leak.

Activity Should be available for garbage collection so don't use activity context beyond its scope.

If you have to create a singleton object for your application and that object needs a context, always pass the application context.

Do not use getApplicationContext() with LayoutInflater, unless you really do want to ignore your theme.

Context is an abstract class (that means you can’t instantiate it directly ).

They (Application Context, Activity, Service) are all subclasses of ContextWrapper class.

ContextWrapper is just an Adapter class for Context — not actual implementation.

Activity and Services themselves are subclasses of Context, Activity and Services get their own instance of the Context object.

Pankaj K.

Android Expert | Mentor | Published Author

2 年

Curious to know usecases of 4th to last action from content providers

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了