Showing ProgressDialog while a work in progress ( background process ) using AsyncTask in Android

September 1, 2012
By

In this article, we will see how to show a ProgressDialog while a work is progressing in a non-ui thread ( background ). Here the background process is executing in an AsyncTask object.

This application is developed in Eclipse ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK plugin (R20.0.3 ).


1. Create a new Android application project

Create new Android application Project

Figure 1 : Create new Android application Project


2. Design application launcher icon

Design Application Launcher Icon

Figure 2 : Design Application Launcher Icon


3. Create a blank activity for creating MainActivity class

Create a blank activity

Figure 3 : Create a blank activity


4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details


5. Delete the Android’s Support Library, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.


6. Update the file res/values/strings.xml


<resources>

    <string name="app_name">ProgressDialogDemo</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">ProgressDialog Demo</string>
    <string name="str_btn_start">Start Work</string>

</resources>


7. Update the layout file res/layout/activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/btn_start"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/str_btn_start"
        tools:context=".MainActivity" />
</RelativeLayout>


8. Update the MainActivity class in the file src/in/wptrafficanalyzer/progressdialogdemo/MainActivity.java


package in.wptrafficanalyzer.progressdialogdemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private Button mBtnStart;
    private int mProgressStatus = 0;
    private ProgressDialog mProgressDialog ;
    private ProgressBarAsync mProgressbarAsync;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mBtnStart = (Button) findViewById(R.id.btn_start);

        /** Creating a progress dialog window */
        mProgressDialog = new ProgressDialog(this);

        /** Close the dialog window on pressing back button */
        mProgressDialog.setCancelable(true);

        /** Setting a horizontal style progress bar */
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

        /** Setting a message for this progress dialog
        * Use the method setTitle(), for setting a title
        * for the dialog window
        *  */
        mProgressDialog.setMessage("Work in Progress ...");

        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {

                /** Show the progress dialog window */
                mProgressDialog.show();

                /** Creating an instance of ProgressBarAsync */
                mProgressbarAsync = new ProgressBarAsync();

                /** ProgressBar starts its execution */
                mProgressbarAsync.execute();
            }
        };
        mBtnStart.setOnClickListener(listener);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    private class ProgressBarAsync extends AsyncTask<Void, Integer, Void>{

        /** This callback method is invoked, before starting the background process */
        @Override
            protected void onPreExecute() {
            super.onPreExecute();
            mProgressStatus = 0;
        }

        /** This callback method is invoked on calling execute() method
        * on an instance of this class */
        @Override
        protected Void doInBackground(Void...params) {
            while(mProgressStatus<100){
                try{

                    mProgressStatus++;

                    /** Invokes the callback method onProgressUpdate */
                    publishProgress(mProgressStatus);

                    /** Sleeps this thread for 100ms */
                    Thread.sleep(100);

                }catch(Exception e){
                    Log.d("Exception", e.toString());
                }
            }
            return null;
        }

        /** This callback method is invoked when publishProgress()
        * method is called */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mProgressDialog.setProgress(mProgressStatus);
        }

        /** This callback method is invoked when the background function
        * doInBackground() is executed completely */
        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mProgressDialog.dismiss();
        }
    }
}


9. Screenshot of the application

A work in progress in background using AsyncTask

Figure 5 : A work in progress in background using AsyncTask


10. Download


11. Reference

ttp://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , , , , ,

One Response to Showing ProgressDialog while a work in progress ( background process ) using AsyncTask in Android

  1. Luca Crisi on September 30, 2013 at 8:28 pm

    Hi George.

    Well… what does it do, apart from wasting time with a progress?
    How do you PROGRAMMATICALLY ADVANCE THE PROGRESS?
    This would be more useful…

    So, let’s say I must accomplish several tasks before giving the user the ability to use the main activity.

    At each step I advance a little.

    When I’m finished loading, I set to 100 and it closes, finally allowing me to use the app.

    Thank you
    Best regards.

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner