0

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.

Raeglan
  • 514
  • 1
  • 5
  • 17
  • use flag to identify backpress event. on orientation change you will get onConfigurationChanged system call. while swiping app from recent screen or application(process) killed in background, Your apps service onDestroyed will get called. – Keyur Thumar Feb 13 '17 at 10:18

1 Answers1

1

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

See more here Acrivity.onDestroy

MaxV
  • 2,601
  • 3
  • 18
  • 25
  • P.S. It's not a good idea to stop service in onDestroy because it's not necessary to onDestroy calling while activity destroying – MaxV Feb 13 '17 at 10:18
  • Thanks I overlooked that while reading the documentation. Also, what do you mean with your P.S.? Is the `onDestroy()` not always called when finishing an activity? And I will probably write the `isFinishing()` on the `onPause` to check if finish was called. – Raeglan Feb 13 '17 at 10:24
  • [link](https://developer.android.com/reference/android/app/Activity.html#onDestroy()) There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away. The good place to stop service is onStop() method and restart service in onStart() method in relation with isFinishing() value – MaxV Feb 13 '17 at 10:26
  • 1
    @link that is why I wanted to check if the destroy method was being called because of an user action or if the system did it. So that I will only kill the background service if the user explicitly killed my app. For example how Google Maps closes the Navigation running in background if you swipe the app of the recent apps list in android. – Raeglan Feb 13 '17 at 10:31