繁体   English   中英

为什么文档不使用 `this` 即 `Service` 作为文档中 `Context` 的参数?

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

如果不使用它,让ServiceContext继承有什么用处?

例如来自同步适配器的 android 文档
我们看:

public class SyncService extends Service {
    // Storage for an instance of the sync adapter
    private static SyncAdapter sSyncAdapter = null;   

    // etc  

    sSyncAdapter = new SyncAdapter(getApplicationContext(), true);

所以它不会在SyncAdapter的构造函数中传递this ,而是在getApplicationContext中传递。
那么为什么this不是在文档中作为Context传递的呢? 那么让ServiceContext继承有什么意义呢?

那么为什么这不是在文档中作为 Context 传递的呢?

因为SyncAdapter实例保存在static字段中:

private static SyncAdapter sSyncAdapter = null;   

static字段是故意的 memory 泄漏:您在该字段中保存的任何内容都不能被垃圾收集,对于该 ZA8CFDE6331BD59EB2AC96F8911C4B6666 引用的任何内容也是如此。

getApplicationContext()返回Application object。 这是一个 singleton,在您的进程分叉时设置。 因此,它是“预先泄露的”——你不能通过对它的static引用来进一步泄露它。

由于SyncAdapter实例保存在static字段中,因此我们传递给SyncAdapter构造函数的任何Context都可能泄漏——无论它是否与SyncAdapter的实现相关,这可能因操作系统版本或制造商干预而异。 因此,为了安全起见,文档使用Application singleton 作为Context ,而不是冒险泄漏SyncService实例。

那么为什么这不是在文档中作为 Context 传递的呢?

因为这可能会通过sSyncAdapter字段泄漏SyncService实例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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