Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many types of context in android and what is better to use

I just wanted to know how many ways to get the context, which method used in which situation. Which one better to use, and what is the main and key deference between them.

like image 469
Puja Mishra Avatar asked Jul 17 '13 06:07

Puja Mishra


People also ask

Which context should I use in Android?

Holding a reference to Activity in a long living object or thread can cause a memory leak. In this case, use application context.

How many types of context are there in Android?

There are mainly two types of Context that are available in Android.

What is context in Android and how it is used?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in. The activity object inherits the Context object.

What is the difference between activity context and Applicationcontext?

They are both instances 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.


2 Answers

For Your better understands you should read android official blog. an also look at HackBod Answer.

There are some references URL which help you more about the context

  1. What exactly does using the Application Context mean?
  2. Difference between Activity Context and Application Context
  3. http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html

Thanks

like image 193
Ashish Dwivedi Avatar answered Sep 19 '22 17:09

Ashish Dwivedi


Context class represents the local environment of an App, It encapsulates all the services and resources available to the app. There is a base class ApplicationContext, and sub classes for components: Activity, Service etc.

Always prefer using ApplicationContext because it is global and doesn't cause serious issues if its leaked, that is: an unused reference of it stays and is not garbage collected.

Sometimes you have to use sub components like Activity or Service as context. Use this when creating Intents, or creating UI Elements, or showing a toast etc. That is: functions that are specifically bound to these component's identity, its UI or its display window.

like image 37
S.D. Avatar answered Sep 19 '22 17:09

S.D.