简体   繁体   中英

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. I'm doing database calls in my function.

My app architecture is based on fragments for each screen (one MainActivity with FragmentContainerView), navigation is using JetPack navigation.

I have tried calling my function in onDestroy(), onDestroyView(), onDetach() - none of them are called when manually closing the app. onStop() fires prematurely (when fragment isn't in view anymore), but I need it when the app closes.

I'm using kotlin .

How do go about doing this?

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. They can do api call when your app is killded or closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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