Should getSystemService (...) result be cached?

The getSystemService documentation recommends that you do not exchange service objects between various different contexts .

For one context, is it preferable to cache the service object by assigning it to the instance field in onCreate() or should it be obtained during use? What is idiomatic use?

+7
source share
2 answers

Since holding a system service object has a very low current cost, I recommend holding it in a data item. Whether you get it in onCreate() or lazily initialize it if / when needed is up to you.

Note that using a system service object can have significant costs. Holding an instance of LocationManager cheap; using GPS (e.g. via requestLocationUpdates() ) is not cheap.

+5
source

I was going to ask the same thing. This is how I do it - inside a service (which inherits from context)

 private static volatile LocationManager lm; // not final - we need a context private LocationManager lm() { LocationManager result = lm; if (result == null) { synchronized (LocationMonitor.class) { // my service result = lm; if (result == null) result = lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); } } return result; } 
0
source

All Articles