Is context.getSystemService()
an expensive call?
I.e. I have build a little http networking library (I know there are other http networking libraries available) that uses ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
to check (before executing a http request) if the user is connected with the internet (kind of fail fast strategy).
My question is should I save the ConnectivityManager
as an instance variable (class field) of my http library or should I call ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
every time before I start an http request to retrieve a "new" ConnectivityManager? Is the same ConnectivityManager instance returned every time I call getSystemService(Context.CONNECTIVITY_SERVICE)
(in other words, can storing a ConnectivityManger into a class field lead to problems since my http library is a long living one --> lives as long as application run)
My question is should I save the ConnectivityManager as an instance variable (class field) of my http library or should I call ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); every time before I start an http request to retrieve a "new" ConnectivityManager?
I would hold onto the instance. While getSystemService()
does not in practice seem to be that expensive to call, why call it more often than needed?
in other words, can storing a ConnectivityManger into a class field lead to problems since my http library is a long living one --> lives as long as application run
To be on the safe side, call getSystemService()
on the Application
singleton (getApplicationContext()
). Usually, the object returned by getSystemService()
knows nothing about the Context
that created it. Occasionally, it does — CameraManager
in Android 5.0 suffered from this flaw, though that was fixed in Android 5.1. If the system service object is going to outlive the context that I am in, I tend to use getApplicationContext()
to retrieve the system service, out of paranoia.
(the memory leaks, they're out to get me!)
Is the same ConnectivityManager instance returned every time I call getSystemService(Context.CONNECTIVITY_SERVICE)
To be honest, I have never looked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With