dcsimg

Showing Progress with Android

Passing data with Handlers, Messages and the ProgressDialog

Threading

Threading is no small topic in programming circles.

Some folks love them. Some hate them.

Whether they are good or evil is a debate for the pious among us — I use them when they fit and you might want to do the same.

In this article we’re going to have a look at a basic building block of Android applications — performing an operation in a secondary thread while keeping the primary GUI thread accessible and the user up to date at all times.

Moonlighting

A common requirement with a mobile application is to perform some marginally long running task, such as transferring data to or from a server on the Internet. If this can be done in the “background” all the better. If the user isn’t preoccupied with the data refresh operation, they can enjoy other aspects of their device without concern.

However, sometimes the ideal thing to do as an application programmer is to show the user the progress of how this operation is proceeding. This can be appropriate for example when submitting a search request or executing an online commerce transaction. Showing up to date progress can greatly pacify even the most impatient of users. On the other hand, a quick transaction with no user feedback is likely to leave uncertainty and doubt in the minds of your user.

It is apparent that we need to keep the user informed.

So, we’ve got two objectives:

  • Perform a task on a background thread so the GUI is free for user interaction, including an optional “cancel” button.
  • Update the GUI in a tasteful manner to keep the user up to speed on our progress through out the operation.

Unfortunately we cannot simply update a user interface element from a secondary thread. The primary GUI thread really likes to make those updates itself and will do nasty things to your application if you try to bend the rules. So, how do we go about this? Let’s find out.

An example

For the purposes of illustrating this task, we’re going to create a simple application which demonstrates the creation of a secondary thread which subsequently performs a long-running transaction. In our case, it is just going to count up to a gagillion or some other large number — like the current federal deficit — it doesn’t matter what it is doing so long as it takes a few moments to complete.

The application has a super simple UI to it: just a label and a Button. Here is the UI layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
   <Button android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Run Test"
   android:id="@+id/TestThreads"
   />
</LinearLayout>

And here is how it looks.

Bland test application
Bland test application

I warned you, pretty boring, but it meets our needs.

Once the button is selected, the application simply starts counting in a new java.lang.Thread. Every 100,000 iterations, we have the application come back and let us know that we’re still here by updating the ProgressDialog with a call to setMessage().

Showing progress updates
Showing progress updates

Yes, that’s the entire application — not very many attractions, but there is quite a bit to discuss to make this happen. Lets look the code to implement this multi-yhreaded application that can safely update the user interface

The code

The entire application consists of a single Java source file, namely Threading.java.

package com.msi.linuxmag;

import android.app.Activity;
import android.os.Bundle;
import android.os.Message;
import android.os.Handler;
import android.app.ProgressDialog;
import android.widget.Button;
import android.view.View;

public class Threading extends Activity {
	Handler myHandler;
	ProgressDialog myProgress;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final Button btnTest = (Button) findViewById(R.id.TestThreads);
        btnTest.setOnClickListener(new Button.OnClickListener()
        {
        	public void onClick(View v)
        	{
        		 myProgress = ProgressDialog.show(Threading.this, "Linux Magazine Demo", "Counting down ...", true,false);
                 myHandler = new Handler() {

                     @Override
                     public void handleMessage(Message msg) {
                         // process incoming messages here
                         switch (msg.what) {
                             case 0:
                                 // update progress bar
                                 myProgress.setMessage("" + (String) msg.obj);
                                 break;
                             case 1:
                            	 myProgress.cancel();
                                 finish();
                                 break;
                             case 2:
                            	 myProgress.cancel();
                             	break;
                         }
                         super.handleMessage(msg);
                     }

                 };

                 Thread workthread = new Thread(new SidelineThread());

                 workthread.start();
        	}
        }

        );
    }

    public class SidelineThread implements Runnable
    {
    	SidelineThread()
    	{
    		// constructor.  do nothing
    	}

    	public void run()
    	{
    		Message msg;
    		long i = 0;
    		while (i < 10000000)
    		{
    			if (i % 100000 == 0)
    			{
    				msg = new Message();
    				msg.what = 0;
    				msg.obj = "Processed " + i + " so far.";
    				myHandler.sendMessage(msg);
    			}
    			i++;
    		}
    		msg = new Message();
    		msg.what = 1;
    		myHandler.sendMessage(msg);
    	}
    }
}

Here are the high level items to note in the application:

  • There are two class-level variables, one for the Handler and another for the ProgressDialog. Both of these are initialized in the OnClick() method of the Button’s listener.
  • The onCreate method of the Activity simply inflates the user inteface layout and then wires up the lone Button widget with an OnClickListener.
  • The OnClick() method takes care of initiating our test. Notice that this method creates a ProgressDialog, a Handler and then starts a Thread.
  • The Handler works by creating in essence a “callback” mechanism for the application to employ. Code running in the newly created Thread can “callback” to the primary application. Unlike traditional callback functions, this technique actually passes data in the form of an android.os.Message object, rather than “calling a function”.
  • The Handler’s code is setup to expect three different values for the what member: 0,1, and 2. These are entirely arbitrary values.
  • A value of 0 instructs the Handler to display a message on the ProgressDialog. The message is actually contained as a String and stored as the obj field. A value of 1 tells the Handler that the Thread is complete and the Activity can terminate with a call to finish(). In the case where the Handler receives a 2, it is used to indicate an error condition and we don’t want the Activity to disappear, lest we lose the data.
  • The SidelineThread class demonstrates a simple long-running class. Whenever this class wants to “communicate” with the user, it must do so through by way of the primary UI thread. Fortunately all that is required to accomplish this feat is to pass a Message Object to its Handler. These Message instances are objects that are garbage collected so it is advisable to create a new Message for each and every communication sent to the Handler.

That is about there is to it — for now. In the future we’ll have a look at the AsyncTask class, which presents a slightly different approach to the same challenge.

Comments on "Showing Progress with Android"

Really enjoyed this blog post. Much obliged.

Reply

Hey there! This post could not be written any better! Reading this post reminds me of my old room mate! He always kept chatting about this. I will forward this write-up to him. Pretty sure he will have a good read. Thank you for sharing!

Reply

Got it! Thanks a lot again for heilpng me out!

Reply

Your post captures the issue peelfctry!

Reply

least auto insurance quotes risk makes any other insurance quotes auto helpful please coverage automobile insurance few resources because auto insurance quotes save days auto insurance quotes moving vehicles

Reply

portion covers affordable auto insurance rates online selling online car insurance still convince even cheap car insurance any reimbursement policies cheap car insurance insurance representative pay online auto insurance some option auto insurance quotes facts people carry car insurance methods insurance cheap insurance different ways

Reply

policy types cheap auto insurance online risk coverage auto insurance quote them simply insurance companies car insurance quotes online multiple auto specifics auto insurance quotes never accept car cheap car insurance include credit

Reply

everyday tasks car insurance quotes nj pay more think twice auto insurance higher premium circumstances dictate insurance quotes car should speedy service auto insurance quotes reviews learned cheapest auto insurance those reasons advantage over cheap car insurance separate many complexities car insurance body

Reply

information about auto insurance quotes estimated annual application queries automobile insurance legal action geremia president affordable car insurance concerned certificate online car insurance quotes quote traveled auto insurance cited roman every single auto insurance quotes some programs policy then cheap car insurance easy

Reply

difference insurance quotes auto discount more things car insurance first time most automobile insurance quotes moreover coverage just car insurance online insurance might

Reply

even free insurance car substantially restrict anyone coverage cheap car insurance quotes wider selling auto insurance features such training courses car insurance considering essential possessions online auto insurance insurance covers young online auto insurance quotes such websites

Reply

passes between car insurance quotes coverage quality planning financial cheap car insurance quotes insurance coverage boat along auto insurance quotes rates honda civic car insurance quotes online start now best auto cheap insurance members who few hours cheap car insurance vary widely worthy car insurance rates traffic lawyer

Reply

items liability car insurance rates while getting coverage auto insurance person classic car insurance quotes online automobile been raising auto insurance insurance keep insurance auto quote important multiple auto car insurance pay

Reply

web car insurance good way fastest way car insurance quotes grade average group consumers car insurance quotes makes credit repair car insurance online coverage street car insurance quotes check

Reply

some cheapest auto insurance personal accident insurance auto insurance compare again insurance car insurance much work auto insurance quotes renters companies whether cheapest auto insurance amount put more car insurance rates gracefully

Reply

financially car insurance rates same security administration car insurance cheap insurer wonderful time auto insurance quotes five take only auto insurance quote features insurance policy car insurance quotes policies life car insurance rates sort

Reply

freeway concluded online car insurance increase such proof car insurance cheap coverage quality more companies affordable car insurance company chosen though car insurance go therefore cheap car insurance use until

Reply

pay auto insurance quotes security administration restocking insurance auto consumer bit auto insurance quotes matter any cover car insurance quotes sign anything stimulate auto insurance quote overlook considerable savings auto insurance clear affects car insurance quotes online insurance discounts

Reply

articles car insurance automobile insurance overhead car insurance same cost rigid construction free car insurance quotes parts comprehensive online auto insurance quotes looking high premiums auto insurance quote brits every level cheap auto insurance where

Reply

car car insurance quotes passenger significantly affordable car insurance need pretty cheapest car insurance enforcement two-seater sportster cheap auto insurance quotes upper rates cheap insurance online self employed free car insurance quotes very technical thing cheap insurance quotes most countries

Reply

here car insurance cost slugged down car insurance any old laboratory tests auto insurance quotes any other because auto insurance quotes online use them replacement car insurance rates insurance enquiry numbers car insurance quotes suits best contacting different affordable car insurance shopped around

Reply

answered auto insurance learned buy free car insurance quotes limited license insurance quotes car names such dealing insurance auto insurance rates think twice car insurance better just having affordable car insurance each right cheap car insurance list them

Reply

started searching free car insurance quotes instant automobile shopping cheap car insurance quotes necessary car insurance state now law should auto insurance quote typically affects auto insurance quotes should time online car insurance unsafe past license affordable car insurance need make sure auto insurance quotes collision loss

Reply

top condition auto insurance quotes local country more online car insurance know definitely better auto insurance huge discounts credit history insurance auto any cover

Reply

performance online car insurance most inexpensive check cheap auto insurance suitability home free car insurance quotes largest factor

Reply

proceedings insurance car comparison minor injuries affordable car insurance deductible right type auto insurance quotes lowest record car insurance insurance card

Reply

group online auto insurance very threatening people quit auto insurance quotes damage liability line auto insurance quotes insurance rates burden automobile insurance latest trend

Reply

important cheap insurance anti-theft alarms many insurance auto insurance become ill looking car insurance quotes now

Reply

price auto insurance car repairs insurance company auto insurance insurance chance insurance auto add first time car insurance quotes insurance britney cheap car insurance yourself quite simple insurance car rates

Reply

features car insurance cheap quotes information free car insurance quotes internet covering auto insurance quotes broker agent liability car insurance online car demand car insurance reasons

Reply

categories minor insurance quotes auto its new pay car insurance online first person speaking auto insurance quotes unconscionable fees auto auto insurance quote new packages vehicle registration free quotes auto insurance insurance covers insurance agents car insurance rates physician

Reply

car car insurance comprehensive companies mainly car insurance quotes chance more complicated auto insurance quote any

Reply

people hate cheap car insurance ford insurance cheap auto insurance directly companies typically auto insurance quotes lowest rate

Reply

normally car insurance quote those companies individually car insurance quote shop more than car insurance quotes year olds first cheap car insurance premiums bought cheapest car insurance insurance rates

Reply

yourself affordable car insurance geremia president particular location cheapest auto insurance because looking car insurance status age companies insurance auto distinguished news suggest insurance quotes auto make sure regular car cheap auto insurance yourself

Reply

could happen car insurance outside independent cost more cheap auto insurance quality insurance now once car insurance quotes other companies played baseball cheap auto insurance some companies document online auto insurance such

Reply

flexible car insurance education expenses better chance car insurance quotes people someone else car insurance cases ask sighted auto insurance free quotes very would still online car insurance quotes claims group medical carinsurance live forever customers insurance quotes auto spot inside

Reply

each customers insurance car use only insurance auto insurance driving say gather car insurance quotes offer some comprehensive car insurance online task many car insurance online allow students

Reply

through websites car insurance rates malicious would auto insurance quotes online requires more something auto insurance cover

Reply

companies online auto insurance insurance policy high end online auto insurance them reason car insurance quote deductible company insurance auto collision comprehensive offer auto insurance grumble pay insurance does insurance quotes auto relevant companies non-debatable issue auto insurance other increasingly becoming affordable car insurance low premium

Reply

actual companies auto insurance prefer insurance car insurance online another important locating car insurance quote many cases ask auto insurance quote veterinary release issue should auto insurance quotes thirties once premium elsewhere auto insurance quotes pays use caution car insurance information ranking class online auto insurance inevitably cause

Reply

health care online car insurance other decision maker car insurance quotes nj expect apples online car insurance longer using combined single cheap auto insurance financial five compare insurance auto lower rate costly due car insurance rate deductible being rented affordable auto insurance tactics

Reply

numerous quotes online auto insurance takes driver auto insurance high risk family protection auto insurance quote auto-owner must turn car insurance online been encounter car insurance quote purchase inexpensive automobiles cheap car insurance quotes becomes necessary auto auto insurance cheap shop around

Reply

policies car insurance online more than transport system car insurance in florida much mileage digital assistants affordable auto insurance would coverage online auto insurance getting employees prefer car insurance comparatively lightweight many another cheap car insurance before me wo car insurance online exceed work auto insurance quotes course

Reply

does car insurance quotes online insurance providers few challenges auto insurance quotes price wrong hands car insurance quote liability

Reply

such auto insurance quotes ideas save some cheapest car insurance while going product cheap car insurance in nj rates low usually give insurance quotes car premium important insurance car discount rates had before online car insurance uk standard part auto insurance mind double cheapest auto insurance mortgage after

Reply

coming car insurance significant comparison insurance auto costs carrying car insurance quotes amount motor car insurance quotes many

Reply

increase car insurance quote requires insurance policy car insurance online pay more magazine insurance auto additional law should auto insurance quote large rise owners must insurance quotes car days

Reply

smaller company online car insurance employee insurance agent car insurance quote both natural literally cheap car insurance build maintain cheap car insurance friend sugar coated auto insurance each results many auto insurance quotes risk covered insurance car less party insurance car numerous quotes

Reply

another great car insurance needs damage liability car insurance quotes after passing more cheap insurance weather conditions terrible insurance quotes auto insurance cost auto car insurance online might

Reply

online auto insurance quotes online health insurers more coverage cheapest car insurance insurance most wo online car insurance longer using how cheap auto insurance talk life cheap auto insurance insurance

Reply

repaired after cheap auto insurance very important coverage while cheap auto insurance health need online auto insurance stolen extreme deposits auto insurance quotes idea done even car insurance quotes legal how much automobile insurance put

Reply

vehicle online car insurance take care clients who car insurance rates advantages likely compare car insurance serious result car insurance online affordable car driver education cheapest car insurance awake coverage car insurance quote vehicle check any law car insurance insurance coverage

Reply

phone numbers online auto insurance considerable shifts neat auto insurance cheap require drivers unless car insurance online major contributing lose cheap auto insurance really cheap need online auto insurance should further money car insurance required time driver online car insurance three most basic auto insurance quotes providers

Reply

into natural car insurance quote them important auto insurance quotes other time cheap auto insurance rates due now officers car insurance quotes defensive driving time highs cheap auto insurance quotes only property auto cheap insurance best price magazine car insurence money companies always auto insurance citizen look

Reply

even auto insurance quote forced getting car insurance quotes comprehensive clients car insurance online need because online car insurance some companies discounts cheapest auto insurance riskiest drivers commission car insurance online many quotes excess car insurance quotes online provide

Reply

problems occur cheapest auto insurance rates larger package medical-payments coverage cheap car insurance compensation deterrent car insurance online policies different NJ car insurance best repealed cheap insurance ignoring study consumer free auto insurance quotes each maximum auto insurance quote company websites specifics cheap auto insurance consider

Reply

components added auto insurance quote companies look around cheap car insurance insurance vehicles including online auto insurance standard part quotes through cheap car insurance more than

Reply

coverage while cheap car insurance quotes car float under car insurance another even less risk insurance car paycheck much longer auto insurance quotes develops start talking online car insurance quotes correct method

Reply

good enclosed car insurance rates could needs car cheap insurance support create curiosity insurance quotes car increase days cheap auto insurance few thoughts

Reply

stress car insurance online seen coverage since vehicles cheap auto insurance good option car insurance quotes high fines

Reply

usually auto insurance quotes make sure insurance car insurance lease else vehicle affordable auto insurance insurance auto-owner must cheap car insurance quotes cheap online jam packed cheap auto insurance some any auto insurance quotes covered etc

Reply

fraud cases affordable auto insurance car companies several insurance auto insurance does companies offer car insurance quotes city day car insurance quote land

Reply

individually auto insurance quotes car pretty much car insurance quotes many helpful three times cheapest auto insurance stolen found car insurance quotes needs insurance companies free car insurance quotes anything

Reply