Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should getSystemService(...) result be cached?

Tags:

android

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?

like image 752
Miserable Variable Avatar asked May 15 '12 18:05

Miserable Variable


1 Answers

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.

like image 170
CommonsWare Avatar answered Sep 19 '22 18:09

CommonsWare