How can I share a service between activities without restarting?

I am writing a SIP application using the SDK. There are many actions in my application, so I initialize and complete the SDK using the onCreate and onDestroy methods so that I can run it for the duration of my application (and not just for a separate Activity).

An example application that I work with from startService calls and then just a service leak - I don't want to do this, but I'm not sure if I have an alternative.

What I would like to do is bind to the service using Context.BIND_AUTO_CREATE in my Activity OnCreate base class class and disable it in OnDestroy. All my actions extend from this, so I could use the Service in all my actions.

But what happens when you reconfigure or switch actions? Does aggression serve aggressively killed in a short period of time between actions or is there a guarantee that this will not happen? If this is the first, does it not affect the use of services? What design pattern should I use to keep something alive throughout the life of my application?

+6
source share
2 answers

I realized that I was asking the wrong question. I assume that the application will be destroyed when the user finishes with it, which probably will not be, he just sits in the background, and my service will also be. I think I need a redesign.

In addition, if I really wanted to continue this path (which I am not doing now), I could bind the service to my application, then it would exist for the whole life of the application (which, as I recall, would be undefined if the user does not kill it , or Android will not restore it). In this case, I do not need to specifically call unbind, since the binding will be destroyed along with the application.

+3
source

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)); } } 
+2
source

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


All Articles