android - 未绑定(bind)并停止的Service的onDestroy未被调用

标签 android service

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

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

如果按“后退”按钮,则 Activity::onDestroy() 的 isFinishing == true,如果按主页按钮,则调用 onDestroy() (我选中了“不保持 Activity Activity ”设置),但 isFinishing = =假。

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

想知道新的生命周期 LifecycleRegistryOwner 是否可以为 Activity 真正被销毁提供一些钩子(Hook)。

以下是 Activity fragment :

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)
    }
}

最佳答案

回答您的最终问题(释义):

Why would isFinishing ever be false in onDestroy?

这是来自 the source code 的相关 fragment :

* 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 破坏的两个不同原因。

关于android - 未绑定(bind)并停止的Service的onDestroy未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46288923/

相关文章:

grails 服务层次结构

testing - 如何在指令链接中监视服务功能?

android - 如何从他的号码中获取联系人的姓名

Android:从特定的 -dpi 文件夹访问可绘制对象?

android - 如何仅从图库中选择视频?

service - 如何处理依赖于服务堆栈中的用户 session 的 Redis MQ 请求

android - 如何每分钟不间断地运行一个 Jobscheduler 或一个 Service?

java - 如何在特定时间后将应用程序发送到后台

android - 如何在 Android 上创建半可拖动的回收 View ?

具有空闲要求的 Android JobScheduler 不会被解雇