【问题标题】:Unbound and stopped Service's onDestroy is not called未绑定和停止服务的 onDestroy 未被调用
【发布时间】:2017-09-18 22:14:37
【问题描述】:

在其 onStart() 中的 Activity 绑定到 MusicPlayService,并在其 onStop() 中取消绑定 MusicPlayService。在其 onDestroy() 中,它调用了 stopService,但 MusicPlayService 的 onDestroy() 根本没有被调用

****** 更新:onDestroy() 中的 isFinishing 为 false。

如果按下返回按钮,则 activity::onDestroy() 具有 isFinishing == true,如果按下主页按钮,则调用 onDestroy()(我已选中“不保持活动活动”设置)但 isFinishing = =假。

我猜这是正确的行为,只有活动的 finish() 才会开始设置 isFinishing == true。即使主页按钮会触发 onDestroy(),操作系统仍可能认为这不是真正的“完成”。

想知道新的 arch-lifecycle LifecycleRegistryOwner 是否可以提供一些钩子,让 Activity 真正被销毁。

这里是活动的sn-p:

override fun onStart() {
    super.onStart()
    if (!isBound) {
        val bindIntent = Intent(this, MusicPlayService::class.java)
        isBound = bindService(bindIntent, myConnection,
                Context.BIND_AUTO_CREATE)
    }
}

override fun onStop() {
    super.onStop()
    unbindService(myConnection)
    isBound = false
}


override fun onDestroy() {
    super.onDestroy()
    if (isFinishing) {
        val intentStopService = Intent(this, MusicPlayService::class.java)
        stopService(intentStopService)
    }
}

【问题讨论】:

  • 发现是检查isFinishing导致问题,但是为什么onDestroy时isFinishing还是false?

标签: android service


【解决方案1】:

回答你最终的问题(转述):

为什么在 onDestroy 中 isFinishing 永远是假的?

这是来自the source code的相关sn-p:

* The final call you receive before your
* activity is destroyed.  This can happen either because the
* activity is finishing (someone called {@link Activity#finish} on
* it, or because the system is temporarily destroying this
* instance of the activity to save space.  You can distinguish
* between these two scenarios with the {@link
* Activity#isFinishing} method.

所以isFinishing 标志是区分Activity 破坏的两个不同原因的帮助工具。

【讨论】:

    【解决方案2】:

    条件

    if (isFinishing) {
        val intentStopService = Intent(this, 
    MusicPlayService::class.java)
        stopService(intentStopService)
     }
    

    你在 onDestroy() 中检查的总是在 onDestroy 中返回 false。 isFinishing 通常用在 onPause() 中并在那里返回 true。因为 onDestroy 在活动已经完成并且 isFinished 返回 false 之后被调用。因此,您的实现的服务销毁代码不会被执行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多