Android: How to start the service when the application is visible?

I want the service to start in the background when one of several actions in my application is visible.

I am currently bound to it in a subclass of Application , for example:

 public class App extends Application { @Override public void onCreate() { super.onCreate(); bindService(new Intent(this, MyService.class), mServiceConnection, BIND_AUTO_CREATE); } } 

However, there is no corresponding onDestroy method where you can disable the service. When, at the end of the last action, the service continues to work indefinitely.

  • Is this normal as it is? Should I just let the OS shut down the service with low memory?
  • Alternatively, is there a way to do this based on activity?
+4
source share
1 answer

This can be done very easily. Bind the service to the main tasks. As long as the asset is active, Android will support the service.

When all actions are disabled, the service will automatically die. (services called by onbind will automatically die when all bind operations disappear). Only when you use onCreate to create a service should you worry about ondestroy.

0
source

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


All Articles