3

I have a Thread with a message-Looper for some Location calculation. For this i call:

LocationManager.requestLocationUpdates(mProvider, mMinTime, mMinDistance, (LocationListener)this, looper);

To get a valid Looper-object I prepare my Thread like this:

    Looper.prepare();
    mLooper = Looper.myLooper();
    handler = [...]
    Looper.loop();

But is it somehow possible to have an additional while-loop for data-processing in the same thread?

Probably I can somehow derive my own Looper and process the messages manually, but how?

Mat
  • 202,337
  • 40
  • 393
  • 406
eL.
  • 311
  • 1
  • 2
  • 15

1 Answers1

0

There is no need for such a thing.

When you call Looper.loop(), the thread runs the message queue of it´s handler. So, any message or post received by the Handler will be processed on the Looper thread.

Like this:

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

    Looper.prepare();

    final Handler h = new Handler();
        final boolean isRunning = true;

        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run()
            {
                //Do stuff like download


                h.post(new Runnable() {

                     @Override
                     public void run() {

                         //Post stuff to Thread t1

                     }
                });

                isRunning = false;
                h.getLooper().quit();
            }
        }

    while(isRunning)
    {
            //This will ensure that the messages sent by the Handler, be called inside the Thread
    Looper.loop();
    }
    }
}   

This way you ensure a Thread keeps running the time needed to respond to the Handler posts and callbacks. You can also extend Handler with your own handleMessage methods and they will also get called inside the Thread t1.

Hope it helps.

Raphael Ayres
  • 864
  • 6
  • 16
  • 1
    Q1: how do you set the final boolean isRunning to false? Q2: How do you set the final boolean isRunning when it is defined within an enclosing type? Q3: how do you use threads without starting them? Q4: how do you handle messages within thread t1 and update variables in thread t2: for example handler receives a "stop running" message, which is handled within the handleMessage method and the endless loop in thread t2 - while(!stopped) - is stopped by setting the stopped boolean of thread t2 to false; ?? I can't get it to work :( – user504342 Nov 16 '13 at 16:25