Tuesday, 17 September 2013

Why not directly instantiate services in Android?

Why not directly instantiate services in Android?

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?

No comments:

Post a Comment