esoni
esoni

Reputation: 1362

Interrupt looper in a thread

hi mate i have a thread with this code

private final class Consumer extends Thread {

    public boolean running;

    public Handler consumerHandler;

    public void run() {
        Looper.prepare();
        consumerHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.i(LOG_TAG, "Consumer-> " + msg.obj);
            }
        };
        Looper.loop();

    }

}

My activity create a thread T of type Consumer and call start on it. How can the activity stop the thread T ?

Upvotes: 3

Views: 1321

Answers (3)

droid192
droid192

Reputation: 2232

One comment above said Looper does not check for isInterrupted(). I tried to convince mine by calling Thread.interrupt() and adding it inside the loop:

        if (isInterrupted()) {
            socket.close();
            Looper.myLooper().quit();
        } else {
            Looper.loop();
        } 
        //some exit code.

I also called myHandler.sendEmptyMessage(0) to do one loop and catch the interrupt, but no sign of running exit code. On debug the Message did not even arrive at the queue;
Im not sure if excited or not.

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94635

Running message loop will not normally exit the loop unless an exception is thrown or you've call the quit() method. Have a look at DOC - Be sure to call quit() to end the loop.

    @Override
    protected void onDestroy() {
      consumerObj.consumerHandler.quit(); 
      super.onDestroy();
    }

Upvotes: 2

Lawrence Gimenez
Lawrence Gimenez

Reputation: 3237

Try this

if(Consumer != null) {
   Thread thread = Consumer;
   Consumer = null;
   thread.interrupt();
}

or have a condition inside

public void run() {
   while(running) {

   }
}

to stop thread set running = false;

refer here

Upvotes: 0

Related Questions