Understand IntentService In Xamarin With Visual Studio 2015

Introduction

In my previous article, we learned about bound and unbound services - how to create them and their life cycle. In this article, we will learn the lifecycle of Intent service and how to create Intent service using Xamarin with Visual Studio 2015.

IntentService

An IntentService is a subclass of the Service class. It is simply service creation and usage. IntentService does not handle multiple requests simultaneously. It is like queue processor where work is queued up and IntentService processes each work one by one. It is the best way to implement service using the IntentService class when we do not need multiple works at a time. This type of service is not bound by application component.

Life cycle of IntentService

Lifecycle of IntentService is very similar to Unbound Service, as shown in the following figure.

 

IntentService class contains six methods as described in the following table.

Method

Use

OnCreate()

This method is used for initializing service. It can be used for initializing variable, object required by service.

OnBind()

This method must be implemented by all bound services. It will be called first when any client tries to connect with bound service. For IntentService is not bound by any application component that’s why this method returns null.

OnUnbind()

This method calls when all clients are unbound.

OnRebind()

This method calls when new clients have connected to service, after it had disconneted by OnUnbind().

OnStartCommand()

This method must be implemented by all started services. It calls first when the type of service is set to started service.

OnDestroy()

This method calls when service is destroyed by StopService() or StopSelf() method from application component.

Following are the steps to create IntentService in Android application.

Step 1 Create new Project for Android Application 

 

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

Step 2 Creating IntenService Class

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


Step 3 Declaring “IntenService” class with Override Methods

Now, we need to extend (inherit) “IntenService” class from base class “IntentService” and also implement base method required by Service. Here, I am implementing IntentService, so abstract methods are OnStartCommand(), OnDestroy(), OnHandleIntent(), and OnBind() needs to be implemented. We can add OnCreate() but it is optional. Here, as I said, I am implementing “IntentService” so OnBind() method returns null. Snipped code is as follows.

IntenService.cs
  1. [Service]  
  2. class IntenService : IntentService  
  3. {  
  4.     IntentFilter intentfilter;  
  5.     ResponseReceiver receiver;  
  6.   
  7. public override void OnCreate()  
  8. {  
  9.       base.OnCreate();  
  10.       intentfilter = new IntentFilter("MY_ACTION");  
  11.       receiver = new ResponseReceiver();  
  12.       RegisterReceiver(receiver, intentfilter);  
  13. }  
  14.   
  15. public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, intstartId)  
  16. {  
  17.         Toast.MakeText(this"Intent Service is start", ToastLength.Long).Show();  
  18.         return base.OnStartCommand(intent, flags, startId);  
  19. }  
  20.   
  21. public override IBinder OnBind(Intent intent)  
  22. {  
  23.          return null;  
  24. }  
  25.   
  26. public override void OnDestroy()  
  27. {  
  28.          base.OnDestroy();  
  29.          Toast.MakeText(this"Intent Service Destroyed", ToastLength.Long).Show();  
  30. }  
  31. protected override void OnHandleIntent(Intent intent)  
  32. {  
  33.          string message = intent.GetStringExtra("Test_Message");  
  34.          Intent broadcastIntent = new Intent("MY_ACTION");  
  35.          broadcastIntent.PutExtra("Test_Message", message + "Readers....!!!!!");  
  36.          SendBroadcast(broadcastIntent);  
  37. }  
  38. }  

As I explained previously, Lifecycle of IntentService starts from “OnStartCommand()” method. So When the above service starts by an Android component (Activity in this example), it will show message that “IntentService is start” on screen. Same when this service is terminated, it will show message “IntentService is Destroyed”. Intent Service is never bound that’s why I am returning “null” in OnBind()method. When any work queues up in IntentService, OnHandleIntent() method calls and performs required work. Here, When IntentService starts it will start with OnCreate() method where I have registered Broadcast Receiver by RegisterReceiver() method. I have explained how Broadcast Receiver works in my previous article on “Understand Broadcast Receiver using Xamarin with Visual Studio 2015 so you can go through it for understanding of how Broadcast receiver works and implements in Xamarin.

In this article, I am sending one message from MainActivity class to IntentService class. In OnHandleIntent() method, I add “Readers…..!!!!” string in message send by MainActivity class and send output string to Broadcast Receiver. In this article, I have created “ResponseReceiver” class which extended from Broadcast Receiver base class. “ResponseReceiver” class looks like below,

  1. [BroadcastReceiver(Enabled = true)]  
  2. public class ResponseReceiver : BroadcastReceiver  
  3. {  
  4.       public override void OnReceive(Context context, Intent broadcastIntent)  
  5.       {  
  6.                Toast.MakeText(context, "Processed String by IntenServiceOnHandleIntent Method is,"   + " value received: " + broadcastIntent.GetStringExtra("Test_Message"),  
  7.                                           ToastLength.Long).Show();  
  8.       }    
  9. }  

In “ResponseReceiver” class, I just received a modified message from OnHandleIntent() method of “IntenService” class and displayed it on screen.

Step 4 Layout of the Main.axml

I have used the same project as used in my previous article on “Understand Bound Service using Xamarin with Visual Studio 2015”. I just added one button for starting IntentService as “Start IntentService”. Final Main.axml file looks like 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. </LinearLayout>  

Screenshot of Layout as shown below,

Now, when user clicks on “Start Intent Service” button, “IntentService” service starts using StartService() method. Snipped code of OnCreate() method of MainActivity is as 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.      btnstartstartedservice.Click += Btnstartstartedservice_Click;  
  11.      btnstopstartedservice.Click += Btnstopstartedservice_Click;  
  12.      btnstartboundservice.Click += Btnstartboundservice_Click;  
  13.      btnstopboundservice.Click += Btnstopboundservice_Click;  
  14.      btnstartintentservice.Click += Btnstartintentservice_Click;          
  15. }  
  16. private void Btnstartintentservice_Click(object sender, System.EventArgs e)  
  17. {  
  18.      Intent intent = new Intent(thistypeof(IntenService));  
  19.      intent.PutExtra("Test_Message""Hello, ");  
  20.      Toast.MakeText(this"Send Test_Message to IntenService Service Class", ToastLength.Long).Show();  
  21.      StartService(intent);  
  22. }  
  23. private void Btnstopboundservice_Click(object sender, System.EventArgs e)  
  24. {  
  25.      UnbindService(MyBoundServiceConnection);  
  26. }  
  27. private void Btnstartboundservice_Click(object sender, System.EventArgs e)  
  28. {  
  29.      var BoundServiceIntent = new Intent(thistypeof(BoundService));  
  30.      BindService(BoundServiceIntent, MyBoundServiceConnection, Bind.AutoCreate);  
  31. }  
  32. private void Btnstopstartedservice_Click(object sender, System.EventArgs e)  
  33. {  
  34.      StopService(new Intent(thistypeof(MyServices)));  
  35. }  
  36. private void Btnstartstartedservice_Click(object sender, System.EventArgs e)  
  37. {  
  38.      StartService(new Intent(thistypeof(MyServices)));  
  39. }  

Output

 

Summary

In this article, we have learned about the IntentService life cycle and how to create and start IntentService type of service in Xamarin with Visual Studio 2015.

Up Next
    Ebook Download
    View all
    Learn
    View all