Understand Bound Service Using Xamarin With Visual Studio 2015

Introduction 

In previous articles, I have discussed about Unbound Services. In this article, we will learn the lifecycle of Bound Services. For creating a Bound Service, we need to create Bound Service class, a Binder for binding the Service, and Service Connection.

Bound Service

A service can be bound by application component by calling the BindService() function. It provides an interface that allows the bound component and services to interact with each other. When there are no clients bound to the service, Android will shut down that service.

Lifecycle of Bounded Service



Service class contains six types of methods as described in the following table. 

Method Use
OnCreate() This method is used for initializing service. It can be used for initializing variable and objects required by service.
OnBind() This method must be implemented by all the bound services. It will first call when any client try to connect with bound service. For Unbounded service, this method return null.
OnUnbind() This method is called when all clients are unbound.
OnRebind() This method is called when new clients get connected to service, after it had disconneted by OnUnbind().
OnStartCommand() This method must be implemented by all the started services.
OnDestroy() This method is called when service is destroyed by StopService() or StopSelf() method from application component.

The following steps are required for creating a Bound Service type for Android application.

Step 1 Create Blank Android Project

 

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

Step 2 Create Class, Binder, and ServiceConnection for Bound Service

Add new class in project by right clicking on project directory, select “Add->New Item”. Select “Class” from template. I have given  “BoundService” as the file name. In the same way, we need to add class for Binder and Service Connection.

 

Now, we need to extend “BoundService” class from base class “Service” and also implement base method required by Bound Service. Required methods for Bound Service are OnBind() (the starting point of Bound Service), OnUnBind(), and OnDestroy(). We can add OnCreate(), OnRebind() methods optionally.

Here, as I said, I am implementing Bound Service so OnBind() method returns “binder” object of “MyBoundServiceBinder” extended from Binder base class. We need to add “BoundServiceConnetion” extended from IServiceConnection base class. Snipped of code as follow,

BoundService.cs

  1. [Service]  
  2. Class BoundService : Service  
  3. {  
  4.    private MyBoundServiceBinder binder;  
  5.    public override void OnCreate()  
  6.    {  
  7.       base.OnCreate();  
  8.    }  
  9.    public override  IBinder OnBind(Intent intent)  
  10.    {  
  11.       binder = new MyBoundServiceBinder(this);  
  12.       Toast.MakeText(this"OnBind() method start from BoundService", ToastLength.Long).Show();  
  13.       Toast.MakeText(this"Bound Service is started",ToastLength.Long).Show();  
  14.       return binder;  
  15.     }  
  16.     public override bool OnUnbind(Intent intent)  
  17.     {  
  18.         Toast.MakeText(this"OnUnBind() Method Called from BoundService.cs",   ToastLength.Long).Show();  
  19.         return base.OnUnbind(intent);  
  20.      }  
  21.      public override void OnDestroy()  
  22.      {  
  23.           Toast.MakeText(this"Bound Service Destroyed", ToastLength.Long).Show();  
  24.           base.OnDestroy();  
  25.       }  
  26. }  

MyBoundServiceBinder.cs

  1. class MyBoundServiceBinder : Binder  
  2. {  
  3.     BoundService service;  
  4.     public MyBoundServiceBinder(BoundService service)  
  5.     {  
  6.         this.service = service;  
  7.      }  
  8. }  

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.         public void OnServiceDisconnected(ComponentName name)  
  8.         {  
  9.                  Console.WriteLine("OnServiceDisConnected() Method called");  
  10.         }  
  11. }  

Step 3 Layout of Main.axml and how to Bind and Unbind Bound Service

I have used the same layout as used in previous articles. I have just added two more buttons to start and stop Bound Service in Main.axml. The updated Main.axml is shown below.

  1. <?xmlversionxmlversion = "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. </LinearLayout>  

Screenshot of Updated Layout is shown below.

 
Now, when user clicks on “Start Bound Service” button, “BoundService” starts using BindService() method and when user clicks on “Stop Bound Service”, “BoundService” is terminated by Unbindservice() method. Snipped code 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.     
  10.    btnstartstartedservice.Click += Btnstartstartedservice_Click;    
  11.    btnstopstartedservice.Click += Btnstopstartedservice_Click;    
  12.    btnstartboundservice.Click += Btnstartboundservice_Click;    
  13.    btnstopboundservice.Click += Btnstopboundservice_Click;           
  14. }    
  15.     
  16. private void Btnstopboundservice_Click(object sender, System.EventArgs e)    
  17. {    
  18.    UnbindService(MyBoundServiceConnection);    
  19. }    
  20.     
  21. private void Btnstartboundservice_Click(object sender, System.EventArgs e)    
  22. {    
  23.    var BoundServiceIntent = new Intent(this,typeof(BoundService));    
  24.    BindService(BoundServiceIntent, MyBoundServiceConnection, Bind.AutoCreate);              
  25. }    
  26.     
  27. private void Btnstopstartedservice_Click(object sender, System.EventArgs e)    
  28. {    
  29.    StopService(new Intent(thistypeof(MyServices)));    
  30. }    
  31.     
  32. private void Btnstartstartedservice_Click(object sender, System.EventArgs e)    
  33. {    
  34.    StartService(new Intent(thistypeof(MyServices)));       
  35. }    

Output



Summary

In this article, we have learned about the life cycle of Bound Service, how to create, bind, and unbind Bound type of Service in Xamarin using Visual Studio 2015.


Similar Articles