Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is context.getSystemService() an expensive call?

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)

like image 459
sockeqwe Avatar asked Sep 05 '15 20:09

sockeqwe


1 Answers

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.

like image 64
CommonsWare Avatar answered Nov 10 '22 03:11

CommonsWare