首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >LocalService和LocalBinder在Android 10中泄漏内存

LocalService和LocalBinder在Android 10中泄漏内存
EN

Stack Overflow用户
提问于 2020-09-08 05:39:52
回答 1查看 286关注 0票数 2

我有一个与这里建议的完全相同的LocalService实现,以便通过绑定提供对服务方法的访问。

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

代码语言:javascript
复制
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,这个实现似乎会漏掉内存。当服务未绑定(并被销毁)时,LocalServiceLocalBinder对象不会被垃圾回收。下一个绑定将创建一个新的服务对象。根据内存分析器,LocalBinder对象是在Cleaner中引用的。知道怎么修吗?

EN

回答 1

Stack Overflow用户

发布于 2022-05-28 02:34:07

有点晚了但已经到了。绑定与组件(例如服务)的生命周期无关。绑定器的实例在内部保留,以防其他进程/线程调用绑定程序的transact方法。

在您的代码中,LocalBinder是一个内部类。因此,隐式LocalBinder具有对LocalService的引用。因此,即使LocalService可能已经被销毁,它的引用仍然包含在LocalBinder中,从而泄漏了LocalService

解决方案是使LocalBinder成为一个静态类(或完全独立的类),并为您的LocalService使用一个WeakReference

我知道您的代码直接来自Android文档,但它仍然是错误的。事实上,如果你想去看看,有一份旧的bug报告,Android团队承认了这一点,然后将其标记为“过时(不会修复)”,因为这个团队已经决定转向另一个方向--我不知道这意味着什么,只是他们不会在不久的将来改变它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63787707

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档