Download Code

In this tutorial you will learn about AsyncTask and how to use it in android application.To understand this concept you must have some knowledge of threads and Runnable,how they works.So let me give some basic information about everything which we will use in this tutorial.

AsyncTask

AsyncTasks enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

There are three type of parameters used by asynchronous task.

  • Params :  the type of the parameters sent to the task upon execution.
  • Progress : the type of the progress units published during the background computation.
  • Result : the type of the result of the background computation.

There are four steps required for asynchronous task to execute.

  • onPreExecute() : This method is called before thread get started.Used to setup a task like progress bar.
  • RunInBackground(Params…) : responsible for background computation.This method will contain the background running operation modules.
  • onProgressUpdate(Progress…) : This method is used to display progress in UI while background computation is executing.
  • onPostExecute(Result) : This method gets result of background computation as a parameter.

In this tutorial we will develop a sample android application.To load website and at the same while loading webpage. You can click a button which will represent that background operation is running without disturbance.

Ok,Now create Android Application Project.

After creating project go to your Main.axml .Write code for two buttons and web View.

asynctask,xamarin,android,C#,xamarin android

Now go to your MainActivity.cs class.Create variables for buttons,webView,refer their id’s and apply click listener on both buttons.

Next create a private class within the parent class,extend it with AsyncTask  class.

We have just used doInBackground() method yet.One by One we will go through every method.

Now create variable for private class(here parallel).Within Display Website button case and call display url method in doInBackground() method.Next show Toast on other button click.

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Webkit;
using Android.Views;
using System;

namespace XamarinAsyncTask
{
	[Activity(Label = "XamarinAsyncTask", MainLauncher = true, Icon = "@mipmap/icon")]
	public class MainActivity : Activity, Android.Views.View.IOnClickListener
	{

		Button asyncBtn, other;
		WebView myWeb;

		protected override void OnCreate(Bundle savedInstanceState)
		{
			base.OnCreate(savedInstanceState);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Main);
			initialize();


		}
		public void initialize()
		{
			asyncBtn = ( Button )this.FindViewById(Resource.Id.webBtn);
			other = ( Button )FindViewById(Resource.Id.otherBtn);
			myWeb = (WebView)FindViewById(Resource.Id.webPage);
			asyncBtn.SetOnClickListener(this);
			other.SetOnClickListener(this);
		}

		public void OnClick(View v)
		{
			switch(v.Id){
				case Resource.Id.webBtn:
					parallel task = new parallel(this);
					task.Execute(new String[] { "http://www.androidcodec.com" });
					break;
				case Resource.Id.otherBtn:
					Toast.MakeText(this, "I am trying to disturb your Thread",ToastLength.Short).Show();
					break;
			}
		}
		public class parallel : AsyncTask<String, Java.Lang.Object, String>
		{
			MainActivity mainActivity;
			public parallel(MainActivity mainActivity)
			{
				this.mainActivity = mainActivity;
			}
			protected override String RunInBackground(params String[] @params)
			{
				mainActivity.myWeb.LoadUrl(@params[0]);
				return "d";
			}
		}
	}
}

At last go to your Properties > AndroidManifest.xml file and add INTERNET permission.

asynctask,xamarin android,xamarin C#,RunInbackground,background process,android C#

Now save and run Android Application Project.Click on Display Website and your background computation start.At the same when you click other button it will display toast without disturbing background computation.

asynctask,xamarin,C#,programming android C#

That’s it for this tutorial.I hope you understand everything about Asynchronous Tasks.Next tutorial will be about download something using Asynchronous Task.

Thanks.