简体   繁体   English

Android - 用户关闭应用程序或操作系统关闭应用程序时的活动/片段生命周期事件

[英]Android - Activity/fragment lifecycle event when user closes app or OS closes app

I'm trying to call a function when user closes app manually (force close/manually closing through recent apps etc.) or when the OS closes the app to free up memory.当用户手动关闭应用程序(通过最近的应用程序强制关闭/手动关闭等)或操作系统关闭应用程序以释放 memory 时,我正在尝试调用 function。 I'm doing database calls in my function.我正在我的 function 中进行数据库调用。

My app architecture is based on fragments for each screen (one MainActivity with FragmentContainerView), navigation is using JetPack navigation.我的应用架构基于每个屏幕的片段(一个带有 FragmentContainerView 的 MainActivity),导航使用 JetPack 导航。

I have tried calling my function in onDestroy(), onDestroyView(), onDetach() - none of them are called when manually closing the app.我曾尝试在onDestroy()、onDestroyView()、onDetach()中调用我的 function - 手动关闭应用程序时不会调用它们。 onStop() fires prematurely (when fragment isn't in view anymore), but I need it when the app closes. onStop() 过早触发(当片段不再在视图中时),但是当应用程序关闭时我需要它。

I'm using kotlin .我正在使用kotlin

How do go about doing this? go 如何做到这一点?

override fun onDestroy() {
        CoroutineScope(Dispatchers.IO).launch{

            //Database calls

        }
        super.onDestroy()
    }

If you want to make call when your app is closed or killed so your should use Service or WorkManager.如果您想在您的应用程序关闭或终止时拨打电话,那么您应该使用 Service 或 WorkManager。 They can do api call when your app is killded or closed.当您的应用程序被杀死或关闭时,他们可以进行 api 调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM