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:

  1. 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();
    }
  2. Next, we create an instance of IBinder, or rather Binder, which holds a reference to the running service:
    public class ...

Get Xamarin Mobile Development for Android Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.