【问题标题】:Android Context leak for lateinit service binding用于 Lateinit 服务绑定的 Android 上下文泄漏
【发布时间】:2021-07-17 00:28:00
【问题描述】:

所以我创建了一个服务,按照这个:https://developer.android.com/guide/components/bound-services

我在视图模型中绑定服务。

现在 linter 给了我以下警告:

错误:此字段 泄漏上下文对象 [StaticFieldLeak] lateinit var positionManager: PositionManager

如何解决?


   var mBound = false
   lateinit var positionManager: PositionManager

   private val connection = object : ServiceConnection {
       override fun onServiceConnected(className: ComponentName, service: IBinder) {
           val binder = service as PositionManager.LocalBinder
           if (!mBound) {
               positionManager = binder.getService()
               mBound = true
           }
       }

       override fun onServiceDisconnected(arg0: ComponentName) {
           mBound = false
       }
   }

   public fun startServices(context: Context?) {
       Intent(context, PositionManager::class.java).also { intent ->
           context?.bindService(intent, connection, Context.BIND_AUTO_CREATE)
       }
   }

   public fun stopService(context: Context?){
       if(mBound){
           context?.unbindService(connection)
       }
   }

【问题讨论】:

    标签: android kotlin service viewmodel


    【解决方案1】:

    改用可空字段并在stopService 方法中将其设置为空。

    【讨论】:

    • 这并不能解决问题。 Error: This field leaks a context object [StaticFieldLeak] var positionManager: PositionManager? = null
    【解决方案2】:

    解决方案是将服务置于弱引用中:

    lateinit var positionManager: WeakReference<PositionManager>
    

    问题在于视图模型持有对服务的引用。如果要销毁视图模型,则对服务的引用可能会阻止 GC 释放其内存 - 导致泄漏。有关详细信息,请参阅此帖子:

    https://medium.com/@zhangqichuan/memory-leak-in-android-4a6a7e8d7780

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-16
      • 1970-01-01
      • 2014-08-27
      相关资源
      最近更新 更多