3

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.

Sarvan
  • 61
  • 8
  • Get data from service read this http://stackoverflow.com/questions/30648766/binding-a-service-to-multiple-activities – Hemantvc Nov 18 '15 at 04:20
  • Have a look at the [documentation about "Bound Services"](http://developer.android.com/guide/components/bound-services.html). – S.D. Nov 18 '15 at 05:11

3 Answers3

2

Basically, i would suggest that you start the service in application class and send broadcast to service whenever its needed to send any data to service.But make sure the service is running.

Nigam Patro
  • 2,760
  • 1
  • 18
  • 33
0

When you create a Service you should override the onStartCommand() method so if you closely look at the signature below, this is where you receive the intent object which is passed to it:

 public int onStartCommand(Intent intent, int flags, int startId)

So from an activity you will create the intent object to start service and then you place your data inside the intent object for example you want to pass a userID from Activity to Service:

 Intent serviceIntent = new Intent(YourService.class.getName())
 serviceIntent.putExtra("UserID", "123456");
  context.startService(serviceIntent);

When the service is started its onStartCommand() method will be called so in this method you can retrieve the value (UserID) from the intent object for example

public int onStartCommand (Intent intent, int flags, int startId){

    String userID = intent.getStringExtra("UserID");

    return START_STICKY;
}

Note: the above answer specifies to get an Intent with getIntent() method which is not correct in context of a service

Sai Aditya
  • 2,353
  • 1
  • 14
  • 16
0

In this scenario, you should consider using IntentService. IntentService is a special kind, which handles a queue of work, sent through Intents. When the first activity calls startService(), the service is started and begins its work. Consequent calls to startService, will queue them and results in the works being processed one after another, until the last sent intent is done, and then service will shutdown it self. It's pretty straightforward to use and takes care of the heavy lifting and all the boilerplate code you should write. For further study, you can take a look at this .

Farhad
  • 12,178
  • 5
  • 32
  • 60