When using methods on context, I always get a confusion which one to use and when, namely, getActivity() or getApplicationContext() . Please help me solve this. Thanks in advance.
Asked
Active
Viewed 1,858 times
-2
-
Why is this down-voted so much? Seems like a legit question to me. (Also repeated here: http://stackoverflow.com/questions/5018545/getapplication-vs-getapplicationcontext) with much better results. Maybe the question has been edited... – SMBiggs Mar 07 '16 at 16:41
-
Possible duplicate of [Difference btn mContext.get().getApplicationContext() and getActivity()](http://stackoverflow.com/questions/33447762/difference-btn-mcontext-get-getapplicationcontext-and-getactivity) – Nahid Bandi Jun 06 '16 at 10:57
1 Answers
5
getSystemService()
is a method on Context
. Fragment
does not inherit from Context
. Activity
does. You can call getActivity()
on your Fragment
to obtain an Activity
on which to call getSystemService()
.

CommonsWare
- 986,068
- 189
- 2,389
- 2,491
-
2@NagabhushanBaddi: Use `Context.CONNECTIVITY_SERVICE` because `CONNECTIVITY_SERVICE` is static constant in Context class so you need to use class name to access it – ρяσѕρєя K Feb 07 '15 at 18:17
-
1@NagabhushanBaddi: "I tried even getActivity().getSystemService()" -- you can see `getSystemService()` in [the JavaDocs for `Activity`](http://developer.android.com/reference/android/app/Activity.html#getSystemService(java.lang.String)). – CommonsWare Feb 07 '15 at 18:19