In the Actions section, start the service using startService()
, and bind it to the service. This will save your service in the event of a configuration change.
Disable the service in onDestroy()
your activity. The service will continue to work, as you have launched it not only for this.
Store the static counter variable in your startup activity. Increase it by 1 for another trigger of activity in onCreate()
and decrease it by one in onDestroy()
. So, if 3 actions were open and it is assumed that you are holding the remaining 2 in a stack, the static counter is three. Now in onDestroy()
each counter decrease and check if it is zero, stop the service.
In my FirstActivity ( Launcher ), I have public static int counter = 0;
then in every action:
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FirstActivity.counter++; } @Override protected void onDestroy() { super.onDestroy(); if (--FirstActivity.counter == 0) { stopService(new Intent(this, MyService.class)); } }
source share