lauriys
lauriys

Reputation: 4792

How can I bind two Android Activities to one Service?

I would like to ask for some example, where two different activities (a button in the first activity opens a second activity), are communicating with one service (AIDL, etc.).

I've tried many different tutorials, but they are only about how to make one activity → one service.

Upvotes: 10

Views: 9857

Answers (3)

Kaveesh Kanwal
Kaveesh Kanwal

Reputation: 1763

You can do it by using Messenger that provide IPC communication without using AIDL. This is how you can bind multiple activities to a service.

If you need your service to communicate with remote processes, then you can use a Messenger to provide the interface for your service. This technique allows you to perform inter-process communication (IPC) without the need to use AIDL.

Have a look at this link. When you see the code, you will find a switch case within a Handler. This will cater to the multiple requests that you will send from you multiple activities/components.

Upvotes: 0

D4N14L
D4N14L

Reputation: 440

This is probably old, but I'll try to answer it anyway...

In Android, seeing as only one Activity can bind to a Service at a time, and only one Activity can be shown at a time, there isn't any real reason to want to bind two Activities at a time.

But, if you'd like, the best solution is to bind the Service in the onResume() method, and unbind it in the onPause() method. This allows you to give two unrelated Activities access to the service, while only having one bound at a time.

Upvotes: 14

Rich Schuler
Rich Schuler

Reputation: 41972

Each Activity is responsible for binding and unbinding from the Service. This is normally done in onResume / onPause, or onStart / onStop, depending on your requirements. One Activity cannot bind another Activity to a Service. That's just the way it is. :)

Upvotes: 3

Related Questions