Xamarin Android – Service Tutorial
This is a xamarin android service tutorial and example.
A service is an android component used to implement long running operations.
They allow work to be executed without actively interacting with user interaface components.
All android apps have atleast one of the four cornerstone components: Activity, BroadcastReceiver, ContentProviders and Services.
The Service is the primary mechanism for background work in Android.
When to use Services
You should use a service when you want to implement long running background operations.
Services are very commonly used for tasks that are performed in the background, such as time consuming calculations, downloading files, playing music, and so on.
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.
Furthermore, services can also be used for IPC(Interprocess Communication) between Android applications. For example one Android app might use the music player service that is from another app or an app might expose data (such as a person’s contact information) to other apps via a service.
Types of Services in Android
Services, which we said are used to implement long running tasks can be divided or classified into 4 different categories.
- Bound Service – As the names suggests, this is a service that has some other component bound to it. Normally this other component is usually an activity.
- Started Service – This is a service that has been started by some other Android component and will run in the background until something stops it. Remember we talked about Bound Services having another component bound to it, on the other hand a started service does not have any clients directly bound to it.
- Hybrid Service – This is a hybrid of both bound and started services. It has both their characteristics. A hybrid service can be started by when a component binds to it or it may be started by some event.
- IntentService – This is a class that inherits from
Service
. It is specialized and is basically used for easy creation then usage of services. An IntentService is meant to handle individual autonomous calls. Normally generally a service handles multiple calls concurrently, however anIntentService
is more like a work queue processor – work is queued up and an IntentService processes each job one at a time on a single worker thread. Typically, an IntentService is not bound to an Activity or a Fragment.
Which Service Type should you use?
Different tasks may require different types of services, so you should choose the service type that suits your application requirements.
Having said that,it’s normally recommended that an IntentService or a bound service be used for most tasks as they are sufficient for most tasks that an Android application must perform.
An IntentService is a good choice for "one-shot" tasks, such as downloading a file, while a bound service would be suitable when frequent interactions with an Activity/Fragment is required.
More Service Types
Majority of services normally run in the background. We can call these Background Services
However, this is not a requirement. There is a special sub-category of Service class known as a Foreground service.
Foreground Services do get given a higher priority (compared to a normal service) to perform some work for the user (such as playing music).
We also have Remote Services. These do run on their own processes on the same device.
Remote Services can also be called Out-of-Process Services.
Creating and Using a Service
1. Create a Class
- Right click you project in visual studio and choose ‘Add’ — ‘New Class’.
- A dialog pops up.
- Type the class name.
Well nothing big a new class is created for us:
namespace Servicer
{
class MyService
{
}
}
2. Derive from Android.App.Service
We then make that class derive from Android.App.Service
.
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.
public override IBinder OnBind(Intent intent)
{
return null;
}
4. Register Service
Register in the AndroidManifest by decorating with the Service attribute:
[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.
If you prefer a vide tutorial check here:
That method requires us to pass an Intent object.
So we first create the intent:
Intent i=new Intent(this,typeof(MyService));
Then start the service:
StartService(i);
Android Service Example – Start/Stop a service at runtime using a CheckBox
Main.axml
Here’s our layout. We have a checkbox to start or stop the service.
Our root XML element is the RelativeLayout.
We have a TextView which will be our header label.
Then a CheckBox that we use to start or stop the service.
Here’s the full XML layout.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/headerLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="casual"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="Service - Start and Stop"
android:textAllCaps="true"
android:textSize="24sp"
android:textStyle="bold" />
<CheckBox
android:id="@+id/myCheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Start/Stop"
android:padding="5dp" />
</RelativeLayout>
GreeterService.cs
Let’s now come to our C# code. Xamarin Android apps are written in C# and XAML.
Import Namespaces
We need to import namespaces into our Xamarin Android app.
For instance, Android.App
where the Service
component resides.
We then specify our namespace:
namespace FirstService
This is our Service. We derive from android.app.Service
.
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
namespace FirstService
{
[Service]
class GreeterService : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
/*
* This service will run until stopped explicitly because we are returning sticky
*/
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
Toast.MakeText(this,"Greetings from our First Service",ToastLength.Long).Show();
return StartCommandResult.Sticky;
}
/*
* When our service is to be destroyed, show a Toast message before the destruction.
*/
public override void OnDestroy()
{
base.OnDestroy();
Toast.MakeText(this, "Oh Greeter Service is Destroyed.", ToastLength.Long).Show();
}
}
}
MainActivity.cs
Here’s our main activity clas:
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
namespace FirstService
{
[Activity(Label = "FirstService", MainLauncher = true, Theme = "@android:style/android:Theme.Holo.Light.DarkActionBar", Icon = "@drawable/icon")]
public class MainActivity : Activity
{
public void StartGreeterService()
{
Intent myIntent=new Intent(this,typeof(GreeterService));
this.StartService(myIntent);
}
public void StopGreeterService()
{
Intent myIntent = new Intent(this, typeof(GreeterService));
this.StopService(myIntent);
}
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView (Resource.Layout.Main);
CheckBox startServiceCheckBox = FindViewById<CheckBox>(Resource.Id.myCheckbox);
startServiceCheckBox.CheckedChange += startServiceCheckBox_CheckedChange;
}
void startServiceCheckBox_CheckedChange(object sender, CompoundButton.CheckedChangeEventArgs e)
{
if (e.IsChecked)
{
StartGreeterService();
}
else
{
StopGreeterService();
}
}
}
}
RESULT
Best Regards.