Sunday, April 22, 2012

Showing Progress in a Long Running Process

One of the great things about Android is that there often is several different ways you can implement a specific programming task. Let's say that you want to have some sort of indication that a background process is occurring, for example downloading bootstrap data or posting data to an api or simply displaying a splash screen when the app launches for a few seconds.

Iphone apps use a little spinner icon to denote this.

You could do this as out of box progress bar and there is a DownloadManager api that looks pretty interesting and I'm going to be trying it on my next project. The disadvantage of the progress bar is that phone manufacturers can change the default image associated with it which makes your GUI look different to different users.  

Now another approach would be to use an imageview and Android's animation framework to spin an icon.  Code is below and it's simple. This allows you to customize the spinning icon to your heart's content. On a surf report app I wrote, I spun a surfboard. On a ski report app, I spun a snowflake. On another Find Your Friend app, I actually spun to two little man images one doing a cartwheel to the left of a "LOADING...." textview and one doing a cartwheel to the right of that textview.  You'll see that I'm controlling the visibility of the image view which you set and unset in your asynctask or thread handler.


 <ImageView  
         android:id="@+id/spinnerView"  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:layout_marginTop="12dp"  
         android:visibility="invisible"  
         android:layout_centerHorizontal="true"  
         android:layout_below="@id/logo"  
         android:src="@drawable/loadingimagewhite" />  
  protected void startSpinner()  
   {  
           ImageView iv = (ImageView) findViewById(R.id.spinnerView);  
           iv.setVisibility(View.VISIBLE);  
                Drawable d = getResources().getDrawable(R.drawable.loadingimagewhite);  
             iv.setImageDrawable(d);  
             float width = d.getMinimumWidth() / 2;  
             float height = d.getMinimumHeight() / 2;  
             RotateAnimation a = new RotateAnimation(0, 360, width, height);  
             a.setDuration(3000);  
             a.setRepeatCount(RotateAnimation.INFINITE);  
             a.setInterpolator(new LinearInterpolator());  
             a.setRepeatMode(RotateAnimation.RESTART);  
             iv.startAnimation(a);  
   }  
      protected void stopSpinner()  
   {  
           ImageView iv = (ImageView) findViewById(R.id.spinnerView);  
           iv.setVisibility(View.INVISIBLE);  
        iv.clearAnimation();  
   }