Search code examples
androidandroid-activityactivity-lifecycleandroid-ondestroy

How to know if a user triggered onDestroy in an Activity and not the system?


I am writing a service which stays open in background and records user action.

Now, if a user finish the App Activity by pressing the back key or swiping the app away in the recent apps screen I want to finish the background service as well, but if Android calls onDestroy, because of an orientation change or some other reason the service should still run in background.

For that I need to know the difference in code of when the user closed the activity or if it was android.

For the back button this is an easy fix, just overwrite the onBackpressed and everything is fine, this will not be called, however, if the user swipes the app off the recent apps screen.


Solution

  • You can check this.isFinishing() for your activity when onDestroy is called.

    See more here Acrivity.onDestroy