0

I am learning how to use Looper and Handler class in android development http://developer.android.com/reference/android/os/Looper.html The example given in the android development is not clear to understand what is the usage and the how to use it.I dont know how to add Handler inside the Looper and how I can call the Looper to loop. If it is available, can anyone give me a simple example to use it.

public class LooperTest extends Activity{

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}
private class LooperTesting extends Thread
{
    public Handler handler;
    public void run()
    {
        Looper.prepare();
        handler = new Handler()
        {
            public void handlerMessage(Message msg)
            {
                    // do something
            }
        };
        Looper.loop();

    }
}
}
user1494052
  • 47
  • 1
  • 7

2 Answers2

0

Hope this Links are helps to u

  1. Link1
  2. Link2
  3. Link3
Dixit Patel
  • 3,190
  • 1
  • 24
  • 36
  • These links I have read before but I still not understand how to use it. The main problem is "Do we need to call the LooperTest(Which is on the above question) outside it, like on the onCreate method ?" If not, then how the android know how to call this class and the handler – user1494052 Jan 16 '13 at 05:20
0

In your example you have only defined a Thread with a Looper. You need to start the Thread with the associated Looper before you can post any messages to it. I've added some code to your example to illustrate what has to be done:

public class LooperTest extends Activity{

    LooperTesting mBgThread;

    public void onCreate(Bundle savedInstanceState)
    { 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mBgThread = new mBgThread();

        // Start the thread. When started, it will wait for incoming messages.
        // Use the post* or send* methods of your handler-reference.
        mBgThread.start();
    }

    public void onDestroy() {
        // Don't forget to quit the Looper, so that the
        // thread can finish. 
        mBgThread.handler.getLooper().quit();
    }

    private class LooperTesting extends Thread
    {
        public Handler handler;
        public void run()
        {
            Looper.prepare();
            handler = new Handler()
            {
                public void handlerMessage(Message msg)
                {
                    // do something
                }
            };
            Looper.loop();
        }
    }
}