Android AsyncTask Example

By | September 1, 2015

AysnTask is an inbuilt class in android which can be used for performing background operations like downloading a file, making HTTP Request and then showing the results on the UI.
AsyncTask 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.

The basic structure of AsyncTask is as follows:

private class SampleAsyncTask extends AsyncTask<String, Integer, Integer> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Integer doInBackground(String... params) {
			return null;
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
		}
	}

When an asynchronous task is executed, the task goes through 4 steps:

onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
doInBackground(Params…), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress…) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress…) step.
onProgressUpdate(Progress…), invoked on the UI thread after a call to publishProgress(Progress…). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Implementation:
Sample example of AsyncTask for opening a website in background:
Create an Android Activity and copy the code below:

package com.tutorialsface.android.androidasynctasktutorial;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Toast;

public class MainActivity extends Activity {
	final Context context = this;

	/** Called when the activity is first created. */

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
      }

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

		@Override
		protected String doInBackground(String... urls) {
                         /*Your background work here */

			WebView webView = (WebView) findViewById(R.id.webView);
			webView.getSettings().setJavaScriptEnabled(true);
			webView.loadUrl(urls[0]);

			return null;
		}

		@Override
		protected void onPostExecute(String result) {
                       /* Called when work in doInBackground() is finished.*/
                       /* So you can write UI here i.e. update your UI after finishing doInBackground*/
		}
	}
	public void readWebpage(View v) {
		LoadWebPage task = new LoadWebPage();
		task.execute(new String[] { "http://www.tutorialsface.com" });

	}
}

The layout file for the above Activity is as follows:
main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="readWebpage"
        android:text="Load Webpage" >
    </Button>

    <WebView
        android:id="@+id/webView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

You may need to modify your AndroidManifest.xml to add required Internet Permissions.

8,772 total views, 1 views today

(Visited 4,736 times, 1 visits today)