Wednesday, January 18, 2012

Android Coding - AsyncTask Simple Example

Coming from a C++ background I have found it very insightful to code in Java with Android. I have found that Java lends itself to Object Orientation more readily than C++.  In this case inheriting from Android's AsyncTask Class.

AsyncTask is a way to easily perform asynchronous tasks.  Extremely useful when updating the UI.  In fact, you cannot simply write a For Loop in your base Android code and have it update the UI per each iteration.  It will only update the UI at the end.

My example is simple: take an imageView that has been defined in the main.xml file and update the image that it contains every 500ms after pressing a button.

For this example I assume you have already created the basic structure of your program with an imageView, a button, your images and the structure to allow you to click the button and perform an action.


Call the AsyncTask
This code should go where you are calling your button
// Define the # of iterations to change the image
Integer runLength = new Integer(4);
      
// Link to your imageView in your GUI
imageview1 = (ImageView)findViewById(R.id.imageView1);
      
// Call the AsyncTask
new ChangeGuiImages2().execute(runLength); 
Execute the AsyncTask
This code should go in the same function as the rest of your code (for my example it was directly after the onCreate function)
private class ChangeGuiImages2 extends 
   AsyncTask <integer, boolean integer> {

   // This function performs the task (does not update the UI)
   @Override
   protected Boolean doInBackground(Integer... runLength){
      
      // Make a copy of the runLength Integer
      int l_runLength = runLength[0].intValue();
      
      
      // Run you loop to update the imageView
      for (int i=0; i < l_runLength; i++){
       
         // Log what the function is doing
         Log.d(TAG,"doInBackround"+i);
       
         // Call the progress function, pass the current loop iteration
         Integer progress = new Integer(i);
         publishProgress(progress);
          
         // Sleep for 500ms
         SystemClock.sleep(500);
      }
   return null;    
   }
     
   // This function is used to send progress back 
   //   to the UI during doInBackground
   @Override
   protected void onProgressUpdate(Integer...integers){
      
      // Log what the functions is doing
      Log.d(TAG,"onProgressUpdate:"+integers[0]);
      
      // Create a local copy of the integer 
      int l_integers = integers[0].intValue();
      
      // Set the imageview to the appropriate image based on iteration. 
      //   (sample_0, sample_1, ... etc.)
      imageview1.setImageResource(getResources().getIdentifier(
          "sample_"+l_integers, "drawable", getPackageName()));
   }
     
   // This function is called when doInBackground is done
   @Override
   protected void onPostExecute(Boolean b){
      
      // Log what the functions is doing
      Log.d(TAG,"onPostExecute");
      
   }     
} 

2 comments:

  1. Cool Dan, good to see that you are still "geeking" out, I am interested to see what you're planning to do with the Andriod =)

    I know pretty much nothing about Java besides the little bit that leaks through in Matlab. So is AsynTask like a parallel process or is it more on the lines of a event/callback function

    ReplyDelete
    Replies
    1. Yea man, I am still trying to stay in the EE/CS loop. Definitely do not want to forget my roots now that I am working so far from them.

      I am hoping to write some android apps sometime soon. Of course I have the debate of writing code for fun or writing code for my thesis. A never ending debate I suppose.

      I as well know little about Java so android is forcing me to learn about that as well. It is definitely much easier than C++ for learning/implementing OO though.

      AsyncTask is really a simplification of Java threading. Specifically created by the UI thread to keep the UI thread for performing long operations that would cause the UI to appear to freeze up. Even though it is a separate thread it has some access to the UI thread which is very useful.

      Delete