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);
You can do this with one service class.
Simply make the methods you need to access static.
I'd say you are misusing the class :-).
Calling startService() multiple times does not result in starting multiple service.
From the doc:
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.
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
, viabindService()
.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.