Xamarin Android - Service

January 11, 2018 Oclemy Xamarin Service 1 minute, 23 seconds

A service is an android component used to implement long running operations.

When to use Services

You should use a service when you want to implement long running background operations.

For instance if you want to synchronize data in the background, a Service would be a perfect candidate.

In that type of task you can create a service that runs periodically or as needed. You can make use of a system alarm.

Then your service can terminate when the task is over.

Creating and Using a Service

1. Create a Class

  1. Right click you project in visual studio and choose 'Add' -- 'New Class'.
  2. A dialog pops up.
  3. Type the class name.

Well nothing big a new class is created for us: ```c# namespace Servicer { class MyService { } }


#### **2. Derive from Android.App.Service**
We then make that class derive from `Android.App.Service`.
```language
    class MyService : Service
    {
    }

That will force us to implement one method. Why? Because the Service class is actually an abstract class.

3. Override OnBind()

We need only override the OnBind() method. That method takes an Intent object and should return an IBinder instance.

```c# public override IBinder OnBind(Intent intent) { return null; }


### **4. Register Service**
Register in the AndroidManifest by decorating with the Service attribute:
```c#
    [Service]
    class MyService : Service{}

We do this since Services are Android component so they have to be registered in the manifest.

5. Start the Service

This is normally done from an Activity. We do start a service using the Activity's StartService() method.

That method requires us to pass an Intent object.

So we first create the intent: ```c# Intent i=new Intent(this,typeof(MyService));

Then start the service:
```c#
StartService(i);

Comments