Seva Alekseyev
Seva Alekseyev

Reputation: 61378

Starting Android services by intent vs. by instance creation

It's my understanding that Android services are supposed to be singletons - no more than one class instance running at a time. So you're supposed to start them via intents, as opposed to

MyService mse = new MyService();

However, in Google's in-app billing sample, that's exactly what they do in Dungeons.java, line 235. So it's obviously legal.

I'm wondering, if I start a service like this, will the framework later recognize that it's running? In other words, if I try to call startService() on the same service later on, will the framework recognize that an instance of the service already exists and dispatch startService() calls to it?

Upvotes: 2

Views: 156

Answers (2)

David Wasser
David Wasser

Reputation: 95578

I don't know what example you are referring to. But you absolutely positively cannot instantiate an Android component (Activity, BroadcastReceiver, Service, Provider) yourself using the new keyword. These components can only be instantiated by the Android framework, as the framework needs to set up the Context of the component.

There is (unfortunately) nothing stopping you from writing Service s = new MyService();, but it will do you no good. Android will never call any of the lifecycle mathods on this Service and any calls you make to methods of the Service will probably fail spectacularly because the instance has no Context.

Upvotes: 1

chubbsondubs
chubbsondubs

Reputation: 38789

If you instantiate the service directly instead of using intents that guarantees the service will run within your Activities process. If that activity should be killed then down goes the service too. Is that a bad practice? Well it depends on what you wanted. If you need that service to live through potential shutdowns of activities then yes that's a bad thing to do. If you don't care or your app can tolerate those shutdowns then it's ok. However, I'd argue if you need a background job running that can be stopped when your Activity stops then you need to use AsyncTask and NOT a service.

Upvotes: 0

Related Questions