Looper in Android

What is Looper?
Looper is a class which is used to execute the Messages(Runnables) in a queue. Normal threads have no any queue. For example, Simple thread do not have any queue. It is one time execution and after end of the code the thread will be stopped and it will not able to run another Message(Runnable).
Where we can use Looper class?
If someone wants to execute multiple messages(Runnables) then he should use the Looper class which is responsible for create a queue in the thread. For example. If we are writing an application which downloads files from the internet then we can use Looper class for put a files in the queue to be download.
How it works?
There is prepare() method to prepare the Looper. Now after that you can use loop() method to create a message loop in the current thread and now your looper is ready to execute the requests in the queue until you quit the loop.
Here is the code by which you can prepare the Looper.
class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }
When should we use Looper?

Most interaction with a message loop is through the Handler class.
Below there is a run method of thread
@Override
    public void run() {
        try {
            // preparing a looper on current thread         
            // the current thread is being detected implicitly
            Looper.prepare();

            Log.i(TAG, "DownloadThread entering the loop");

            // now, the handler will automatically bind to the
            // Looper that is attached to the current thread
            // You don't need to specify the Looper explicitly
            handler = new Handler();

            // After the following line the thread will start
            // running the message loop and will not normally
            // exit the loop unless a problem happens or you
            // quit() the looper (see below)
            Looper.loop();

            Log.i(TAG, "DownloadThread exiting gracefully");
        } catch (Throwable t) {
            Log.e(TAG, "DownloadThread halted due to an error", t);
        } 
    }
 
 
Android Looper is a Java class within the Android user interface that together with the Handler class to process UI events such as button clicks, screen redraws and orientation switches. They may also be used to upload content to an HTTP service, resize images and execute remote requests.
http://developer.android.com/reference/android/os/Looper.html
 


 

Comments

Popular posts from this blog

How to draw an overlay on a SurfaceView used by Camera on Android?

Create EditText with dropdown in android

Android TCP Connection Chat application