Download Code

Android AsyncTask Tutorial

In android asynctask 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.
  • doInBackground(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 android asynctask tutorial project go to your activity_main.xml .Write code for two buttons and webView just like this.

android asynctask,android asynctask tutorial,asynctask tutorial,

Now go to your MainActivity.java class.Create variables for buttons,webView,refer their id’s and apply click listener on both buttons.After that your class should look like this.

public class MainActivity extends Activity implements OnClickListener{

	Button web,message;   // button variables
	WebView displayWeb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initialize();     // calling method from where everything will start
	}
	// refering id and click listener method
	public void initialize(){
		web = (Button) findViewById(R.id.webBtn);     // getting display webpage button id
		message = (Button) findViewById(R.id.otherBtn);   // getting message display button id
		displayWeb = (WebView) findViewById(R.id.webPage);   // refering webview
		displayWeb.getSettings().setJavaScriptEnabled(true);   // enabling javascript
		web.setOnClickListener(this);                       // applying click listener
		message.setOnClickListener(this);                   // applying click listener
	}
	// click event method
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.webBtn:
			
			break;
		case R.id.otherBtn:
			
			break;
		}
	}
}

Next create a private class within the parent class,extend it with AsyncTask  class.Implement all methods of AsyncTask class.

public class MainActivity extends Activity implements OnClickListener{

	Button web,message;   // button variables
	WebView displayWeb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initialize();     // calling method from where everything will start
	}
	// refering id and click listener method
	public void initialize(){
		web = (Button) findViewById(R.id.webBtn);     // getting display webpage button id
		message = (Button) findViewById(R.id.otherBtn);   // getting message display button id
		displayWeb = (WebView) findViewById(R.id.webPage);   // refering webview
		displayWeb.getSettings().setJavaScriptEnabled(true);   // enabling javascript
		web.setOnClickListener(this);                       // applying click listener
		message.setOnClickListener(this);                   // applying click listener
	}
	// click event method
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.webBtn:
			break;
		case R.id.otherBtn:
			
			break;
		}
	}

	private class parrllel extends AsyncTask<String, Void, String>{

		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			
			                      
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			
		}

		

		
	}

}

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

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

MainActivity.java

package androidcodec.parallelcomputation;

/*
 * 
 * All Rights Reserved By: Farhan Rasheed
 * 
 * */

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity implements OnClickListener{

	Button web,message;   // button variables
	WebView displayWeb;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initialize();     // calling method from where everything will start
	}
	// refering id and click listener method
	public void initialize(){
		web = (Button) findViewById(R.id.webBtn);     // getting display webpage button id
		message = (Button) findViewById(R.id.otherBtn);   // getting message display button id
		displayWeb = (WebView) findViewById(R.id.webPage);   // refering webview
		displayWeb.getSettings().setJavaScriptEnabled(true);   // enabling javascript
		web.setOnClickListener(this);                       // applying click listener
		message.setOnClickListener(this);                   // applying click listener
	}
	// click event method
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.webBtn:
			parrllel task = new parrllel();    // creating a variable for asyncTask
			task.execute(new String[] { "http://www.androidcodec.com "});    // url to load on webpage
			break;
		case R.id.otherBtn:
			Toast.makeText(getApplicationContext(), "I am try to disturb your thread", Toast.LENGTH_SHORT).show();
			break;
		}
	}

	private class parrllel extends AsyncTask<String, Void, String>{

		@Override
		protected String doInBackground(String... urls) {
			// TODO Auto-generated method stub
			
			displayWeb.loadUrl(urls[0]);                        // loading url 
			return "d";
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			
		}

		

		
	}

}

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

android asynctask,android asynctask tutorial,asynctask tutorial,

Now save and run android asynctask tutorial 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.Output will be like this.

android asynctask,android asynctask tutorial,asynctask tutorial,

After clicking second button.

android asynctask,android asynctask tutorial,asynctask tutorial,

 

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

Thanks