Android - Periodic sleep based UI updates

   Quite a few applications spawn a background thread or ASyncTask to perform a periodic operation in the background and update the UI accordingly. This makes sense when the when the operation is a database or network based operation but in some cases this is as trivial as a sleep for few seconds like this,


   new Thread( new Runnable() {
         @Override
         public void run() {

              try {
                 Thread.sleep( 1000 );
                 Message msg = mMainThreadHandler.obtainMessage();
                 mMainThreadHandler.postMessage( msg );
              } catch ( Exception e ) {
              }

         }
   }).start();

    The background task in this case is just to post periodic message to the main thread, most likely to update the UI. This is fine but a new thread isn't necessary at all and can be optimized just by using ar Handler's method, sendMessageDelayed.

    The handler for this message could first update the UI and then post another message back to itself with the desired delay. This eliminates the need for another thread altogether. So what happens if the main thread is busy? Well, in that case, the UI can't be updated irrespective of how the message is being posted.

No comments: