Recently I needed a way of detecting when the app is going to be killed and execute some operations.

Here is a really easy solution by using an IntentService:

class AppKilledDetectingService: IntentService("AppKilledDetectingService") {
    override fun onHandleIntent(intent: Intent?) {}

    override fun onTaskRemoved(rootIntent: Intent?) {
        // Do your operations before the app is killed
    }

Add the service in the manifest:

...
<application ...>
    ...
    <service android:name=".AppKilledDetectingService" android:stopWithTask="true"/>
</application>    

And that is all you need to do! 👻