5

I have a question regarding the term 'context' in Android. I see that the context provides information about the environment the application runs in, however what is the difference between Application Context and Activity Context?

AND why do I do things like this:

AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);

Why do I pass the context into the constructor? Can anyone provide please help me understand what a context is, and what the context object is?

I do not want copy/paste from android Reference since I already have read it.....too many times without understanding.

user626912
  • 2,546
  • 3
  • 24
  • 33
  • Here is a good answer to a similar question about [Context](http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context/1027438#1027438) – Adinia Mar 15 '11 at 11:41

3 Answers3

3

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.

If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.

The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.

But in general, use the activity context unless you have a good reason not to.

Umesh K
  • 13,436
  • 25
  • 87
  • 129
1

In simple word ill try to explain. Lets take your example

If you are using AlertDialog Builder how will that AlertDialog will understand where he will get displayed??? (If you are not in that activity)

Here context comes in picture. We pass Activity Context to the AlertDialog.In short AlertDialog will will appear in provided context.

This is what my understanding is correct me if I am wrong.

Harshad
  • 7,904
  • 3
  • 24
  • 42
0

Class Overview

Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.

anddev website said it very clearly .

you must pass it to some other class so they can access global information among other things.

hasanghaforian
  • 13,858
  • 11
  • 76
  • 167
eephyne
  • 911
  • 9
  • 15