Understand Unbound Service In Xamarin With Visual Studio 2015

Introduction

Any Android Application is made of four parts, which are Activity, Broadcast receiver, Content Provider and Service. Service is used to perform the background tasks without any interaction with the user and it also works after destroying the application. Generally, the Services are used to perform long running operations in the background. Service can be used to download file operations, perform file I/O operation, play music and interact with the content provider, all from the background. Services can be of four different types, which are given below.

  1. Started or Unbound Service
  2. Bound Service
  3. Intent Service
  4. Hybrid Service

Depending on the application requirement, we can use the types of Services given above. Mostly, Intent Service and Bound Service are used because both types of Services can perform most of the tasks, which can be performed by an Android Application.

In this article, we learn about unbound Services.

Unbound Service

A Service is started by an Application component by StartService() callback method. Started or Unbound Service will be run in the background; even if the Application component that started it is destroyed. This type of Service performs single operations and it does not return a result to the caller. For example, when downloading or uploading a file from Internet, when the download operation is complete, the Service stops itself.

Life cycle of Unbound Service

Lifecycle of Unbound Service is shown the figure given below. Service class content's six methods are described in the table given below.

Method Use
OnCreate() This method is used to initialize the Service. It can be used to initialize 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. For Unbound Service, this method returns null.
OnUnbind() This method calls when all clients unbind.
OnRebind() This method calls when the new clients have connected to the Service. Afterwards, it has been disconneted by OnUnbind().
OnStartCommand() This method must be implemented by all the started Services. It calls first when the type of Service is started Service.
OnDestroy() This method call when service is destroyed by StopService() or StopSelf() method from the Application component.

The steps are given below to create Started or unbound Service in an Android Application.

Step 1

Create new Project for Android Application


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

Step 2

Creating Started Service

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 “MyServices” as the file name, which is shown below.


Step 3

Declaring “MyServices” class with Override Methods

Now, we need to extend (inherit) “MyServices” class from the base class “Service” and also implement the base method, which is required by Service. Here, I am implementing “Started Service” so required compulsory methods, which are OnStartCommand(), OnDestroy() and OnBind(). We can add OnCreate() but it is optional. Here, as I said, I am implementing “Started Service”, so OnBind() method returns null. The code snippet is given below.

  1. [Service]  
  2. class MyServices : Service  
  3. {  
  4. public override StartCommandResult OnStartCommand(Intent intent,StartCommandFlags                                                       flags, int startId)  
  5.     {  
  6.         Toast.MakeText(this"Started Service is start", ToastLength.Long).Show();  
  7.         return base.OnStartCommand(intent, flags, startId);  
  8.      }  
  9. public override void OnDestroy()  
  10.      {  
  11.          base.OnDestroy();  
  12.          Toast.MakeText(this"Started Service is stop", ToastLength.Long).Show();  
  13.       }  
  14. public override IBinder OnBind(Intent intent)  
  15.       {  
  16.             return null;  
  17.        }  
  18. }  
As I explained previously, Lifecycle of Unbound or Started Service starts from “OnStartCommand()” method. Thus, when the Service given above starts by an Android component (Here is Activity), which will show the message that “Started Service is start” on the screen. We can see this in output section of this article. Similarly when this Service is terminated by an Android component, it will show the message “Started Service is stop”. Started Service is never bind due to which I am returning “null” in OnBind()method.

Step 4

Layout of the Main.axml

For start Service, I took one button as “Started Service” and for stop Service, one button as “Stop Started Service”. Thus, in my Main.axml contents, two buttons and Final Main.axml file 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. </LinearLayout>  
Screenshot of the layout is shown below. 


Now, when the user clicks on “Started Service” button, “MyServices” Service starts using StartService() method and when the user clicks on “Stop Started Service”, “MyServices” Service is terminated by StopService() 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.    btnstartstartedservice.Click += Btnstartstartedservice_Click;  
  8.    btnstopstartedservice.Click += Btnstopstartedservice_Click;  
  9. }  
  10. private void Btnstopstartedservice_Click(object sender, System.EventArgs e)  
  11. {  
  12.    StopService(new Intent(thistypeof(MyServices)));  
  13. }  
  14. private void Btnstartstartedservice_Click(object sender, System.EventArgs e)  
  15. {  
  16.    StartService(new Intent(thistypeof(MyServices)));     
  17. }  
Output 


Summary

In this article, we learned about Unbound Service Life cycle and how to create, Start and stop Started or Unbound types of Service in Xamarin, using Visual Studio 2015.

Next Recommended Readings