Search code examples
androidandroid-activityservice

One Service Multiple Activities in Android


I have a service and 3 activities. The service is started in the first activity. Now when I move to the second activity and pressing on some button, I want to send a data to the service.

so in the second activity, inside the click listener I did the following:

 Intent service = new Intent(MyService.class.getName()); 
 service.putExtra("dataToSend",data.toString());
 startService(service);

but the method onStartCommand inside the service, doesn't get called..

Also, I want to create this service to work with multiple activities. I mean each activity will be able to send a data to this service and get a data from it.


Solution

  • QUESTION
    I want to create this service to work with multiple activities. I mean each activity will be able to send a data to this service and get a data from it.

    You don't have to do nothing with your Service. Services remain the same if they are not destroyed, that means all your Activities will be able to access to it's data.

    PROBLEM

    but the method onStartCommand inside the service, doesn't get called..

    WHY
    As long as your service has started, the onStartCommand is not called each time:

    onStartCommand

    Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request.

    startService

    Request that a given application service be started.

    SOLUTION
    call the events you need in onRebind method:

    Called when new clients have connected to the service, after it had previously been notified that all had disconnected in its onUnbind(Intent). This will only be called if the implementation of onUnbind(Intent) was overridden to return true.