Thursday, October 18, 2012

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();
      }
  }

No comments:

Post a Comment