首页 > 解决方案 > Android 10 中的 LocalService 和 LocalBinder 泄漏内存

问题描述

我有一个LocalService完全按照这里建议的实现,以便通过活页夹提供对服务方法的访问。

https://developer.android.com/guide/components/bound-services#Binder

public class LocalService extends Service {
    // Binder given to clients
    private final IBinder binder = new LocalBinder();

    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }
}

从 Android 10 开始,此实现似乎会泄漏内存。当服务未绑定(和销毁)时,LocalService不会对LocalBinder对象进行垃圾收集。下一个绑定创建一个新的服务对象。根据内存分析器,该对象在 Cleaner 中LocalBinder是引用的。知道如何解决吗?

标签: servicememory-leaksgarbage-collectionandroid-10.0android-binder

解决方案


推荐阅读