简体   繁体   中英

Why does the doc do not use `this` i.e `Service` for the argument for `Context` in the documentation?

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?

So why is not this passed as Context in the docs?

Because the SyncAdapter instance is being held in a static field:

private static SyncAdapter sSyncAdapter = null;   

A static field 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 the Application object. This is a singleton, set up when your process is forked. As such, it is "pre-leaked" — you cannot leak it further by having a static reference to it.

Since the SyncAdapter instance is being held in a static field, whatever Context we pass to the SyncAdapter constructor may be leaked — whether it will or not is tied to the implementation of SyncAdapter , which may vary by OS version or manufacturer meddling. So, to be safe, the documentation uses the Application singleton for the Context , rather than risk leaking the SyncService instance.

So why is not this passed as Context in the docs?

Because that might leak the SyncService instance by means of the sSyncAdapter field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM