Communicating with running services
Sometimes, we have a long-running task in a service, but it needs to communicate with our app. This can be needed to send data to the service or to be notified of an event from the service.
How to do it...
To communicate with a service, we need a connection. We use the connection to get a binder, which holds a reference to the service. Let's take a look at the following steps:
Although not entirely necessary for very simple services, we will want an interface that defines the public interface of the service:
public interface IXamarinService { event EventHandler SomeEvent; void SomeInstruction(); }
Next, we create an instance of
IBinder
, or ratherBinder
, which holds a reference to the running service:public class XamarinBinder : Binder { public IXamarinService Service { get; private set; } public XamarinBinder(IXamarinService service) { Service = service; } }
Now that we have the
binder
instance, we can create the actual service implementing the...