使用Looper.loop()时如何停止线程?

时间:2015-09-11 21:07:09

标签: android multithreading android-looper

我几乎阅读了与此主题相关的所有问题,但它们都是完美的,直到"结束"线程。

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

这是我尝试过的代码。我得到了#34;主线程不允许退出&#34;信息。我只想在符合条件的某个时刻退出线程。

0 个答案:

没有答案