0

I have read almost every question related to this topic but they are all perfect until "ending" the thread.

public class LooperThread implements Runnable {

    Handler UI_Handler;
    IncomingHandler handler;


    public LooperThread(Handler ui_handler)
    {
        UI_Handler = ui_handler;
        handler = new IncomingHandler(this);
    }

    public Handler getHandler() {
        return handler;
    }

    public void handleMessage(Message msg)
    {
        int wht = msg.what;
        wht++;
        UI_Handler.obtainMessage(wht).sendToTarget();
        if (wht == 4)
        Looper.myLooper().quit();
    }

    @Override
    public void run() {
        Looper.prepare();
        Looper.loop();
    }

    static class IncomingHandler extends Handler {
        private final WeakReference<LooperThread> mService;

        IncomingHandler(LooperThread lprThread) {
            mService = new WeakReference<>(lprThread);
        }

        @Override
        public void handleMessage(Message msg)
        {
            LooperThread service = mService.get();
            if (service != null) {
                service.handleMessage(msg);
            }
        }
    }
}

here is the code that I tried. And I get "main thread not allowed to quit" message. I just want to quit the thread at some point where a condition is met.

ozgur
  • 2,549
  • 4
  • 25
  • 40
  • 1
    Can you show some code? – ci_ Sep 11 '15 at 21:15
  • @ci_ Edited the question. – ozgur Sep 11 '15 at 21:19
  • And how are you starting the new Thread? You're not showing a Thread at all at this stage, just a Runnable. – ci_ Sep 11 '15 at 21:26
  • @ci_ `LooperThread looperThread = new LooperThread(new UiHandler()); final Handler threadHandler = looperThread.getHandler(); new Thread(looperThread).start();` website says my question is mostly code. That's why I write it here. – ozgur Sep 11 '15 at 21:29
  • You're IncomingHandler is associated with the main Thread, because that's where you create it. – ci_ Sep 11 '15 at 21:39
  • Might be easier to use HandlerThread http://developer.android.com/reference/android/os/HandlerThread.html – ci_ Sep 11 '15 at 21:44
  • @ci_ in that case I still cannot stop the thread. quit method still doesn't work. – ozgur Sep 11 '15 at 22:05
  • You would have to use the handler provided by the HandlerThread, and not create IncomingHandler. – ci_ Sep 11 '15 at 22:07
  • @ci_ how can I get the handler of HandlerThread? There is no method something like getHandler() ? – ozgur Sep 11 '15 at 22:12
  • Sorry, my bad. Use getLooper() and use it when instantiating your Handler. – ci_ Sep 11 '15 at 22:14

0 Answers0