Reputation: 4750
I was wondering why the direct instantiation of a service class through a constructor is not recommended. I couldn't find anything related to it. Here is a very basic example:
Service class:
public class SomeRandomClass extends Service {
private final Context mContext;
public SomeRandomClass(Context context) {
this.mContext = context;
}
}
And inside main Activity/Service:
SomeRandomClass class = new SomeRandomClass(this);
class.someMethod();
The post here states that it is not a good idea to instantiate services directly and one should use startService()
instead but why? If I instantiate my service like this I have a variable directly to the service and I can call methods instead of having to bind to it to be able to call methods on my service.
The only advantage I can see by using startService()
is that Android keeps track of my service but the disadvantage that I have to bind to the Service to communicate with it.
On the other hand by calling the constructor directly I have easy communication but if my activity/service get's killed/terminated the "sub" service is killed as well (I'm not using a activity but other service).
Anything else why it is discouraged?
Upvotes: 2
Views: 854
Reputation: 1696
The official documentation describes a Service
as
(...) an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.
As a result a Service
will still run even if your current activity gets killed by the system for resources management priorities.
You could instantiate a service from an activity or from the application context of your app as a singleton if you decide to sub-class Application
, but expect them to be destroyed much more often than an Android Service
would be.
Upvotes: 0
Reputation: 1498
It only makes sense for SomeRandomClass to be a Service at all if you want to use the facilities provided by Services. And in order to get those facilities you need to start the Service properly.
But you don't appear to want to use those facilities (Automatic background life cycle management, possibly in a separate process). What you appear to want is just a plain old class, without extending Service.
Upvotes: 6