Im still a bit new to the Android Service Class. I know you need to start the service from your application with startService(intent), however my problem is my service has methods inside it. I need to start the service with an intent and then create an object of that class in my Activity so I can call methods of the service. The problem is when I do this I create one instance of the service when I start it with an intent and another instance of the service when I create an object of the class in my activity. This means any data passed to the service from startService(intent) is not there when I create the object of the service. Any ways around this or am I just totally misusing the service class? I can give some code but its basically this:
//Create Object of ControlPanel service class.
ControlPanel cPanel = new ControlPanel();
//Create intent for starting ControlPanel service class
Intent controlPanel = new Intent(this, cPanel.getClass());
//Start Service
startService(controlPanel);
I'd say you are misusing the class :-).
Calling startService() multiple times does not result in starting multiple service.
From the doc:
Request that a given application service be started. The Intent can either contain the complete class name of a specific service implementation to start, or an abstract definition through the action and other fields of the kind of service to start. If this service is not already running, it will be instantiated and started (creating a process for it if needed); if it is running then it remains running.
You should override onStartCommand() as well. The first startService call starts the service if it has not been started yet. In any case onStartCommand will intercept any further startService calls and the intent you want to send to it.
Any ways around this or am I just totally misusing the service class?
You are totally misusing the Service
class.
A Service
is used via two basic patterns:
Sending commands to it, via startService()
.
Binding to it, to call an API exposed by that Service
, via bindService()
.
Binding more accurately depicts what you are trying to do ("so I can call methods of the service"), however binding is tricky to get right, particularly when it comes to configuration changes.
Hence, I would recommend first that you sit back and determine completely and precisely why you are using a Service
in the first place. ControlPanel
, for example, is a name I would associate with a UI, not UI-less ("background") operations. Then and only then can you determine if the command or the binding pattern is appropriate for your use case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With