Stop the service if none of the actions is in the foreground

I have a service that is used by all my actions and should be stopped when none of the actions is in the foreground, but continues to work all the time when one action is visible. Since Android does not preserve its internal state in order to find out which application is in the foreground, is there any clean way to achieve this?

+4
source share
2 answers

I think @biquillo misunderstood your question, but I found a good idea in CommonsWare's answer ..

Basically, you can start a service by simply binding it and setting a flag to create it, if it has not already been created. Then, whenever an activity is created, it is attached to the service, onDestroy it disappears. This will destroy the service once when no activity is tied to it.

Hope this helps and he solved ur problem;) Greetings

+1
source

See the Activity Lifecycle listed at http://developer.android.com/reference/android/app/Activity.html

Understand when the onStart, onStop, and onPause methods are called. Then you can start the service / stopService from the inside.

0
source

Source: https://habr.com/ru/post/1343011/


All Articles