Android AsyncTask Example with Progress Bar

By Arvind Rai, July 07, 2015
This page will walk through Android AsyncTask example with progress bar. This is asynchronous task which runs using background thread and updates UI thread. AsyncTask is an abstract class and always extended by another class to use it by overriding required methods. AsyncTask uses three types of parameter i.e Params, Progress, Result. Params parameters are passed to perform background computation. Progress parameters are used to update UI thread. Result parameter is used to display result after background computation. Here we will demo a progress bar update using AsyncTask.

AsyncTask<Params, Progress, Result>

android.os.AsyncTask<Params, Progress, Result> handles UI thread. AsyncTask performs asynchronous task in background and displays result in UI without changing UI thread. We can use AsyncTask for short operations like progress bar or download. AsyncTask uses 3 generic types. Those are given as follows.
1. Params : Type of parameters that are sent to task.
2. Progress : Type of parameters for progress published during background computation.
3. Result : Type of parameter for result of background computation.

AsyncTask uses 4 steps to execute.
1. onPreExecute(): This method is called before task execution on UI thread.
2. doInBackground(Params...): This method is called just after execution of onPreExecute() in background thread.
3. onProgressUpdate(Progress...): This method is called on UI thread after calling publishProgress(Progress...) within the doInBackground(Params...) for any status update like progress bar.
4. onPostExecute(Result): This method is called on UI thread just after completion of doInBackground(Params...) and the result is passed to onPostExecute(Result).

To update UI thread while background computation, we call publishProgress (Progress... values) within doInBackground(Params...) and hence onProgressUpdate(Progress...) is called to update UI thread. To understand types of parameters Params, Progress, Result, find the screenshot.
Android AsyncTask Example with Progress Bar

AsyncTask Example with Progress Bar

In our example we will provide a demo of progress bar which will be updated using AsyncTask.

Create Activity


MainActivity.java
package com.concretepage;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
public class MainActivity extends Activity {
    Button btn;
    private ProgressBar progressBar;
    TextView txt;
    Integer count =1;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        progressBar.setMax(10);
        btn = (Button) findViewById(R.id.btn);
        btn.setText("Start");
    	txt = (TextView) findViewById(R.id.output);
    	OnClickListener listener = new OnClickListener() {
    	    public void onClick(View view) {
    	    	count =1;
    	    	progressBar.setVisibility(View.VISIBLE);
    	    	progressBar.setProgress(0);
    	        switch (view.getId()) {
	    	        case R.id.btn:
	    	            new MyTask().execute(10);
	    	            break;
	       }
    	    }
        };
        btn.setOnClickListener(listener);
    }
    class MyTask extends AsyncTask<Integer, Integer, String> {
        @Override
        protected String doInBackground(Integer... params) {
            for (; count <= params[0]; count++) {
                try {
                    Thread.sleep(1000);
                    publishProgress(count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "Task Completed.";
        }
        @Override
        protected void onPostExecute(String result) {
        	progressBar.setVisibility(View.GONE);
                txt.setText(result);
                btn.setText("Restart");
        }
        @Override
        protected void onPreExecute() {
        	txt.setText("Task Starting...");
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
        	txt.setText("Running..."+ values[0]);
        	progressBar.setProgress(values[0]);
        }
    }
} 

Layout XML


main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:orientation="vertical" 
       android:background="#D1C4E9">
    <ProgressBar
        android:id="@+id/progressBar"
        android:minHeight="20dip"
        android:maxHeight="20dip" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="@android:style/Widget.ProgressBar.Horizontal"/>
    <Button android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="25sp"/>
    <TextView android:id="@+id/output"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="#FF8A80"
        android:textSize="25sp"/>
</LinearLayout> 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.concretepage"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="11"/>
    <application
        android:allowBackup ="false"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity  android:name=".MainActivity" android:theme="@android:style/Theme.NoTitleBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest> 

Output

Android AsyncTask Example with Progress Bar

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us