Understand Hybrid Service In Xamarin With Visual Studio 2015

Introduction

In this article, we will learn the  lifecycle of Hybrid Service, and how to create, bind and unbind Hybrid Service, using Xamarin with Visual Studio 2015.

Hybrid Service

A hybrid service is a combination of started Service and bound Service. A hybrid Service can be started by any application component. It can bind to the Application component or be started by some event. Hybrid Service will keep running, until it is clearly told to stop or until no clients are bound to it.

Lifecycle of Hybrid Service

Lifecycle of Hybrid Service is shown in the figure given below. Hybrid Service class content has six methods described in the table given below.


MethodUse
OnCreate()This method is used to initialize the Service. It can be used for initializing the variable, object required by the Service.
OnBind()This method must be implemented by all bound Services. It will first call when any client tries to connect with bound Service.
OnUnbind()This method calls when all the clients are unbound.
OnRebind()This method calls when new clients have connected to the Service. Afterwards, it will be disconneted by OnUnbind().
OnStartCommand()This method must be implemented by all started Services. It calls first, when type of Service is started Service.
OnDestroy()This method calls when the Service is destroyed by StopService() or StopSelf() method from the Application component.

The steps are given below to create Hybrid Service in an Android Applications.

Step 1

Create new Project for Android Application
 

I have selected “Blank App(Android)” from template for this article.

Step 2

Creating HybridService Class

Add new class in project by right clicking on project directory, select “Add->New Item”. Select “Class” from the template. I have given the name as “HybridService” as the file name, as shown below. 

Step 3

Declaring “HybridService” class with Override Methods

Now, we need to extend (inherit) “HybridService” class from base class “Service” and also implement base method required by Service. Here, I am implementing Hybrid Service, so required compulsory methods are OnStartCommand(), OnDestroy() and OnBind(). We can add OnCreate() but it is optional. Here, as I said, I am implementing Hybrid Service, so we need to create Binder and Service Connection class. Here, I used a previous article's “Understand IntentService using Xamarin with Visual Studio 2015” project structure, so in that “BoundServiceBinder” and “BoundServiceConnection” is already created, which is Binder and Service Connection class respectively. The code snippet is given below.

HybridService.cs
  1. [Service]  
  2. class HybridService : Service  
  3. {  
  4.     private MyBoundServiceBinder binder_hybrid;  
  5.     public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, intstartId)  
  6.    {  
  7.          Toast.MakeText(this"Hybrid Service is start", ToastLength.Long).Show();  
  8.          return base.OnStartCommand(intent, flags, startId);  
  9.     }  
  10.     public override IBinder OnBind(Intent intent)  
  11.    {  
  12.          binder_hybrid = newMyBoundServiceBinder(this);  
  13.          Toast.MakeText(this"OnBind() method start from HybridService", ToastLength.Long).Show();  
  14.          Toast.MakeText(this"Hybrid Service is started", ToastLength.Long).Show();  
  15.          return binder_hybrid;  
  16.     }  
  17.     public override bool OnUnbind(Intent intent)  
  18.     {  
  19.          Toast.MakeText(this"OnUnBind() Method Called from HybridService.cs", ToastLength.Long).Show();  
  20.          return base.OnUnbind(intent);  
  21.      }  
  22.      public override void OnDestroy()  
  23.     {  
  24.          base.OnDestroy();  
  25.          Toast.MakeText(this"Hybrid Service is Destroyed", ToastLength.Long).Show();  
  26.     }  
  27. }  

MyBoundServiceBinder.cs

  1. class MyBoundServiceBinder : Binder  
  2. {  
  3.       HybridService hybridService;  
  4.       BoundService service;  
  5.   
  6.       public MyBoundServiceBinder(HybridService hybridService)  
  7.       {  
  8.               this.hybridService = hybridService;  
  9.       }  
  10.       public MyBoundServiceBinder(BoundService service)  
  11.       {  
  12.                this.service = service;  
  13.        }  
  14. }  

BoundServiceConnection.cs

  1. class BoundServiceConnection : Java.Lang.Object, IServiceConnection  
  2. {  
  3.         public void OnServiceConnected(ComponentName name, IBinder service)  
  4.         {  
  5.                Console.WriteLine("OnServiceConnected() Method called");  
  6.         }  
  7.   
  8.         public void OnServiceDisconnected(ComponentName name)  
  9.         {  
  10.                 Console.WriteLine("OnServiceDisConnected() Method called");  
  11.         }  
  12. }  

As I explained previously, lifecycle of Hybrid Service starts from “OnStartCommand()” method. When the Service given above starts by an Android component (here is the activity), it will show the message that “Hybrid Service is started” on the screen. We can see this in an output section of this article. Similarly, when this Service is terminated, it will show the message “Hybrid Service is Destroyed”. Hybrid Service requires bound due to which I am returning binder object in OnBind()method.

Step 4

Layout of the Main.axml

I have used same project as used in my previous article on “Understand Intent Service using Xamarin with Visual Studio 2015”. I just added two buttons for starting and stopping Hybrid Service as “Start Hybrid Service” and “Stop Hybrid Service”. Final Main.axmlfile looks, as shown below.

  1. <?xml version="1.0"encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       android:orientation="vertical"  
  4.       android:layout_width="match_parent"  
  5.       android:layout_height="match_parent">  
  6. <Button  
  7.       android:text="Started Service"  
  8.       android:layout_width="match_parent"  
  9.       android:layout_height="wrap_content"  
  10.       android:id="@+id/btnstartstartedservice" />  
  11. <Button  
  12.       android:text="Stop Started Service"  
  13.       android:layout_width="match_parent"  
  14.       android:layout_height="wrap_content"  
  15.       android:id="@+id/btnstopstartedservice" />  
  16. <Button  
  17.       android:text="Start Bound Service"  
  18.       android:layout_width="match_parent"  
  19.       android:layout_height="wrap_content"  
  20.       android:id="@+id/btnstartboundservice" />  
  21. <Button  
  22.       android:text="Stop Bound Service"  
  23.       android:layout_width="match_parent"  
  24.       android:layout_height="wrap_content"  
  25.       android:id="@+id/btnstopboundservice" />  
  26. <Button  
  27.       android:text="Start Intent Service"  
  28.       android:layout_width="match_parent"  
  29.       android:layout_height="wrap_content"  
  30.       android:id="@+id/btnstartintentservice" />  
  31. <Button  
  32.       android:text="Start Hybrid Service"  
  33.       android:layout_width="match_parent"  
  34.       android:layout_height="wrap_content"  
  35.       android:id="@+id/btnstarthybridservice" />  
  36. <Button  
  37.       android:text="Stop Hybrid Service"  
  38.       android:layout_width="match_parent"  
  39.       android:layout_height="wrap_content"  
  40.       android:id="@+id/btnstophybridservice" />  
  41. </LinearLayout>   

Screenshot of Layout is shown below.

Now, when the user clicks on “StartHybridService” button, “HybridService” Service starts using StartService() method and is bound by BindService() method. The code snippet of OnCreate() method of MainActivity is given below.

  1. protected override void OnCreate(Bundle bundle)  
  2. {  
  3.      base.OnCreate(bundle);  
  4.      SetContentView(Resource.Layout.Main);  
  5.      Button btnstartstartedservice = (Button)FindViewById(Resource.Id.btnstartstartedservice);  
  6.      Button btnstopstartedservice = (Button)FindViewById(Resource.Id.btnstopstartedservice);  
  7.      Button btnstartboundservice = (Button)FindViewById(Resource.Id.btnstartboundservice);  
  8.      Button btnstopboundservice = (Button)FindViewById(Resource.Id.btnstopboundservice);  
  9.      Button btnstartintentservice = (Button)FindViewById(Resource.Id.btnstartintentservice);  
  10.      Button btnstarthybridservice = (Button)FindViewById(Resource.Id.btnstarthybridservice);  
  11.      Button btnstophybridservice = (Button)FindViewById(Resource.Id.btnstophybridservice);  
  12.   
  13.      btnstartstartedservice.Click += Btnstartstartedservice_Click;  
  14.      btnstopstartedservice.Click += Btnstopstartedservice_Click;  
  15.      btnstartboundservice.Click += Btnstartboundservice_Click;  
  16.      btnstopboundservice.Click += Btnstopboundservice_Click;  
  17.      btnstartintentservice.Click += Btnstartintentservice_Click;  
  18.      btnstarthybridservice.Click += Btnstarthybridservice_Click;  
  19.      btnstophybridservice.Click += Btnstophybridservice_Click;  
  20. }  
  21.   
  22. private void Btnstophybridservice_Click(object sender, System.EventArgs e)  
  23. {  
  24.      UnbindService(MyBoundServiceConnection);  
  25.      StopService(new Intent(thistypeof(HybridService)));  
  26. }  
  27.   
  28. private void Btnstarthybridservice_Click(object sender, System.EventArgs e)  
  29. {  
  30.      StartService(new Intent(thistypeof(HybridService)));  
  31.      BindService((new Intent(thistypeof(HybridService))), MyBoundServiceConnection, Bind.AutoCreate);  
  32. }  
  33.   
  34. private void Btnstartintentservice_Click(object sender, System.EventArgs e)  
  35. {  
  36.      Intent intent = new Intent(thistypeof(IntenService));  
  37.      intent.PutExtra("Test_Message""Hello, ");  
  38.      StartService(intent);  
  39. }  
  40.   
  41. private void Btnstopboundservice_Click(object sender, System.EventArgs e)  
  42. {  
  43.      UnbindService(MyBoundServiceConnection);  
  44. }  
  45.   
  46. private void Btnstartboundservice_Click(object sender, System.EventArgs e)  
  47. {  
  48.      var BoundServiceIntent = new Intent(thistypeof(BoundService));  
  49.      BindService(BoundServiceIntent, MyBoundServiceConnection, Bind.AutoCreate);  
  50. }  
  51.   
  52. private void Btnstopstartedservice_Click(object sender, System.EventArgs e)  
  53. {  
  54.       StopService(new Intent(thistypeof(MyServices)));  
  55. }  
  56.   
  57. private void Btnstartstartedservice_Click(object sender, System.EventArgs e)  
  58. {  
  59.        StartService(new Intent(thistypeof(MyServices)));  
  60. }  

Output


 

Summary

In this article, we learned about the Hybrid Service lifecycle and how to create, start, bind and unbind Hybrid Service  in Xamarin with Visual Studio 2015.

Next Recommended Readings