98

What is the difference between:

  1. getApplicationContext()
  2. getBasecontext()
  3. getApplication()
  4. getParent()

Can you elaborate with one simple example?

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
Nikunj Patel
  • 21,853
  • 23
  • 89
  • 133
  • 1
    please go through http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context that define same thing also http://developer.android.com/reference/android/content/Context.html – Balban Jul 28 '11 at 05:01

2 Answers2

111

getApplicationContext() Application context is associated with the Applicaition and will always be the same throughout the life cycle.

getBasecontext() should not be used, just use Context instead of it which is associated with the activity and could possible be destroyed when the activity is destroyed.

getApplication() is available to Activity and Services only. Although in current Android Activity and Service implementations, getApplication() and getApplicationContext() return the same object, there is no guarantee that this will always be the case (for example, in a specific vendor implementation). So if you want the Application class you registered in the Manifest, you should never call getApplicationContext() and cast it to your application, because it may not be the application instance (which you obviously experienced with the test framework).

getParent() returns object of the activity if the current view is a child..In other words returns the activity object hosting the child view when called within the child.

Paul Verest
  • 60,022
  • 51
  • 208
  • 332
Ravi
  • 4,872
  • 8
  • 35
  • 46
  • 16
    As you have mentioned we should't use getBaseContext(), if it is not so much important, then why it is in coding and what is its main advantages. please elaborate me about it – Pir Fahim Shah Jun 09 '14 at 04:46
  • getBaseContext() should be used in very specific situations. There is a very good explanation here - https://medium.com/@ali.muzaffar/which-context-should-i-use-in-android-e3133d00772c – lomza Feb 13 '17 at 23:00
37

getApplicationContext() Application context is associated with the Application and will always be the same throughout the life cycle.

getBasecontext() should not be used, just use Context instead of it which is associated with the activity and can be destroyed when the activity is destroyed.

Harinder
  • 11,776
  • 16
  • 70
  • 126