1

I'm building a android library with some functionality, which will be used by 3rd party apps. Within my library I need to access network related stuff, and need to access Context.getSystemService() to get ConnectivityManager. For e.g. -

ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));

The problem is that I do not have an activity class, to get context from. So 2 questions -

  1. Is there a way to get the context of the Activity from which my library method was called?
  2. Is it is a good practice to ask the app(calling my library) to pass the app's activity context down to a 3rd party library?

Thanks!

snakepitbean
  • 217
  • 4
  • 13
  • Pass `context` in constructer or method parameter – Kishore Jethava Apr 26 '17 at 03:09
  • It doesn't necessarily have to be an activity. You can pass in application context as well. SO may be in your library initialization, if you use the application context, then take advantage of that – ifiok Apr 26 '17 at 03:22
  • difyzz - does it still need to be passed by the calling app? Or can I get it within my class itself? – snakepitbean Apr 26 '17 at 03:59
  • You want to add some Java class let say `Helper` class and you have to setup this `Connectivity Manager` functionality there. So you can reuse it whenever you want. – Satan Pandeya Apr 26 '17 at 04:03

1 Answers1

1

Ideally, you should never pass a context to retrieve a resource. You should pass the resource itself (in this case, the ConnectivityManager). If that's impractical (because you need several resources, or you need to reload them from time to time), or the resource itself is tied to the Context's lifecycle, and the application context is useless, then you should pass the context, but also should make possible to erase the reference if needed, so you can avoid leaks and crashes. For example, add a setContext(Context context) method, and set the context to null when leaving the activity. Is not exactly pretty, but given the fact you don't control the actions of the user, it's the safest bet. A similar option would be to delete the library object reference, but that would not stop any operations your library could be doing with the context until the next sweep of the GC. Remember, even if your library operates in the main thread, your app can be sent to background anytime.

Fco P.
  • 2,486
  • 17
  • 20