0

How do I call an API inside fragment using kotlin-coroutines before exiting the application?

In fact, I want it to be called before leaving the application.

MeNoVa
  • 69
  • 2
  • 7

1 Answers1

0

Android apps are not like regular desktop apps; the Android OS decides when to "close" them by calling onDestroy(). This can happen right after you press the system Back button, or hours later, or never.

A possible option is to use onPause() or onStop(), indicating when the user stops interacting with your fragment. But the user might start interacting with another fragment or activity you may have defined in your app.

Some apps listen to the back button press and ask for confirmation to "exit the app" before doing as much internal cleanup as possible. But it goes against the Android UX guidelines.

ris8_allo_zen0
  • 1,537
  • 1
  • 15
  • 35
  • Thank you for your answer. in fact, I have a video call service in the app, and I'd like before closing the app to cancel the video call by calling API and notifying the server for closing the video call. I dont want to do in onPause and onStop because the user will miss his video call turn – MeNoVa Mar 12 '22 at 11:42
  • 1
    Consider that your activity can go in background at any time, e.g. the user taps on a notification, opens another activity, do something, then goes back to your app. And if the device is low on memory, the OS may decide to `onDestroy()` your activity, then recreate it when the user goes back; they expect to see the call still in progress. Consider handling the video call inside a foreground service that the OS won't kill as likely, and the activity/fragment simply connects to it. – ris8_allo_zen0 Mar 12 '22 at 12:01
  • Ok, Thanks. Out of this discussion, If I want to have an API call just before exit or kill the app, Is such a thing possible? – MeNoVa Mar 12 '22 at 16:44
  • 1
    Not in a guaranteed way: the OS may decide to kill your app without giving it any opportunity to do anything before. In your case (closing a video call), I'd suggest sending heartbeat messages to the server during the call and let the server terminate the call if the app doesn't send them anymore and didn't send an explicit close request. – ris8_allo_zen0 Mar 12 '22 at 17:09