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
- [Service]
- class IntenService : IntentService
- {
- IntentFilter intentfilter;
- ResponseReceiver receiver;
-
- public override void OnCreate()
- {
- base.OnCreate();
- intentfilter = new IntentFilter("MY_ACTION");
- receiver = new ResponseReceiver();
- RegisterReceiver(receiver, intentfilter);
- }
-
- public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, intstartId)
- {
- Toast.MakeText(this, "Intent Service is start", ToastLength.Long).Show();
- return base.OnStartCommand(intent, flags, startId);
- }
-
- public override IBinder OnBind(Intent intent)
- {
- return null;
- }
-
- public override void OnDestroy()
- {
- base.OnDestroy();
- Toast.MakeText(this, "Intent Service Destroyed", ToastLength.Long).Show();
- }
- protected override void OnHandleIntent(Intent intent)
- {
- string message = intent.GetStringExtra("Test_Message");
- Intent broadcastIntent = new Intent("MY_ACTION");
- broadcastIntent.PutExtra("Test_Message", message + "Readers....!!!!!");
- SendBroadcast(broadcastIntent);
- }
- }
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,
- [BroadcastReceiver(Enabled = true)]
- public class ResponseReceiver : BroadcastReceiver
- {
- public override void OnReceive(Context context, Intent broadcastIntent)
- {
- Toast.MakeText(context, "Processed String by IntenServiceOnHandleIntent Method is," + " value received: " + broadcastIntent.GetStringExtra("Test_Message"),
- ToastLength.Long).Show();
- }
- }
In “ResponseReceiver” class, I just received a modified message from OnHandleIntent() method of “IntenService” class and displayed it on screen.
- <?xml version="1.0"encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <Button
- android:text="Started Service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/btnstartstartedservice" />
- <Button
- android:text="Stop Started Service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/btnstopstartedservice" />
- <Button
- android:text="Start Bound Service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/btnstartboundservice" />
- <Button
- android:text="Stop Bound Service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/btnstopboundservice" />
- <Button
- android:text="Start Intent Service"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/btnstartintentservice" />
- </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.
- protected override void OnCreate(Bundle bundle)
- {
- base.OnCreate(bundle);
- SetContentView(Resource.Layout.Main);
- Button btnstartstartedservice = (Button)FindViewById(Resource.Id.btnstartstartedservice);
- Button btnstopstartedservice = (Button)FindViewById(Resource.Id.btnstopstartedservice);
- Button btnstartboundservice = (Button)FindViewById(Resource.Id.btnstartboundservice);
- Button btnstopboundservice = (Button)FindViewById(Resource.Id.btnstopboundservice);
- Button btnstartintentservice = (Button)FindViewById(Resource.Id.btnstartintentservice);
- btnstartstartedservice.Click += Btnstartstartedservice_Click;
- btnstopstartedservice.Click += Btnstopstartedservice_Click;
- btnstartboundservice.Click += Btnstartboundservice_Click;
- btnstopboundservice.Click += Btnstopboundservice_Click;
- btnstartintentservice.Click += Btnstartintentservice_Click;
- }
- private void Btnstartintentservice_Click(object sender, System.EventArgs e)
- {
- Intent intent = new Intent(this, typeof(IntenService));
- intent.PutExtra("Test_Message", "Hello, ");
- Toast.MakeText(this, "Send Test_Message to IntenService Service Class", ToastLength.Long).Show();
- StartService(intent);
- }
- private void Btnstopboundservice_Click(object sender, System.EventArgs e)
- {
- UnbindService(MyBoundServiceConnection);
- }
- private void Btnstartboundservice_Click(object sender, System.EventArgs e)
- {
- var BoundServiceIntent = new Intent(this, typeof(BoundService));
- BindService(BoundServiceIntent, MyBoundServiceConnection, Bind.AutoCreate);
- }
- private void Btnstopstartedservice_Click(object sender, System.EventArgs e)
- {
- StopService(new Intent(this, typeof(MyServices)));
- }
- private void Btnstartstartedservice_Click(object sender, System.EventArgs e)
- {
- StartService(new Intent(this, typeof(MyServices)));
- }
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.