Android中获取Context的方法们的区别与联系

getActivity():

This method gives the context of the Activity. You can use it is like the yourActivity.this. The method getActivity() is normally used in fragments to get the context of the activity in which they are inserted or inflated.

getContext():

Returns the context the view is currently running in. Usually the currently active Activity. getContext() is not defined in an Activity. It’s used in a View (or View subclass) to get a reference to the enclosing context (an Activity).

Difference between getActivity() and getContext()

Activity is a subclass of Context.

When you call getActivity() you get an Activity which is a Context as well. But when you call getContext() you will get a Context which might not be an Activity.

When using newer version of Support Library, when Fragment is not hosted by an Activity you can get different objects when calling getActivity() and getContext().

getApplication():

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).

getApplicationContext():

Activity.getApplicationContext(): Returns the context for the entire application (the process all the Activities are running inside of). Use this instead of the current Activity context if you need a context tied to the lifecycle of the entire application, not just the current Activity.