我有一个与这里建议的完全相同的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对象不会被垃圾回收。下一个绑定将创建一个新的服务对象。根据内存分析器,LocalBinder对象是在Cleaner中引用的。知道怎么修吗?
发布于 2022-05-28 02:34:07
有点晚了但已经到了。绑定与组件(例如服务)的生命周期无关。绑定器的实例在内部保留,以防其他进程/线程调用绑定程序的transact方法。
在您的代码中,LocalBinder是一个内部类。因此,隐式LocalBinder具有对LocalService的引用。因此,即使LocalService可能已经被销毁,它的引用仍然包含在LocalBinder中,从而泄漏了LocalService。
解决方案是使LocalBinder成为一个静态类(或完全独立的类),并为您的LocalService使用一个WeakReference。
我知道您的代码直接来自Android文档,但它仍然是错误的。事实上,如果你想去看看,有一份旧的bug报告,Android团队承认了这一点,然后将其标记为“过时(不会修复)”,因为这个团队已经决定转向另一个方向--我不知道这意味着什么,只是他们不会在不久的将来改变它。
https://stackoverflow.com/questions/63787707
复制相似问题