首页 > 解决方案 > SyncAdapter 上的静态字段警告

问题描述

我有这个代码SyncService

public class SyncService extends Service {

    private static SyncAdapter syncAdapter = null;
    private static final Object syncAdapterLock = new Object();

    @Override
    public void onCreate() {
        synchronized (syncAdapterLock) {
            if (syncAdapter == null) {
                syncAdapter = new SyncAdapter(getApplicationContext(), true);
            }
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return syncAdapter.getSyncAdapterBinder();
    }
}

我根据此处的 Android 开发人员页面制作的这段代码:https ://developer.android.com/training/sync-adapters/creating-sync-adapter#CreateSyncAdapterService

问题是:在static抱怨SyncAdapter

不要将 Android 上下文类放在静态字段中(对“SyncAdapter”的静态引用,其中的“上下文”字段指向“上下文”);这是内存泄漏(也破坏了即时运行)

但这就是 Android 开发人员页面中的情况。那么,这样做是对还是错呢?如果错了,正确的方法是什么?我找不到有关此特定点的任何信息...

标签: androidandroid-serviceandroid-contextandroid-syncadapter

解决方案


事情是Service延伸Context。您不应该链接到可能导致内存泄漏的静态字段中的上下文(因为即使垃圾收集器将销毁对象静态链接仍然可用,并且仍将保持上下文对象不被销毁)。我认为这里的解决方案是删除static修饰符。这可能是错误添加的。


推荐阅读