What is the usefulness of having Service inherit from Context if it does not use it?
For example from the android docs for sync adapter
we see:
public class SyncService extends Service {
// Storage for an instance of the sync adapter
private static SyncAdapter sSyncAdapter = null;
// etc
sSyncAdapter = new SyncAdapter(getApplicationContext(), true);
So it does not pass this in the constructor for SyncAdapter but getApplicationContext.
So why is not this passed as Context in the docs? What is the point of having Service inherit from Context then?
Because the
SyncAdapterinstance is being held in astaticfield:A
staticfield is an intentional memory leak: whatever you hold in that field cannot be garbage-collected, and the same is true for anything that is referenced by that object.getApplicationContext()returns theApplicationobject. This is a singleton, set up when your process is forked. As such, it is "pre-leaked" — you cannot leak it further by having astaticreference to it.Since the
SyncAdapterinstance is being held in astaticfield, whateverContextwe pass to theSyncAdapterconstructor may be leaked — whether it will or not is tied to the implementation ofSyncAdapter, which may vary by OS version or manufacturer meddling. So, to be safe, the documentation uses theApplicationsingleton for theContext, rather than risk leaking theSyncServiceinstance.Because that might leak the
SyncServiceinstance by means of thesSyncAdapterfield.