0

I send data between my activity and my service through an intent ( i call startForegroundService multiple times because this call onStartCommand again and with getIntent i fetch my data).

Example:

Intent intent = new Intent(getActivity(), MediaPlayerService.class);
intent.putParcelableArrayListExtra("songList", Main.musicList);
intent.putExtra("songIndex", position);
intent.setAction(Constants.ACTIONS.ACTION_PLAY);
ContextCompat.startForegroundService(getActivity(), intent);

I read somewhere it's better to communicate with my service through binding.

But i'm achieving the same thing with this method, so which one is preferable?

Vince VD
  • 1,506
  • 17
  • 38
  • its not black and white to say its "better" to use service bindings. Its has some particular usecases. I would recommend reading the docs about service communication - they are pretty extensive. – JoxTraex Jul 01 '19 at 01:38
  • @JoxTraex But if i only want to send data between my activities and my service, is my method right? – Vince VD Jul 01 '19 at 01:39
  • Yes, as @pskink said, binding service is the way to go if you want to communicate between your service and activity – Bach Vu Jul 01 '19 at 04:05
  • @pskink Only data i want to send to my service is an Arraylist and a position in my arraylist so should i still opt for binding my service? – Vince VD Jul 02 '19 at 03:10

1 Answers1

0

From the docs :

Started

A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.

Bound

A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

You can read more about this @ : Android Services, Bound Services

Rohit J
  • 107
  • 7