Should getSystemService(...) result be cached?

android

Solution

Since holding a system service object has very little ongoing cost, I recommend holding onto it in a data member. Whether you get one in `onCreate()` or lazy-initialize it if/when needed is up to you.

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

Problem

The documentation of `getSystemService` advises to not share the service objects between various different contexts. For a single context, is it preferable to cache the service object by assigning it to a instance field in `onCreate()` or it should be obtained at the time of use? What is the idiomatic usage?

Original source